Compare commits

...
147 Commits
Author SHA1 Message Date
Mervin Praison c2e33ef6a6 Merge pull request #355 from MervinPraison/develop
Add Image Generation AI Agents with Async Support
2025-01-31 17:26:37 +00:00
MervinPraison 5b2e0a9417 Add Image Generation AI Agents with Async Support
- Introduced new ImageAgent class for generating images using AI models
- Added image generation examples in examples/image/ directory
- Created documentation for image generation feature in docs/features/image-generation.mdx
- Updated package versions to 2.0.61
- Implemented synchronous and asynchronous image generation methods
- Added support for different image models and generation configurations
- Enhanced agent framework with specialized image generation capabilities
2025-01-31 17:26:20 +00:00
Mervin Praison 2f6d9ebcc9 Merge pull request #354 from MervinPraison/develop
Update TypeScript Documentation and Examples with Simplified Agent Wo…
2025-01-31 12:04:54 +00:00
MervinPraison 0610a5b3a4 Update TypeScript Documentation and Examples with Simplified Agent Workflows
- Refactored TypeScript documentation in docs/js/typescript.mdx with simplified code examples
- Updated example scripts in src/praisonai-ts/examples/ with concise, emoji-enhanced workflows
- Simplified multi-agent and single-agent example scripts
- Adjusted task-based agent examples to focus on brevity and creativity
- Updated package version to 1.0.15
- Improved logging and initialization of agents
2025-01-31 12:04:39 +00:00
Mervin Praison 7463744e62 Merge pull request #353 from MervinPraison/develop
Add JavaScript and TypeScript Documentation for PraisonAI SDK
2025-01-31 08:30:18 +00:00
MervinPraison c7428b8282 Add JavaScript and TypeScript Documentation for PraisonAI SDK
- Updated README.md with JavaScript code examples and installation instructions
- Added JavaScript documentation to docs/index.mdx, docs/installation.mdx, docs/introduction.mdx, and docs/quickstart.mdx
- Created new documentation pages for JavaScript, Node.js, and TypeScript in docs/js/
- Added example scripts for single and multi-agent workflows in src/praisonai-ts/examples/
- Updated package version to 1.0.14
- Enhanced PraisonAIAgents class to support auto-generated tasks and improved logging
- Simplified agent initialization and task generation
2025-01-31 08:30:01 +00:00
Mervin Praison ff1deb6b97 Merge pull request #352 from MervinPraison/develop
Update PraisonAI TypeScript SDK with Enhanced Logging, Examples, and …
2025-01-31 07:06:13 +00:00
MervinPraison bdbed2667d Update PraisonAI TypeScript SDK with Enhanced Logging, Examples, and Dependencies
- Upgraded package dependencies and versions
- Added new optional dependencies for enhanced logging and CLI experience
- Implemented PrettyLogger for improved console output
- Updated OpenAI service with more robust error handling and streaming
- Added new example scripts for single, multi-agent, and task-based workflows
- Enhanced logging and debugging capabilities
- Improved agent configuration and initialization
- Added CommonJS example scripts for easier integration
2025-01-31 07:05:56 +00:00
Mervin Praison 2810ec879c Merge pull request #351 from MervinPraison/develop
Add Development and Async TypeScript Documentation for PraisonAI Agen…
2025-01-31 05:31:00 +00:00
MervinPraison 04a8c621bb Add Development and Async TypeScript Documentation for PraisonAI Agents Framework
- Added new documentation pages for development setup and async TypeScript agents
- Updated docs/mint.json to include new navigation entries for JavaScript section
- Added development setup instructions and package structure overview
- Created new documentation for TypeScript async agent workflows
- Simplified and standardized example code across documentation pages
- Updated package version to 1.0.11
2025-01-31 05:30:41 +00:00
Mervin Praison 17cbadaf64 Merge pull request #350 from MervinPraison/develop
Update JavaScript and TypeScript Documentation for PraisonAI Agents F…
2025-01-31 04:55:36 +00:00
MervinPraison fbcdf84350 Update JavaScript and TypeScript Documentation for PraisonAI Agents Framework
- Added new documentation pages for JavaScript, Node.js, and TypeScript in docs/js/
- Updated docs/mint.json to include new navigation entries
- Simplified and standardized example code across documentation pages
- Updated package version to 1.0.8
- Refactored example scripts to use imported PraisonAI package
- Improved documentation structure and code examples for single, multi-agent, and task-based workflows
2025-01-31 04:55:23 +00:00
Mervin Praison ab3295caa1 Merge pull request #349 from MervinPraison/develop
Add TypeScript Examples for PraisonAI Agents SDK
2025-01-30 21:25:54 +00:00
MervinPraison 95517f5007 Add TypeScript Examples for PraisonAI Agents SDK
Expand the PraisonAI TypeScript SDK with comprehensive example scripts demonstrating various agent interaction patterns:

- Added single-agent and multi-agent example scripts
- Implemented chat and task-based agent workflows
- Created examples for parallel and sequential agent processing
- Updated package version to 1.0.7
- Enhanced Agent and PraisonAIAgents classes with improved method signatures
- Added examples covering scenarios like script writing, recipe generation, and research tasks
2025-01-30 21:25:31 +00:00
Mervin Praison 3800825b38 Merge pull request #348 from MervinPraison/develop
Add Node.js AI Agents Framework Documentation
2025-01-30 20:41:21 +00:00
MervinPraison f85e16ab87 Add Node.js AI Agents Framework Documentation
Update documentation to include a comprehensive guide for the PraisonAI Node.js framework:
- Added new JS documentation page in docs/js/js.mdx
- Updated docs/mint.json to include JS navigation and sidebar entry
- Removed praisonai-examples directory, consolidating examples into documentation
- Provided installation, usage, and development setup instructions for the framework
2025-01-30 20:41:00 +00:00
Mervin Praison dbdd3d3d9a Merge pull request #347 from MervinPraison/develop
Add PraisonAI TypeScript AI Agents Framework node.js AI Agents Framework
2025-01-30 20:30:25 +00:00
MervinPraison 1cc5dad01f Add PraisonAI TypeScript Examples and SDK Infrastructure
This commit establishes the TypeScript implementation of the PraisonAI Agents SDK, including:

- Created comprehensive example scripts in `praisonai-examples/`
- Implemented core SDK modules in `praisonai-ts/src/`
- Added multi-agent workflow examples (single, multi-agent, task-based)
- Developed base implementations for agents, tasks, tools, and LLM integration
- Configured TypeScript project with comprehensive package setup
- Implemented ArXiv search and download tools as initial tool example
- Added logging and utility modules for enhanced development experience

The commit provides a foundational TypeScript SDK with modular architecture and example scripts demonstrating agent interactions.
2025-01-30 20:27:33 +00:00
Mervin Praison 3797e4fe25 Merge pull request #346 from MervinPraison/develop
Remove Jupyter notebook agent examples from cookbooks/notebooks/yaml/
2025-01-30 07:04:34 +00:00
MervinPraison d840e7d0ef Remove Jupyter notebook agent examples from cookbooks/notebooks/yaml/
This commit removes a collection of Jupyter notebook files containing agent example implementations across various domains, including:

- Research and analysis
- Writing and creative tasks
- Job and recruitment workflows
- Trip planning
- Social media and content generation
- Search and information retrieval

The removal appears to be part of a broader reorganization of the project's example and cookbook materials, streamlining the repository structure.
2025-01-30 07:04:19 +00:00
Mervin Praison 6f9ca636aa Merge pull request #345 from MervinPraison/develop
Remove multiple Jupyter notebook agent examples from cookbooks
2025-01-30 07:03:19 +00:00
MervinPraison f254d9e290 Remove multiple Jupyter notebook agent examples from cookbooks
This commit removes a large collection of Jupyter notebook files in the `cookbooks/notebooks/` directory that contained various agent example implementations. These notebooks covered a wide range of use cases including:

- Research and analysis agents
- Writing and creative agents
- Job and recruitment agents
- Trip planning agents
- Social media and content generation agents
- Search and information retrieval agents

The removal appears to be part of a broader reorganization of the project's example and cookbook materials.
2025-01-30 07:03:06 +00:00
Mervin Praison 2e95279cd5 Merge pull request #344 from MervinPraison/develop
adding cookbooks
2025-01-30 07:02:19 +00:00
MervinPraison c218ad62ce adding cookbooks 2025-01-30 07:01:39 +00:00
Mervin Praison d10849085d Merge pull request #343 from MervinPraison/develop
adding js sdk
2025-01-30 06:55:13 +00:00
MervinPraison 9594426fc2 Add PraisonAI Agents SDK and Example Scripts
- Initialized PraisonAI Agents SDK project structure in `src/praisonai-agents/`
- Added comprehensive set of example scripts demonstrating agent capabilities
- Included core SDK modules for agents, tasks, tools, knowledge, and LLM integration
- Implemented various agent workflows including:
  - Chain of Thought reasoning
  - Web search
  - Code analysis
  - Memory management
  - Multi-agent coordination
- Created configuration files for development environment setup
- Added sample data and test files for agent interactions

The commit establishes a foundational SDK with diverse agent interaction examples and modular architecture.
2025-01-30 06:54:57 +00:00
MervinPraison 1c6fc71a06 adding js sdk 2025-01-30 06:52:54 +00:00
Mervin Praison d7289acc1d Merge pull request #340 from MervinPraison/develop
Add Hugging Face token export instruction to generate-reasoning docum…
2025-01-29 06:28:13 +00:00
MervinPraison 54a748b4c7 Add Hugging Face token export instruction to generate-reasoning documentation
- Updated docs/features/generate-reasoning.mdx to include HuggingFace token export step
- Expanded environment variable setup instructions for Hugging Face integration
2025-01-29 06:27:49 +00:00
Mervin Praison 9f62e9201a Merge pull request #339 from MervinPraison/develop
2.0.60
2025-01-29 05:59:25 +00:00
MervinPraison 1b69360d9f Bump PraisonAI version to 2.0.60 and update dependencies
- Updated version to 2.0.60 in Homebrew formula, pyproject.toml, and Docker files
- Upgraded praisonaiagents dependency from 0.0.56 to 0.0.60
- Added new documentation for generating reasoning data
- Included example script for chain-of-thought data generation
- Enhanced workflow task management and logging in process modules

The changes improve the framework's version management, documentation, and provide new tools for synthetic reasoning data generation.
2025-01-29 05:58:58 +00:00
MervinPraison 9bdc6545ad Enhance Workflow Task Management with Workflow Finished Flag and Improved Routing
- Added `workflow_finished` flag to `Process` class to enable early workflow termination
- Implemented more robust task routing logic in `process.py` for decision and loop tasks
- Updated task reset mechanism to respect `rerun` parameter
- Improved context clearing and task status management
- Enhanced logging for workflow progression and task transitions

The changes provide more flexible and controlled workflow execution, with better handling of task conditions and early termination scenarios.
2025-01-28 16:40:22 +00:00
MervinPraison 06cd909367 Add max_iter parameter and enhanced workflow task management with fallback mechanism
- Updated `orchestrator-workers.py` to include `max_iter=10` parameter in workflow initialization
- Enhanced `process.py` with a new `_find_next_not_started_task()` method to provide fallback task selection
- Implemented comprehensive logging for workflow cycles, task status, and iteration tracking
- Added retry counter and fallback mechanism to handle scenarios with incomplete or stalled tasks
- Improved workflow termination logic with detailed final summary logging

The changes improve workflow reliability, prevent potential infinite loops, and provide more robust task management in complex multi-agent scenarios.
2025-01-28 11:26:32 +00:00
MervinPraison 67aeece7fc Bump praisonaiagents package version to 0.0.58
- Updated version in `pyproject.toml` and `uv.lock`
- Incremented package version for continued development and improvements
2025-01-27 19:19:40 +00:00
MervinPraison ef67d0753c Enhance Workflow Task Management with Detailed Logging and Loop Task Handling
- Updated `.cursorrules` with comprehensive technical overview of workflow execution challenges
- Refactored `cot-agents.py` to:
  - Add Pydantic model for structured output
  - Improve task description and condition handling
  - Add output validation for chain of thought generation
- Enhanced `process.py` with:
  - Extensive debug logging for task execution
  - Improved loop task and subtask management
  - More detailed logging of task status and progression

The changes improve workflow reliability, provide deeper insights into task execution, and prevent infinite loops in complex task workflows.
2025-01-27 19:18:49 +00:00
MervinPraison f374f9f791 Enhance COT Agent Workflow with Improved Task Management and Logging
- Refactored `cot-agents.py` to include:
  - New `write_csv` and `count_questions` functions
  - Added `TotalQuestionsEvaluator` agent for tracking question count
  - Improved task workflow with decision and loop task types
- Updated `process.py` to support:
  - Enhanced logging for task execution
  - Better handling of loop and decision tasks
  - Improved subtask creation and management
- Modified `csv_tools.py` to support more flexible CSV writing with string input
- Implemented more robust task progression and status tracking

The changes improve the flexibility, logging, and task management of the Chain of Thought agent workflow.
2025-01-27 13:59:59 +00:00
MervinPraison 492fb29af9 Enhance Chain of Thought (COT) agent workflow with batch processing and Hugging Face integration
- Added `cot-agents-batch.py` to support batch processing of Q&A pairs
- Updated `cot-agents.py` with a more comprehensive workflow including:
  - Question generation
  - Chain of Thought solution generation
  - Hugging Face dataset upload
- Refined `generatecot.py` with improvements to solution generation:
  - Reduced max attempts
  - Adjusted scoring thresholds
  - Added direct QA pair tracking

The changes improve the flexibility and automation of Chain of Thought solution generation and dataset management.
2025-01-27 02:52:14 +00:00
MervinPraison cd56ebd5cf Add Chain of Thought (COT) generation tools and update project structure
- Introduced comprehensive `generatecot.py` in `praisonaiagents/tools/train/data/` with advanced Chain of Thought solution generation capabilities
- Added multiple COT-related tools and methods:
  - Solution generation and improvement
  - Answer verification
  - Error detection and correction
  - Export to various formats (JSON, CSV, Alpaca)
  - HuggingFace dataset upload support
- Updated tool mappings in `__init__.py` to include COT-related tools
- Moved existing `generatecot.py` from `train/data/` to `tools/train/data/`
- Bumped project version to 0.0.57 in relevant files

The changes enhance the framework's capabilities for generating and managing step-by-step problem-solving solutions with AI-powered reasoning.
2025-01-26 07:22:32 +00:00
MervinPraison 08e99f6ef7 Enhance GenerateCOT with dictionary-based solution generation and Alpaca format export
- Added new methods to generate solutions in dictionary format:
  - `get_solution_dict()` for step-by-step problem solving
  - `improve_solution_dict()` to refine existing solutions
  - `start_dict()` to generate and validate solutions
- Implemented `export_alpaca_format()` to convert solutions to Alpaca training format
- Updated type hints and added example usage for new methods
- Extended the script with additional QA data processing and export demonstration

The changes improve the flexibility and usability of the GenerateCOT class for solution generation and data preparation.
2025-01-25 08:22:08 +00:00
MervinPraison 670d653ae9 Add GenerateCOT class for step-by-step solution generation and verification
- Created a new Python script `generatecot.py` in the train/data directory
- Implemented a comprehensive solution generation class with features like:
  - Step-by-step problem solving
  - Answer verification
  - Solution improvement
  - Error detection and correction
- Added support for loading and saving solutions with JSON
- Included an example usage demonstrating the class functionality

The GenerateCOT (Chain of Thought) class provides a robust mechanism for generating and refining solutions to various problems using AI-powered reasoning.
2025-01-25 07:47:20 +00:00
Mervin Praison faa014b8b0 Merge pull request #333 from MervinPraison/develop
2.0.59
2025-01-24 17:17:53 +00:00
MervinPraison 6d454d0c6e Update PraisonAI to version 2.0.59 and enhance dependencies
- Bumped PraisonAI version from 2.0.58 to 2.0.59 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonaiagents` dependency version from `0.0.53` to `0.0.56` across relevant files for improved functionality.
- Modified agent task descriptions in `repetitive-agents.py` to clarify expected outputs.
- Enhanced the `process.py` file to improve task handling and expected output management.

These changes aim to refine the PraisonAI framework's capabilities and ensure compatibility with the latest dependencies.
2025-01-24 17:17:32 +00:00
MervinPraison 0ec3fe3510 Add new agent scripts and update version to 0.0.55
- Introduced three new Python scripts: `deepseek-reasoning-output-tokens.py`, `llm-deepseek-reasoning-steps.py`, and `llm-langchain-toolcall.py` to enhance reasoning capabilities and multi-source information retrieval.
- Updated `pyproject.toml` and `uv.lock` to reflect the new version 0.0.55.
- Enhanced `wikipedia-agent.py` to utilize the new `gpt-4o-mini` model for improved performance.
- Improved `agent.py` to support tool calls in chat completions, refining the overall functionality of the agent framework.

These changes aim to expand the capabilities of the PraisonAI framework by integrating new reasoning features and improving user experience with updated versioning.
2025-01-24 13:04:34 +00:00
MervinPraison 707888cdf9 Remove deprecated agent scripts and update version to 0.0.54
- Deleted `any-llm-agents.py` and `any-llm-agents-advanced.py` scripts to streamline the agent framework.
- Updated `pyproject.toml` and `uv.lock` to reflect the new version 0.0.54.
- Enhanced `agent.py` and `llm.py` to improve handling of reasoning steps by ensuring `reasoning_steps` is properly managed in API calls.

These changes aim to simplify the agent framework and improve the overall functionality of the PraisonAI system.
2025-01-24 10:35:42 +00:00
Mervin Praison 42051630bc Merge pull request #331 from MervinPraison/develop
Develop
2025-01-23 17:19:08 +00:00
MervinPraison bfcccb6355 Update PraisonAI to version 2.0.58 and enhance reasoning capabilities
- Bumped PraisonAI version from 2.0.57 to 2.0.58 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonaiagents` dependency version from `0.0.50` to `0.0.53` across relevant files for improved functionality.
- Enhanced reasoning features by modifying agent initialization parameters to use `reasoning_steps` instead of `show_reasoning`, improving clarity in agent behavior.
- Introduced a new script `deepseek-reasoning-multi-agents.py` for multi-agent reasoning tasks, showcasing the integration of reasoning agents.
- Added documentation for new reasoning features, including a detailed guide on creating reasoning extract agents.

These changes aim to refine the reasoning capabilities and improve the overall user experience within the PraisonAI framework.
2025-01-23 17:18:54 +00:00
MervinPraison e329afc394 Refactor reasoning capabilities and update version to 0.0.52
- Removed the `any-llm-think.py` script to streamline the agent framework.
- Enhanced `deepseek-reasoning-agents.py` to include reasoning display options and updated the method for starting agents.
- Updated `pyproject.toml` and `uv.lock` to reflect the new version 0.0.52.
- Improved `agent.py` and `llm.py` to support reasoning content in both synchronous and asynchronous calls, enhancing the overall functionality of the agent framework.

These changes aim to refine the reasoning features and improve the user experience within the PraisonAI framework.
2025-01-23 13:52:58 +00:00
MervinPraison 9417cc6457 Add new reasoning agents and update version to 0.0.51
- Introduced three new Python scripts: `any-llm-think.py`, `deepseek-reasoning-agents.py`, and `deepseek-think.py` for enhanced reasoning capabilities using the `deepseek-reasoner` model.
- Updated `pyproject.toml` and `uv.lock` to reflect the new version 0.0.51.
- Enhanced the `agent.py` file with new data classes and methods to support reasoning content in chat completions, improving the overall functionality of the agent framework.

These changes aim to expand the capabilities of the PraisonAI framework by integrating reasoning features and improving the user experience with updated versioning.
2025-01-23 10:52:15 +00:00
Mervin Praison 10a3d279ae Merge pull request #329 from MervinPraison/develop
Update index.mdx description to enhance clarity and detail
2025-01-23 06:40:49 +00:00
MervinPraison 2a916208e1 Update index.mdx description to enhance clarity and detail
- Revised the description of PraisonAI to emphasize its capabilities as a production-ready Multi-AI Agents framework with self-reflection.
- Highlighted the integration of PraisonAI Agents, AutoGen, and CrewAI as a low-code solution for automating tasks and solving complex challenges.
- Focused on the framework's strengths in simplicity, customization, and effective human-agent collaboration.

These changes aim to provide users with a clearer understanding of PraisonAI's functionalities and benefits.
2025-01-23 06:40:23 +00:00
Mervin Praison bcd0bbbd24 Merge pull request #328 from MervinPraison/develop
Refactor documentation for agent setup and usage
2025-01-23 06:38:06 +00:00
MervinPraison 5701a40f11 Refactor documentation for agent setup and usage
- Updated the introduction.mdx file to streamline the steps for installing the PraisonAI package and configuring the environment.
- Revised agent creation examples to simplify the process for both single and multiple agents, enhancing clarity and usability.
- Added a new section for creating an `agents.yaml` configuration file for no-code users, including automatic generation instructions.
- Improved the overall structure and readability of the documentation to facilitate a better user experience.

These changes aim to provide clearer guidance for users in setting up and utilizing the PraisonAI framework effectively.
2025-01-23 06:37:49 +00:00
Mervin Praison 3ffac395bb Merge pull request #327 from MervinPraison/develop
Update README and documentation with new video tutorials
2025-01-23 06:34:56 +00:00
MervinPraison 37119aa3ac Update README and documentation with new video tutorials
- Removed the License section from README.md to streamline content.
- Added a comprehensive list of video tutorials to docs/index.mdx, covering various AI agent functionalities such as self-reflection, reasoning, and multimodal capabilities.
- Enhanced the documentation's educational resources, providing users with visual aids to better understand the Praison AI framework.

These changes aim to improve user engagement and learning through accessible video content.
2025-01-23 06:34:36 +00:00
Mervin Praison 8b2d324d3b Merge pull request #326 from MervinPraison/develop
Enhance README with new AI agent video resources
2025-01-23 06:30:01 +00:00
MervinPraison 6d0b29e60d Enhance README with new AI agent video resources
- Added multiple new video links to the README.md, showcasing various AI agent functionalities including self-reflection, reasoning, multimodal capabilities, and more.
- Improved the documentation's educational value by providing visual resources for users to better understand the Praison AI framework.

These changes aim to enrich the user experience by offering accessible learning materials related to AI agents.
2025-01-23 06:29:44 +00:00
Mervin Praison 583cbc5efa Merge pull request #325 from MervinPraison/develop
Update documentation and examples for agent initialization and usage
2025-01-23 06:21:43 +00:00
MervinPraison 90dd84a152 Update documentation and examples for agent initialization and usage
- Revised the README.md to reflect the updated method for starting agents, changing `agent.chat` to `agent.start` for clarity and accuracy.
- Added a new section in the README.md for creating an `agents.yaml` file, enhancing the setup instructions for users.
- Updated the installation instructions in `docs/index.mdx` to clarify package names and improve the overall structure of the documentation.
- Streamlined code examples in `docs/concepts/agents.mdx` to focus on single and multiple agent initialization, ensuring users have clear and concise guidance.

These changes improve the clarity and usability of the documentation, making it easier for users to understand and implement the PraisonAI framework.
2025-01-23 06:21:25 +00:00
Mervin Praison ef7fa66e33 Merge pull request #324 from MervinPraison/develop
Update PraisonAI to version 2.0.57 and enhance documentation
2025-01-23 06:06:43 +00:00
MervinPraison 1659ed61bc Update PraisonAI to version 2.0.57 and enhance documentation
- Bumped PraisonAI version from 2.0.56 to 2.0.57 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonaiagents` dependency version from `0.0.49` to `0.0.50` across relevant files for improved functionality.
- Added a new `docker-compose.yml` file and multiple Dockerfiles for different services (UI, chat, development) to streamline deployment.
- Enhanced the README.md with new sections on AI agents flow, tools, memory, and various processing types, improving clarity and usability.
- Introduced a new test script `cl-test.py` for validating chat functionalities with the Gemini API.

These changes improve the overall functionality, usability, and deployment processes of the PraisonAI framework.
2025-01-23 06:06:23 +00:00
Mervin Praison b8939ef439 Merge pull request #323 from MervinPraison/develop
adding chat with pdf
2025-01-22 18:37:48 +00:00
MervinPraison 4bada9e5fc adding chat with pdf 2025-01-22 18:37:27 +00:00
Mervin Praison 51c4cb00b0 Merge pull request #322 from MervinPraison/develop
updating docs
2025-01-22 18:32:20 +00:00
MervinPraison ad96549ea3 updating docs 2025-01-22 18:32:03 +00:00
Mervin Praison 183d10d7cc Merge pull request #321 from MervinPraison/develop
Develop
2025-01-22 18:29:04 +00:00
MervinPraison bce1559ab5 docs update 2025-01-22 18:28:46 +00:00
MervinPraison 6f3fb87ba3 Update README and local development documentation for improved clarity and logging instructions
- Revised section headings in README.md to number the agent categories for better organization.
- Added logging configuration instructions to the local-development.mdx file, detailing how to set log levels for both standard and advanced logging.
- Removed outdated logging instructions from README.md to streamline the documentation.

These changes enhance the clarity of the documentation and provide users with essential logging setup information for local development.
2025-01-22 18:24:24 +00:00
Mervin Praison e7f6b2df67 Merge pull request #320 from MervinPraison/develop
Update README and agent initialization for enhanced clarity and funct…
2025-01-22 18:07:29 +00:00
MervinPraison 08d72eeb80 Update README and agent initialization for enhanced clarity and functionality
- Revised the README.md to better describe PraisonAI as a production-ready Multi-AI Agents framework, emphasizing its capabilities in automating tasks and problem-solving.
- Updated the list of features to include new agent types and functionalities, such as Code Interpreter Agents and Async & Parallel Processing.
- Simplified the agent initialization examples in the README, providing clearer instructions for users to create and run agents.
- Modified the agent client initialization in main.py to handle missing API keys more gracefully.
- Added "developers/local-development" to mint.json for improved documentation structure.

These changes enhance the user experience by providing clearer documentation and improving the robustness of agent initialization.
2025-01-22 18:07:15 +00:00
Mervin Praison 11aefae90f Merge pull request #319 from MervinPraison/develop
Enhance Streamlit UIs and Add New Model Integrations
2025-01-22 13:07:45 +00:00
MervinPraison 10d5158d27 Enhance Streamlit UIs and Add New Model Integrations
- Updated `mint.json` to include new Streamlit UIs for Deepseek, Gemini, and Ollama models, improving model accessibility.
- Expanded documentation in `models.mdx` and `google.mdx` to provide detailed setup instructions for integrating OpenAI, Litellm, and Gemini models.
- Introduced new example scripts for Gemini and Ollama Streamlit applications, showcasing interactive chat capabilities.
- Added comprehensive features and prerequisites sections in the new UI documentation to guide users in setting up their environments.

These changes enhance the usability and functionality of the PraisonAI framework, particularly in model integration and user interface development.
2025-01-22 13:07:31 +00:00
Mervin Praison 1d8b814fcd Merge pull request #318 from MervinPraison/develop
Update PraisonAI to version 2.0.56 and enhance agent functionality
2025-01-22 10:46:35 +00:00
MervinPraison 6e8a5b98a8 Update PraisonAI to version 2.0.56 and enhance agent functionality
- Bumped PraisonAI version from 2.0.55 to 2.0.56 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.46` to `0.0.49` across relevant files for improved functionality.
- Introduced new agent examples for Google Gemini and Deepseek models, enhancing the framework's capabilities.
- Enhanced logging configurations to suppress unnecessary output and improve clarity during execution.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in agent management and logging clarity.
2025-01-22 10:46:18 +00:00
Mervin Praison 59d0ff8c95 Merge pull request #317 from MervinPraison/develop
Refactor deepseek agent implementation and remove unused files
2025-01-21 19:02:39 +00:00
MervinPraison b2109faa06 Refactor deepseek agent implementation and remove unused files
- Simplified the deepseek agent setup by removing the previous configuration and task definitions, replacing them with a more streamlined agent initialization.
- Updated the agent's instructions for clarity and direct usage.
- Deleted the unused `small.pdf` file to clean up the repository.
- Added "deepseek" model to the list of available models in `mint.json` for improved model management.

These changes enhance the usability and clarity of the deepseek agent within the PraisonAI framework.
2025-01-21 19:02:25 +00:00
Mervin Praison 024eaed456 Merge pull request #316 from MervinPraison/develop
Develop
2025-01-21 17:51:15 +00:00
MervinPraison 4fd3a572cf Update PraisonAI to version 2.0.55 and adjust dependencies
- Bumped PraisonAI version from 2.0.54 to 2.0.55 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.45` to `0.0.46` across relevant files for improved functionality.
- Adjusted deployment scripts and documentation to ensure compatibility with the new version.

These changes enhance the overall functionality and usability of the PraisonAI framework, particularly in dependency management and deployment processes.
2025-01-21 17:50:53 +00:00
MervinPraison baaf8b6256 Update version to 0.0.46 and enhance memory feature checks
- Bumped the version of the `praisonaiagents` package from 0.0.45 to 0.0.46 in `pyproject.toml` and `uv.lock` to reflect the latest updates.
- Added import checks for memory features in the `Agent`, `PraisonAIAgents`, and `Task` classes to ensure proper handling of memory dependencies.
- Removed the obsolete `Memory` import from the `__init__.py` file to streamline the codebase.

These changes improve the robustness of the PraisonAI framework by ensuring that memory features are only utilized when the necessary dependencies are installed.
2025-01-21 16:47:31 +00:00
Mervin Praison fe4550d2bc Merge pull request #315 from MervinPraison/develop
2.0.54
2025-01-21 15:01:57 +00:00
MervinPraison db09a94425 Update PraisonAI to version 2.0.54 and enhance agent functionality
- Bumped PraisonAI version from 2.0.53 to 2.0.54 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.44` to `0.0.45` across relevant files for improved functionality.
- Removed the obsolete `knowledge-embedding-agents.py` file and introduced a new `vector-db-agents.py` file to enhance knowledge retrieval capabilities.
- Added new documentation for RAG (Retrieval Augmented Generation) agents, detailing their configuration and usage in `docs/features/rag.mdx`.
- Updated deployment scripts to ensure compatibility with the new version and improved agent functionalities.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in knowledge management and retrieval capabilities.
2025-01-21 15:01:12 +00:00
MervinPraison 2db36dc932 Enhance Knowledge Agent Configuration and Update Version
- Updated the Knowledge Agent configuration to include a new versioning system and improved vector store settings.
- Changed the collection name from "custom_knowledge" to "praison" for consistency across files.
- Added user_id parameter to the Knowledge Agent for better user tracking.
- Enhanced the embedding database configuration to support dynamic context management.
- Bumped the version of the `praisonaiagents` package from 0.0.44 to 0.0.45 in `pyproject.toml` to reflect these updates.

These changes improve the functionality and usability of the Knowledge Agent within the PraisonAI framework, particularly in knowledge management and retrieval capabilities.
2025-01-21 13:09:41 +00:00
Mervin Praison 8c0e4277a4 Merge pull request #313 from MervinPraison/develop
Update PraisonAI to version 2.0.53 and enhance agent functionality
2025-01-20 10:04:38 +00:00
MervinPraison 41448617d5 Update PraisonAI to version 2.0.53 and enhance agent functionality
- Bumped PraisonAI version from 2.0.52 to 2.0.53 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.43` to `0.0.44` across relevant files for improved functionality.
- Enhanced the `PraisonAIAgents` class to include a `max_iter` parameter, allowing for more control over agent iterations.
- Added new tasks to `agents/tasks.csv` to expand the capabilities of the agents in handling various writing tasks.
- Updated documentation to reflect changes in agent functionality and new task examples.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in task execution and agent capabilities.
2025-01-20 10:04:20 +00:00
Mervin Praison 49ea23c676 Merge pull request #312 from MervinPraison/develop
Introducing Repetitive Agents
2025-01-20 07:18:19 +00:00
MervinPraison bb0dc63680 Update PraisonAI to version 2.0.52 and enhance repetitive agents functionality
- Bumped PraisonAI version from 2.0.51 to 2.0.52 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.42` to `0.0.43` across relevant files for improved functionality.
- Introduced new files for repetitive agents in `agents/repetitive-agents.py` and `examples/concepts/repetitive-agents.py`, enabling automated task loops.
- Enhanced documentation with a new section on repetitive agents in `docs/features/repetitive.mdx` and updated `mint.json` to include the new feature.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in handling repetitive tasks and enhancing agent capabilities.
2025-01-20 07:17:43 +00:00
MervinPraison 7774f2c565 Add loop agent functionality and update task management in PraisonAI agents
- Introduced a new loop agent in `loop_agents.py` to create and manage a loop of tasks from a CSV file.
- Added a new file `repetitive-manual-agents.py` that implements task identification, status checking, and updating functionalities.
- Updated `process.py` to enhance task handling by allowing dynamic input files for loop tasks.
- Removed the obsolete `repeat_agents.py` file to streamline the codebase.
- Bumped the version of the `praisonaiagents` package from 0.0.42 to 0.0.43 in `pyproject.toml` and `uv.lock` to reflect these changes.

These updates improve the task execution capabilities of the PraisonAI framework, particularly in handling repetitive tasks and enhancing agent functionality.
2025-01-20 06:56:33 +00:00
MervinPraison 5533fd3476 Enhance logging and improve decision/loop task handling in PraisonAI agents
- Suppressed debug logs from the markdown parser to reduce noise in the logging output.
- Refactored decision-making logic to utilize Pydantic models for better type safety and clarity.
- Updated loop task handling to ensure proper context management and error handling.
- Introduced dynamic literal types for decision and loop tasks to enhance flexibility in task definitions.

These changes improve the overall robustness and usability of the PraisonAI framework, particularly in task execution and logging clarity.
2025-01-19 05:58:46 +00:00
Mervin Praison 262a90a235 Merge pull request #310 from MervinPraison/develop
2.0.51
2025-01-18 06:02:35 +00:00
MervinPraison 60928dcb90 Update PraisonAI to version 2.0.51 and enhance dependencies
- Bumped PraisonAI version from 2.0.50 to 2.0.51 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.41` to `0.0.42` across relevant files for improved functionality.
- Enhanced documentation with updated installation instructions for various examples, ensuring users have access to the latest package versions.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in dependency management and documentation clarity.
2025-01-18 06:02:09 +00:00
MervinPraison c8552e1158 Update PraisonAI agents package version to 0.0.42 in pyproject.toml and uv.lock
- Bumped the version from 0.0.41 to 0.0.42 to reflect recent updates and ensure users have access to the latest features and improvements.
- This change maintains the integrity of the PraisonAI framework and prepares it for future enhancements.
2025-01-18 05:48:57 +00:00
Mervin Praison c57d7db9bb Merge pull request #309 from MervinPraison/develop
Enhance Streamlit UIs for Code Analysis and Hackathon Judging
2025-01-17 22:21:06 +00:00
MervinPraison 236abc2c83 Enhance Streamlit UIs for Code Analysis and Hackathon Judging
- Updated `mint.json` to group Streamlit pages under a new "Streamlit" section, improving organization.
- Renamed titles in `code-analysis.mdx` and `hackathon-judge.mdx` to include "Agent" for clarity.
- Added new Streamlit UI files: `code-analysis-streamlit.mdx` and `hackathon-judge-streamlit.mdx`, providing interactive interfaces for code analysis and hackathon project evaluation.
- Each new UI includes detailed descriptions, features, quick start guides, and visual flowcharts to enhance user experience and understanding.

These changes significantly improve the usability and accessibility of the PraisonAI framework's Streamlit applications, offering users powerful tools for code and project evaluation.
2025-01-17 22:20:51 +00:00
Mervin Praison 76c5f8fe3f Merge pull request #308 from MervinPraison/develop
Add new code analysis and hackathon judge agents with Streamlit integ…
2025-01-17 19:03:12 +00:00
MervinPraison 82750020d2 Add new code analysis and hackathon judge agents with Streamlit integration
- Introduced `code-analysis-agents.py` and `code-analysis-streamlit.py` for comprehensive code evaluation, including metrics on architecture, maintainability, performance, and security.
- Added `context-agents-code.py` and `context-agents.py` for CV analysis capabilities, providing detailed scoring and recommendations.
- Implemented `hackathon-judge-agent.py` and `hackathon-judge-streamlit.py` for evaluating hackathon projects through video demonstrations, offering scores and feedback on innovation, technical complexity, and presentation quality.
- Enhanced documentation with new examples for code analysis and hackathon judging, improving user guidance and showcasing agent capabilities.
- Updated `mint.json` to include new examples, enriching the available resources for users.

These additions significantly expand the functionality of the PraisonAI framework, providing users with powerful tools for code and project evaluation.
2025-01-17 19:02:56 +00:00
Mervin Praison f49ad9fbc2 Merge pull request #306 from MervinPraison/develop
Develop
2025-01-17 17:35:18 +00:00
MervinPraison c086c60fd6 Update PraisonAI to version 2.0.50 and enhance dependencies
- Bumped PraisonAI version from 2.0.49 to 2.0.50 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.40` to `0.0.41` across relevant files for improved functionality.
- Added a new `context-agents.py` file to introduce a CV analysis agent with comprehensive evaluation capabilities.
- Modified deployment scripts to ensure compatibility with the updated package version.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in dependency management and the introduction of new agent capabilities.
2025-01-17 17:35:00 +00:00
MervinPraison 4f8f4f2036 Update package version to 0.0.41 in uv.lock
- Bumped the version of the PraisonAI agents package from 0.0.40 to 0.0.41 to reflect recent updates.
- This change ensures that the latest features and improvements are properly versioned and available for users.
2025-01-17 17:26:51 +00:00
MervinPraison 8e91c20967 Update package version to 0.0.41 in pyproject.toml
- Bumped the version of the PraisonAI agents package from 0.0.40 to 0.0.41 to reflect recent updates.
- This change ensures that the latest features and improvements are properly versioned and available for users.

These updates maintain the integrity of the PraisonAI framework and prepare it for future enhancements.
2025-01-17 17:26:34 +00:00
MervinPraison 6f092c1507 Refactor agent context handling and improve task prompt generation
- Updated `crewai-tools-example.py` to remove unnecessary whitespace.
- Modified `agent.py` to replace `schema_json()` with `model_json_schema()` for JSON output consistency.
- Enhanced context handling in `agents.py` to avoid duplicates and improve clarity in task prompts by using lists instead of strings.
- Added support for passing content to tasks in both `start` and `astart` methods, allowing for dynamic context management.
- Improved task prompt generation in `task.py` to handle various context types, ensuring better output formatting.

These changes enhance the functionality and usability of the PraisonAI agents, particularly in context management and task execution clarity.
2025-01-17 17:25:58 +00:00
Mervin Praison 8f553d3a54 Merge pull request #305 from MervinPraison/develop
2.0.49
2025-01-17 12:24:16 +00:00
MervinPraison 2d647e25b5 Update PraisonAI to version 2.0.49 and enhance dependencies
- Bumped PraisonAI version from 2.0.48 to 2.0.49 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.39` to `0.0.40` across relevant files for improved functionality.
- Modified deployment scripts to ensure compatibility with the updated package version.
- Enhanced documentation by adding a new "Tools" section in `mint.json` and updating the title in `custom.mdx` for better clarity.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in dependency management and documentation clarity.
2025-01-17 12:23:44 +00:00
MervinPraison 039bb772f5 Update version to 0.0.40 and enhance agent functionality
- Bumped the package version in `pyproject.toml` and `uv.lock` from `0.0.39` to `0.0.40` to reflect recent updates.
- Improved the `Agent` class in `agent.py` to support both Langchain and CrewAI tools by adding checks for the presence of `run` and `_run` methods, allowing for more flexible function handling.

These changes enhance the functionality of the PraisonAI agents, ensuring compatibility with different toolsets and improving overall usability.
2025-01-17 12:13:08 +00:00
Mervin Praison 459c2f2b70 Merge pull request #304 from MervinPraison/develop
Add new examples and enhance documentation for AI agent use cases
2025-01-17 10:34:16 +00:00
MervinPraison ee59706357 Add new examples and enhance documentation for AI agent use cases
- Introduced multiple new example files for various AI agent applications, including Climate Impact, Crypto Validator, DeFi Market Maker, Medicine Protocol, Neural Architecture, Quantum Optimiser, Research Assistant, Space Mission, and Vulnerability Detection.
- Updated `mint.json` to include new examples, improving the breadth of use cases available for users.
- Enhanced the `examples.mdx` file to provide links and descriptions for the newly added examples, facilitating easier navigation and understanding of the capabilities of PraisonAI.

These changes significantly expand the documentation and practical examples available to users, showcasing the versatility of the PraisonAI framework in various domains.
2025-01-17 10:33:58 +00:00
Mervin Praison 2a51644773 Merge pull request #303 from MervinPraison/develop
Refactor documentation and enhance quickstart guide for PraisonAI
2025-01-16 11:45:30 +00:00
MervinPraison cce908fa22 Refactor documentation and enhance quickstart guide for PraisonAI
- Removed unnecessary note from the introduction section of `introduction.mdx` for improved clarity.
- Updated the `quickstart.mdx` to provide a more comprehensive and user-friendly guide, including detailed steps for both code and no-code approaches to creating AI agents.
- Enhanced the `knowledge.mdx` file by renaming the vector store from "Chroma" to "Vector DB" for better clarity in terminology.
- Added prerequisites and tips to the quickstart guide to assist users in setting up their environment effectively.

These changes improve the overall usability and clarity of the documentation, making it easier for users to get started with PraisonAI.
2025-01-16 11:45:01 +00:00
Mervin Praison acf476f715 Merge pull request #302 from MervinPraison/develop
Develop
2025-01-16 11:13:41 +00:00
MervinPraison e5d77de79c Update PraisonAI to version 2.0.48 and enhance dependencies
- Bumped PraisonAI version from 2.0.47 to 2.0.48 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Updated the `praisonaiagents` dependency version from `0.0.38` to `0.0.39` across relevant files for improved functionality.
- Modified deployment scripts to ensure compatibility with the updated package version.
- Removed outdated references in documentation and improved clarity in agent-related concepts.

These changes enhance the overall functionality and usability of the PraisonAI framework, particularly in dependency management and deployment processes.
2025-01-16 11:13:22 +00:00
MervinPraison 9ab444b54c Update knowledge agent configuration and versioning
- Changed the knowledge source in `knowledge-agents.py` from `small.pdf` to `large.pdf` to utilize a more comprehensive dataset.
- Bumped the package version in `pyproject.toml` and `uv.lock` from `0.0.38` to `0.0.39` to reflect recent updates.
- Enhanced the `Knowledge` class in `knowledge.py` by adding a progress display for memory storage operations, improving user experience during knowledge updates.

These changes improve the functionality and usability of the knowledge management system within the PraisonAI framework.
2025-01-16 10:14:11 +00:00
Mervin Praison e13f543c6d Merge pull request #301 from MervinPraison/develop
v0.0.38
2025-01-16 08:27:58 +00:00
MervinPraison 4f235d358c Update PraisonAI to version 2.0.47 and enhance knowledge management features
- Bumped PraisonAI version from 2.0.46 to 2.0.47 in `Dockerfile`, `pyproject.toml`, and `uv.lock` to reflect the latest updates.
- Updated the `praisonai.rb` formula to point to the new version's tarball.
- Enhanced the knowledge management system by adding a new `knowledge.mdx` file and related examples for creating knowledge-based agents.
- Updated documentation to include new concepts and improve clarity on knowledge management functionalities.
- Refactored deployment scripts to ensure compatibility with the updated package version.

These changes improve the overall functionality and usability of the PraisonAI framework, particularly in knowledge management and deployment processes.
2025-01-16 08:27:33 +00:00
MervinPraison b7847feb1e Update package version and enhance logging in Knowledge class
- Bumped the package version in `pyproject.toml` and `uv.lock` from `0.0.37` to `0.0.38` to reflect recent changes.
- Modified the `Knowledge` class in `knowledge.py` to include a `verbose` parameter for improved logging control.
- Implemented an internal logging helper method to streamline log messages and manage logging levels based on the `verbose` setting.
- Updated various logging statements to utilize the new logging helper, enhancing clarity and consistency in log outputs.

These changes improve the maintainability and usability of the knowledge management system by providing better logging capabilities.
2025-01-16 08:14:21 +00:00
MervinPraison 7ac730462c Update knowledge agent configuration and enhance memory management
- Changed the knowledge source in `knowledge-agents.py` from `large.pdf` to `small.pdf` for improved testing consistency.
- Bumped the package version in `pyproject.toml` from `0.0.36` to `0.0.37` to reflect recent changes.
- Updated the `chromadb` dependency version in `pyproject.toml` to `0.5.23` for compatibility.
- Enhanced the `CustomMemory` class in `knowledge.py` to allow dynamic memory management without relying on LLM, improving performance and flexibility.
- Introduced cached properties in the `Knowledge` class for better configuration handling and memory management.

These changes improve the knowledge agent's functionality and ensure better performance in memory operations.
2025-01-16 08:07:08 +00:00
MervinPraison 9cbc8d082d Add chunking functionality and update knowledge management features
Knowledge working without lazy loading

- Introduced a new `chunking-direct-test.py` file to demonstrate the usage of the `Chunking` class for text chunking with various strategies.
- Updated `knowledge-agents.py` to change the knowledge source from `2409.13731v3.pdf` to `large.pdf` and modified the agent's query for clarity.
- Revised `knowledge-direct-test.py` to replace the reference to `sample.pdf` with `small.pdf`, ensuring consistency in test file usage.
- Added `knowledge-large-pdf-test.py` to test the handling of large PDF files, integrating logging for better traceability.
- Updated `pyproject.toml` to include the new `chonkie` dependency for chunking functionalities.
- Removed the deprecated `sample.pdf` and added `small.pdf` to the agents directory for testing purposes.
- Enhanced the `Knowledge` class in `knowledge.py` to utilize the new `Chunking` class for improved memory management and content processing.

These changes enhance the knowledge management system's capabilities by integrating chunking strategies and improving file handling processes.
2025-01-16 07:56:32 +00:00
MervinPraison 7fb0aed7ac Refactor memory handling in knowledge-direct-test.py and knowledge.py
- Updated memory retrieval, updating, and deletion methods in `knowledge-direct-test.py` to correctly access memory IDs from the new results structure.
- Enhanced logging to provide clearer information about memory operations, including warnings for unexpected memory formats.
- Modified the `Knowledge` class in `knowledge.py` to ensure all memory results are returned in a consistent format, improving the handling of stored memories.
- Improved error handling and added checks for valid memory formats when verifying stored content from text and PDF files.

These changes enhance the robustness and clarity of memory management within the knowledge management system.
2025-01-16 06:24:15 +00:00
MervinPraison 206f0d01e7 Add new knowledge management features and files
- Introduced a new `knowledge-agents-task.py` script to define and execute tasks for knowledge agents, enhancing the framework's capabilities for knowledge retrieval and management.
- Added `knowledge-agents.py` to create a knowledge agent with specific instructions and knowledge sources, allowing for more tailored interactions.
- Implemented `knowledge-direct-test.py` for testing memory storage and retrieval functionalities, showcasing the new capabilities of the knowledge management system.
- Created `md.py` for handling Markdown file conversions, integrating with the knowledge management features.
- Updated `pyproject.toml` to specify the exact version of the `chromadb` dependency, ensuring compatibility with the new features.
- Added new PDF and DOCX files to the agents directory for testing and demonstration purposes.
- Enhanced the `Knowledge` class in `knowledge.py` to support user and agent identifiers, improving memory management and retrieval processes.

This commit significantly expands the knowledge management functionalities within the PraisonAI framework, providing new tools and scripts for better handling of knowledge content.
2025-01-16 05:36:08 +00:00
MervinPraison e19a310314 Update dependencies and enhance knowledge management system
- Updated the `chainlit` dependency version from `2.0.1` to `2.0.3` across multiple configurations in `pyproject.toml` and `agents/pyproject.toml` to ensure compatibility with the latest features and fixes.
- Introduced a new optional dependency group `knowledge` in `agents/pyproject.toml` for enhanced knowledge management capabilities, including `mem0ai` and `markitdown`.
- Refactored the `Knowledge` class in `knowledge.py` to improve initialization and memory management, allowing for better handling of user and agent identifiers.
- Enhanced methods for storing, retrieving, and managing memories, including new functionalities for updating and deleting memories.
- Updated UI components in `mint.json` and `realtime.py` to reflect changes in model naming conventions, improving user experience and clarity.

This commit strengthens the overall functionality and usability of the PraisonAI framework, particularly in knowledge management and UI interactions.
2025-01-15 17:00:15 +00:00
MervinPraison 1ea572689e Refactor Knowledge Management System in knowledge.py
- Overhauled the `Knowledge` class to enhance the knowledge management system, introducing a more flexible initialization with user and agent identifiers, and improved configuration options.
- Streamlined methods for adding, searching, and deleting knowledge, integrating a new memory management system for better performance and organization.
- Updated vector store and embedding configurations to support a wider range of providers and models, including options for graph capabilities.
- Enhanced error handling and debugging features for improved troubleshooting.
- Removed deprecated methods and optimized existing functionality for clarity and efficiency.

This commit significantly improves the structure and capabilities of the knowledge management system within the PraisonAI framework, facilitating better content handling and retrieval.
2025-01-15 06:52:26 +00:00
MervinPraison 96df649b05 Add Knowledge Management System in knowledge.py
- Introduced a new `Knowledge` class for managing knowledge content, including methods for adding, updating, searching, and deleting knowledge.
- Implemented support for various vector store types (Chroma, Pinecone, PGVector, Qdrant, Milvus) for storing embeddings.
- Added functionality for chunking text, generating embeddings using different models (OpenAI, Cohere, SentenceTransformers, HuggingFace), and optional encryption of content.
- Enhanced caching mechanism for search results to improve performance.
- Included comprehensive error handling and debug mode for better troubleshooting.

This commit establishes a robust framework for knowledge management within the PraisonAI agents, enhancing the system's capabilities for handling and retrieving information efficiently.
2025-01-15 06:18:33 +00:00
Mervin Praison 5aed75837a Merge pull request #300 from MervinPraison/develop
Refactor UI documentation and update navigation structure
2025-01-15 05:18:38 +00:00
MervinPraison 9c8f68a05f Refactor UI documentation and update navigation structure
- Renamed and reorganized the UI documentation in `ui.mdx`, changing the title and sidebar title for clarity.
- Updated the installation instructions to provide a more streamlined setup process.
- Removed the previous table of available interfaces and replaced it with a concise description of features.
- Adjusted the `mint.json` file to reflect the new UI documentation structure, enhancing navigation for users.

This commit improves the clarity and accessibility of the user interface documentation, making it easier for users to understand and utilize the PraisonAI framework.
2025-01-15 05:18:07 +00:00
Mervin Praison 9778a69c4d Merge pull request #299 from MervinPraison/develop
Remove deprecated use case documentation and update navigation structure
2025-01-14 17:12:40 +00:00
MervinPraison 73c7994380 Remove deprecated use case documentation and update navigation structure
- Deleted multiple use case files including "Examples," "Adaptive Learning," "Code Review," "Customer Service," "Emergency Response," "Fraud Detection," "Healthcare Diagnosis," "Multilingual Content," "Predictive Maintenance," "Smart City," and "Supply Chain" to streamline documentation.
- Updated `mint.json` to replace "Use Cases" with "Examples" in the navigation, enhancing clarity and organization.
- Adjusted navigation groups to reflect the new structure, ensuring users can easily find relevant information.

This commit focuses on cleaning up outdated documentation and improving the overall user experience by refining the navigation structure.
2025-01-14 17:12:26 +00:00
Mervin Praison 82b83ded41 Merge pull request #298 from MervinPraison/develop
Update PraisonAI and praisonaiagents to versions 2.0.46 and 0.0.36 re…
2025-01-14 13:47:58 +00:00
MervinPraison fc80db32c2 Update PraisonAI and praisonaiagents to versions 2.0.46 and 0.0.36 respectively
- Bumped the PraisonAI package version from 2.0.45 to 2.0.46 in Dockerfile, pyproject.toml, and related files.
- Updated the installation command in Dockerfile and deployment scripts to reflect the new version.
- Updated the praisonaiagents package version from 0.0.35 to 0.0.36 in relevant files.
- Introduced new agents for data analysis, finance, image processing, and more, enhancing the framework's capabilities.
- Added new example scripts demonstrating the usage of the newly created agents.
- Updated documentation to include new agents and their functionalities, improving user guidance and accessibility.

This commit enhances the overall functionality of the PraisonAI framework while ensuring that all components are up-to-date.
2025-01-14 13:46:43 +00:00
Mervin Praison 3f115ca7ba Merge pull request #297 from MervinPraison/develop
Refactor multimodal agent execution and enhance documentation structure
2025-01-14 09:48:14 +00:00
MervinPraison a32d45e6da Refactor multimodal agent execution and enhance documentation structure
- Simplified the execution of the multimodal agent by removing unnecessary result printing, allowing for a cleaner start method call.
- Updated `mint.json` to include new tabs for "Documentation" and "Use Cases," improving navigation and accessibility of relevant information.
- Added a new "Usecases" group in the navigation section of `mint.json`, detailing various use cases for better user guidance.

This commit streamlines the multimodal agent's functionality and enhances the documentation for improved user experience.
2025-01-14 09:47:50 +00:00
Mervin Praison 8823df26ff Merge pull request #294 from MervinPraison/develop
Add EXASearchTool class and integrate with AI agents
2025-01-13 13:20:26 +00:00
MervinPraison 9c2126fbd6 Add EXASearchTool class and integrate with AI agents
- Introduced a new `EXASearchTool` class to interact with the EXA Search API, allowing AI agents to perform searches and retrieve results.
- Implemented methods for running queries and parsing results into a readable format.
- Created a `SearchAgent` to utilize the `EXASearchTool` for searching information about the 'AI Agents Framework'.
- Added a task definition for the `SearchAgent` to demonstrate the tool's functionality.
- Updated documentation to include the new `tools_class` and provide a comprehensive guide on using class-based tools with AI agents.
2025-01-13 13:20:00 +00:00
Mervin Praison 741b01bdf0 Merge pull request #293 from MervinPraison/develop
Refactor autonomous agent workflow and enhance documentation
2025-01-13 12:25:56 +00:00
MervinPraison 6ed9a69cd8 Refactor autonomous agent workflow and enhance documentation
- Renamed and refactored functions in `autonomous-agent.py` to improve clarity and functionality, including changing `get_environment_feedback` to `get_environment_state`.
- Introduced new agents: `Environment Monitor`, `Action Executor`, and `Feedback Processor` to better structure the workflow.
- Updated task definitions to create a more coherent feedback loop and action execution process.
- Added a `main` function to encapsulate the workflow execution and result printing.
- Updated `mint.json` to include a new "Workflows" group for better organization of documentation.
- Removed the outdated `agenticrouting.mdx` documentation file to streamline content.

This commit enhances the overall structure and readability of the autonomous agent system while improving documentation organization.
2025-01-13 12:24:51 +00:00
Mervin Praison 56a42e6d95 Merge pull request #292 from MervinPraison/develop
Update PraisonAI and praisonaiagents to version 2.0.45 and 0.0.35 res…
2025-01-13 11:49:53 +00:00
MervinPraison d2b4affdd1 Update PraisonAI and praisonaiagents to version 2.0.45 and 0.0.35 respectively
- Bumped the PraisonAI package version from 2.0.44 to 2.0.45 in Dockerfile, pyproject.toml, and related files.
- Updated the installation command in Dockerfile and deployment scripts to reflect the new version.
- Updated the praisonaiagents package version from 0.0.34 to 0.0.35 in relevant files.
- Introduced new evaluator-optimiser and parallelisation features with corresponding agent and task implementations.
- Added documentation for the evaluator-optimiser feature and updated existing documentation for parallelisation.
- Adjusted dependencies in uv.lock for compatibility with the new versions.
2025-01-13 11:49:32 +00:00
Mervin Praison 0d5c8b478f Merge pull request #291 from MervinPraison/develop
Add parallelisation feature and update documentation
2025-01-13 07:52:07 +00:00
MervinPraison fdfad70319 Update PraisonAI and praisonaiagents to version 2.0.44 and 0.0.34 respectively
- Bumped the PraisonAI package version from 2.0.43 to 2.0.44 in Dockerfile, pyproject.toml, and related files.
- Updated the installation command in Dockerfile and deployment scripts to reflect the new version.
- Updated the praisonaiagents package version from 0.0.33 to 0.0.34 in relevant files.
- Adjusted dependencies in uv.lock for compatibility with the new versions.
- Refactored agent definitions in parallelization scripts to remove unnecessary verbosity parameters for cleaner code.
2025-01-13 07:51:14 +00:00
MervinPraison fba6b2e2a0 Add parallelisation feature and update documentation
- Introduced a new `parallelisation.py` file to implement parallel processing using AI agents, allowing concurrent execution of tasks for improved performance.
- Created multiple agents and tasks to demonstrate parallel execution and result aggregation.
- Added a new documentation file `parallelisation.mdx` detailing the setup, usage, and benefits of the parallelisation feature.
- Updated `mint.json` to include the new parallelisation feature for better tracking and visibility.
2025-01-13 07:38:24 +00:00
Mervin Praison f9bfb85f44 Merge pull request #290 from MervinPraison/develop
2.0.43
2025-01-13 07:33:48 +00:00
MervinPraison aab4b5b466 Update PraisonAI to version 2.0.43 and praisonaiagents to version 0.0.33
- Bumped the PraisonAI package version from 2.0.42 to 2.0.43 in Dockerfile, pyproject.toml, and related files.
- Updated the installation command in Dockerfile and deployment scripts to reflect the new version.
- Updated the praisonaiagents package version from 0.0.32 to 0.0.33 in relevant files.
- Modified task descriptions in evaluator-optimizer.py to enhance clarity and functionality.
- Adjusted documentation to ensure consistency with the new version.
- Updated dependencies in uv.lock for compatibility with the new versions.
2025-01-13 07:33:15 +00:00
MervinPraison 7ccadde004 Update praisonaiagents to version 0.0.33 and enhance agent functionality
- Bumped the version of the praisonaiagents package from 0.0.32 to 0.0.33 in pyproject.toml and related files.
- Improved tool availability handling by ensuring tools from both tasks and agents are combined for better execution.
- Enhanced parallel task execution logic to efficiently manage asynchronous tasks within workflows.
- Updated callback execution to handle running event loops more gracefully, improving overall stability and error handling.
- Adjusted dependencies in uv.lock for compatibility with the new version.
2025-01-13 06:36:27 +00:00
Mervin Praison 22a9d5ff23 Merge pull request #287 from MervinPraison/develop
Refactor prompt chaining and update JSON configuration
2025-01-12 07:03:55 +00:00
MervinPraison 98a11209ea Refactor prompt chaining and update JSON configuration
- Simplified import statements in agents/prompt_chaining.py for better readability.
- Updated the condition handling in the initial_task to specify "exit" for odd conditions, clarifying task flow.
- Added "features/promptchaining" to the mint.json configuration, enhancing feature tracking for prompt chaining capabilities.
2025-01-12 07:03:32 +00:00
Mervin Praison df3c97e73a Merge pull request #286 from MervinPraison/develop
Update PraisonAI to version 2.0.42 and praisonaiagents to version 0.0.32
2025-01-12 06:40:44 +00:00
MervinPraison 27808964be Update PraisonAI to version 2.0.42 and praisonaiagents to version 0.0.32
- Updated the PraisonAI package version from 2.0.41 to 2.0.42 in Dockerfile, pyproject.toml, and related files.
- Adjusted installation command in Dockerfile and deploy scripts to reflect the new version.
- Updated the praisonaiagents package version from 0.0.31 to 0.0.32 in relevant files.
- Enhanced the prompt chaining implementation in agents/prompt_chaining.py for improved task management and workflow execution.
- Added new documentation on agentic prompt chaining to guide users in creating complex workflows.
- Updated dependencies in uv.lock for compatibility with the new versions.
2025-01-12 06:40:29 +00:00
Mervin Praison b5daf16e0d Merge pull request #285 from MervinPraison/develop
adding docs
2025-01-11 17:13:14 +00:00
MervinPraison a2cac05d16 adding docs 2025-01-11 17:12:56 +00:00
Mervin Praison ad9828d3bb Merge pull request #284 from MervinPraison/develop
Update PraisonAI to version 2.0.41 and enhance documentation
2025-01-11 16:13:02 +00:00
MervinPraison 85ddf04b47 Update PraisonAI to version 2.0.41 and enhance documentation
- Updated PraisonAI package version from 2.0.40 to 2.0.41 in Dockerfile, pyproject.toml, and related files.
- Adjusted installation command in Dockerfile and deploy scripts to reflect the new version.
- Improved logging in agents_generator.py to handle missing tools.py file gracefully.
- Updated deployment documentation to ensure consistency with the new version.
- Adjusted dependencies in uv.lock for compatibility with the updated PraisonAI version.
2025-01-11 16:12:41 +00:00
475 changed files with 43494 additions and 3883 deletions

No files matched your search

+449 -443
View File
@@ -20,7 +20,7 @@
</div>
PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customisation, and efficient human–agent collaboration.
PraisonAI is a production-ready Multi-AI Agents framework with self-reflection, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. By integrating PraisonAI Agents, AutoGen, and CrewAI into a low-code solution, it streamlines the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
<div align="center">
<a href="https://docs.praison.ai">
@@ -37,35 +37,24 @@ PraisonAI is an AI Agents Framework with Self Reflection. PraisonAI application
- 🧠 Reasoning AI Agents
- 👁️ Multi Modal AI Agents
- 🤝 Multi Agent Collaboration
- ⚡ AI Agent Workflow
- 🔄 Use CrewAI or AutoGen Framework
- 🎭 AI Agent Workflow
- 📚 Add Custom Knowledge
- 🧠 Agents with Short and Long Term Memory
- 📄 Chat with PDF Agents
- 💻 Code Interpreter Agents
- 📚 RAG Agents
- 🤔 Async & Parallel Processing
- 🔄 Auto Agents
- 🔢 Math Agents
- 🎯 Structured Output Agents
- 🔗 LangChain Integrated Agents
- 📞 Callback Agents
- 🤏 Mini AI Agents
- 🛠️ 100+ Custom Tools
- 📄 YAML Configuration
- 💯 100+ LLM Support
- 💻 Chat with ENTIRE Codebase
- 🎨 Interactive UIs
- 📄 YAML-based Configuration
- 🛠️ Custom Tool Integration
- 🔍 Internet Search Capability (using Crawl4AI and Tavily)
- 🖼️ Vision Language Model (VLM) Support
- 🎙️ Real-time Voice Interaction
## Using No Code
### Auto Mode:
```bash
pip install praisonai
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
praisonai --auto create a movie script about Robots in Mars
```
### Initialise Mode:
```bash
pip install praisonai
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
praisonai --init create a movie script about Robots in Mars
praisonai
```
## Using Coding
## Using Python Code
Light weight package dedicated for coding:
```bash
@@ -76,58 +65,13 @@ pip install praisonaiagents
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
### 1. Single Agent
Create app.py file and add the code below:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# 1. Create agents
researcher = Agent(
name="Researcher",
role="Senior Research Analyst",
goal="Uncover cutting-edge developments in AI and data science",
backstory="""You are an expert at a technology research group,
skilled in identifying trends and analyzing complex data.""",
verbose=True,
llm="gpt-4o",
markdown=True
)
writer = Agent(
name="Writer",
role="Tech Content Strategist",
goal="Craft compelling content on tech advancements",
backstory="""You are a content strategist known for
making complex tech topics interesting and easy to understand.""",
llm="gpt-4o",
markdown=True
)
# 2. Define Tasks
task1 = Task(
name="research_task",
description="""Analyze 2024's AI advancements.
Find major trends, new technologies, and their effects.""",
expected_output="""A detailed report on 2024 AI advancements""",
agent=researcher
)
task2 = Task(
name="writing_task",
description="""Create a blog post about major AI advancements using the insights you have.
Make it interesting, clear, and suited for tech enthusiasts.
It should be at least 4 paragraphs long.""",
expected_output="A blog post of at least 4 paragraphs",
agent=writer,
)
agents = PraisonAIAgents(
agents=[researcher, writer],
tasks=[task1, task2],
verbose=False,
process="hierarchical",
manager_llm="gpt-4o"
)
result = agents.start()
from praisonaiagents import Agent
agent = Agent(instructions="Your are a helpful AI assistant")
agent.start("Write a movie script about a robot in Mars")
```
Run:
@@ -135,6 +79,394 @@ Run:
python app.py
```
### 2. Multi Agents
Create app.py file and add the code below:
```python
from praisonaiagents import Agent, PraisonAIAgents
research_agent = Agent(instructions="Research about AI")
summarise_agent = Agent(instructions="Summarise research agent's findings")
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
agents.start()
```
Run:
```bash
python app.py
```
## Using No Code
### Auto Mode:
```bash
pip install praisonai
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
praisonai --auto create a movie script about Robots in Mars
```
## Using JavaScript Code
```bash
npm install praisonai
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
```javascript
const { Agent } = require('praisonai');
const agent = new Agent({ instructions: 'You are a helpful AI assistant' });
agent.start('Write a movie script about a robot in Mars');
```
## AI Agents Flow
```mermaid
graph LR
%% Define the main flow
Start([▶ Start]) --> Agent1
Agent1 --> Process[⚙ Process]
Process --> Agent2
Agent2 --> Output([✓ Output])
Process -.-> Agent1
%% Define subgraphs for agents and their tasks
subgraph Agent1[ ]
Task1[📋 Task]
AgentIcon1[🤖 AI Agent]
Tools1[🔧 Tools]
Task1 --- AgentIcon1
AgentIcon1 --- Tools1
end
subgraph Agent2[ ]
Task2[📋 Task]
AgentIcon2[🤖 AI Agent]
Tools2[🔧 Tools]
Task2 --- AgentIcon2
AgentIcon2 --- Tools2
end
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Start,Output,Task1,Task2 input
class Process,AgentIcon1,AgentIcon2 process
class Tools1,Tools2 tools
class Agent1,Agent2 transparent
```
## AI Agents with Tools
Create AI agents that can use tools to interact with external systems and perform actions.
```mermaid
flowchart TB
subgraph Tools
direction TB
T3[Internet Search]
T1[Code Execution]
T2[Formatting]
end
Input[Input] ---> Agents
subgraph Agents
direction LR
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
Agents ---> Output[Output]
T3 --> A1
T1 --> A2
T2 --> A3
style Tools fill:#189AB4,color:#fff
style Agents fill:#8B0000,color:#fff
style Input fill:#8B0000,color:#fff
style Output fill:#8B0000,color:#fff
```
## AI Agents with Memory
Create AI agents with memory capabilities for maintaining context and information across tasks.
```mermaid
flowchart TB
subgraph Memory
direction TB
STM[Short Term]
LTM[Long Term]
end
subgraph Store
direction TB
DB[(Vector DB)]
end
Input[Input] ---> Agents
subgraph Agents
direction LR
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
Agents ---> Output[Output]
Memory <--> Store
Store <--> A1
Store <--> A2
Store <--> A3
style Memory fill:#189AB4,color:#fff
style Store fill:#2E8B57,color:#fff
style Agents fill:#8B0000,color:#fff
style Input fill:#8B0000,color:#fff
style Output fill:#8B0000,color:#fff
```
## AI Agents with Different Processes
### Sequential Process
The simplest form of task execution where tasks are performed one after another.
```mermaid
graph LR
Input[Input] --> A1
subgraph Agents
direction LR
A1[Agent 1] --> A2[Agent 2] --> A3[Agent 3]
end
A3 --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class A1,A2,A3 process
class Agents transparent
```
### Hierarchical Process
Uses a manager agent to coordinate task execution and agent assignments.
```mermaid
graph TB
Input[Input] --> Manager
subgraph Agents
Manager[Manager Agent]
subgraph Workers
direction LR
W1[Worker 1]
W2[Worker 2]
W3[Worker 3]
end
Manager --> W1
Manager --> W2
Manager --> W3
end
W1 --> Manager
W2 --> Manager
W3 --> Manager
Manager --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Manager,W1,W2,W3 process
class Agents,Workers transparent
```
### Workflow Process
Advanced process type supporting complex task relationships and conditional execution.
```mermaid
graph LR
Input[Input] --> Start
subgraph Workflow
direction LR
Start[Start] --> C1{Condition}
C1 --> |Yes| A1[Agent 1]
C1 --> |No| A2[Agent 2]
A1 --> Join
A2 --> Join
Join --> A3[Agent 3]
end
A3 --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef decision fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Start,A1,A2,A3,Join process
class C1 decision
class Workflow transparent
```
#### Agentic Routing Workflow
Create AI agents that can dynamically route tasks to specialized LLM instances.
```mermaid
flowchart LR
In[In] --> Router[LLM Call Router]
Router --> LLM1[LLM Call 1]
Router --> LLM2[LLM Call 2]
Router --> LLM3[LLM Call 3]
LLM1 --> Out[Out]
LLM2 --> Out
LLM3 --> Out
style In fill:#8B0000,color:#fff
style Router fill:#2E8B57,color:#fff
style LLM1 fill:#2E8B57,color:#fff
style LLM2 fill:#2E8B57,color:#fff
style LLM3 fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
#### Agentic Orchestrator Worker
Create AI agents that orchestrate and distribute tasks among specialized workers.
```mermaid
flowchart LR
In[In] --> Router[LLM Call Router]
Router --> LLM1[LLM Call 1]
Router --> LLM2[LLM Call 2]
Router --> LLM3[LLM Call 3]
LLM1 --> Synthesizer[Synthesizer]
LLM2 --> Synthesizer
LLM3 --> Synthesizer
Synthesizer --> Out[Out]
style In fill:#8B0000,color:#fff
style Router fill:#2E8B57,color:#fff
style LLM1 fill:#2E8B57,color:#fff
style LLM2 fill:#2E8B57,color:#fff
style LLM3 fill:#2E8B57,color:#fff
style Synthesizer fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
#### Agentic Autonomous Workflow
Create AI agents that can autonomously monitor, act, and adapt based on environment feedback.
```mermaid
flowchart LR
Human[Human] <--> LLM[LLM Call]
LLM -->|ACTION| Environment[Environment]
Environment -->|FEEDBACK| LLM
LLM --> Stop[Stop]
style Human fill:#8B0000,color:#fff
style LLM fill:#2E8B57,color:#fff
style Environment fill:#8B0000,color:#fff
style Stop fill:#333,color:#fff
```
#### Agentic Parallelization
Create AI agents that can execute tasks in parallel for improved performance.
```mermaid
flowchart LR
In[In] --> LLM2[LLM Call 2]
In --> LLM1[LLM Call 1]
In --> LLM3[LLM Call 3]
LLM1 --> Aggregator[Aggregator]
LLM2 --> Aggregator
LLM3 --> Aggregator
Aggregator --> Out[Out]
style In fill:#8B0000,color:#fff
style LLM1 fill:#2E8B57,color:#fff
style LLM2 fill:#2E8B57,color:#fff
style LLM3 fill:#2E8B57,color:#fff
style Aggregator fill:#fff,color:#000
style Out fill:#8B0000,color:#fff
```
#### Agentic Prompt Chaining
Create AI agents with sequential prompt chaining for complex workflows.
```mermaid
flowchart LR
In[In] --> LLM1[LLM Call 1] --> Gate{Gate}
Gate -->|Pass| LLM2[LLM Call 2] -->|Output 2| LLM3[LLM Call 3] --> Out[Out]
Gate -->|Fail| Exit[Exit]
style In fill:#8B0000,color:#fff
style LLM1 fill:#2E8B57,color:#fff
style LLM2 fill:#2E8B57,color:#fff
style LLM3 fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
style Exit fill:#8B0000,color:#fff
```
#### Agentic Evaluator Optimizer
Create AI agents that can generate and optimize solutions through iterative feedback.
```mermaid
flowchart LR
In[In] --> Generator[LLM Call Generator]
Generator -->|SOLUTION| Evaluator[LLM Call Evaluator] -->|ACCEPTED| Out[Out]
Evaluator -->|REJECTED + FEEDBACK| Generator
style In fill:#8B0000,color:#fff
style Generator fill:#2E8B57,color:#fff
style Evaluator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
#### Repetitive Agents
Create AI agents that can efficiently handle repetitive tasks through automated loops.
```mermaid
flowchart LR
In[Input] --> LoopAgent[("Looping Agent")]
LoopAgent --> Task[Task]
Task --> |Next iteration| LoopAgent
Task --> |Done| Out[Output]
style In fill:#8B0000,color:#fff
style LoopAgent fill:#2E8B57,color:#fff,shape:circle
style Task fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## Adding Models
<div align="center">
<a href="https://docs.praison.ai/models">
<p align="center">
<img src="https://img.shields.io/badge/%F0%9F%93%9A_Models-Visit_docs.praison.ai-blue?style=for-the-badge&logo=bookstack&logoColor=white" alt="Models" />
</p>
</a>
</div>
## Ollama Integration
```bash
export OPENAI_BASE_URL=http://localhost:11434/v1
@@ -147,267 +479,16 @@ export OPENAI_API_KEY=xxxxxxxxxxx
export OPENAI_BASE_URL=https://api.groq.com/openai/v1
```
## Logging
```bash
export LOGLEVEL=info
```
Advanced logging:
```bash
export LOGLEVEL=debug
```
<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/images/architecture-dark.png" />
<source media="(prefers-color-scheme: light)" srcset="docs/images/architecture-light.png" />
<img alt="PraisonAI Architecture" src="docs/images/architecture-light.png" />
</picture>
</div>
## Different User Interfaces:
| Interface | Description | URL |
|---|---|---|
| **UI** | Multi Agents such as CrewAI or AutoGen | [https://docs.praison.ai/ui/ui](https://docs.praison.ai/ui/ui) |
| **Chat** | Chat with 100+ LLMs, single AI Agent | [https://docs.praison.ai/ui/chat](https://docs.praison.ai/ui/chat) |
| **Code** | Chat with entire Codebase, single AI Agent | [https://docs.praison.ai/ui/code](https://docs.praison.ai/ui/code) |
| **Realtime** | Real-time voice interaction with AI | [https://docs.praison.ai/ui/realtime](https://docs.praison.ai/ui/realtime) |
| Other Features | Description | Docs |
|---|---|---|
| **Train** | Fine-tune LLMs using your custom data | [https://docs.praison.ai/train](https://docs.praison.ai/train) |
## Google Colab Multi Agents
| | Cookbook | Open in Colab |
| ------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Basic | PraisonAI | <a target="_blank" href="https://colab.research.google.com/github/MervinPraison/PraisonAI/blob/main/cookbooks/praisonai-googlecolab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" /></a> |
| Include Tools | PraisonAI Tools | <a target="_blank" href="https://colab.research.google.com/github/MervinPraison/PraisonAI/blob/main/cookbooks/praisonai-tools-googlecolab.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" /></a> |
## Installation Options
### Using pip
```bash
pip install praisonai
```
### Framework-specific Installation
```bash
# Install with CrewAI support
pip install "praisonai[crewai]"
# Install with AutoGen support
pip install "praisonai[autogen]"
# Install with both frameworks
pip install "praisonai[crewai,autogen]"
```
### UI and Additional Features
```bash
# Install UI support
pip install "praisonai[ui]"
# Install Chat interface
pip install "praisonai[chat]"
# Install Code interface
pip install "praisonai[code]"
# Install Realtime voice interaction
pip install "praisonai[realtime]"
# Install Call feature
pip install "praisonai[call]"
```
## Quick Start
```bash
# Set your OpenAI API key
export OPENAI_API_KEY="Enter your API key"
# Initialize with CrewAI (default)
praisonai --init "create a movie script about dog in moon"
# Or initialize with AutoGen
praisonai --framework autogen --init "create a movie script about dog in moon"
# Run the agents
praisonai
```
## Full Automatic Mode
```bash
# With CrewAI (default)
praisonai --auto "create a movie script about Dog in Moon"
# With AutoGen
praisonai --framework autogen --auto "create a movie script about Dog in Moon"
```
## Framework-specific Features
### CrewAI
When installing with `pip install "praisonai[crewai]"`, you get:
- CrewAI framework support
- PraisonAI tools integration
- Task delegation capabilities
- Sequential and parallel task execution
### AutoGen
When installing with `pip install "praisonai[autogen]"`, you get:
- AutoGen framework support
- PraisonAI tools integration
- Multi-agent conversation capabilities
- Code execution environment
## TL;DR Multi Agents
```bash
pip install praisonai
export OPENAI_API_KEY="Enter your API key"
praisonai --init create a movie script about dog in moon
praisonai
```
## Table of Contents
- [Installation](#installation)
- [Initialise](#initialise)
- [Run](#run)
- [Full Automatic Mode](#full-automatic-mode)
- [User Interface](#user-interface)
- [Praison AI Chat](#praison-ai-chat)
- [Create Custom Tools](#create-custom-tools)
- [Agents Playbook](#agents-playbook)
- [Include praisonai package in your project](#include-praisonai-package-in-your-project)
- [Commands to Install Dev Dependencies](#commands-to-install-dependencies)
- [Other Models](#other-models)
- [Contributing](#contributing)
- [Star History](#star-history)
## Installation Multi Agents
```bash
pip install praisonai
```
## Initialise
```bash
export OPENAI_API_KEY="Enter your API key"
```
Generate your OPENAI API KEY from here: https://platform.openai.com/api-keys
Note: You can use other providers such as Ollama, Mistral ... etc. Details are provided at the bottom.
```bash
praisonai --init create a movie script about dog in moon
```
This will automatically create agents.yaml file in the current directory.
### To initialise with a specific agent framework (Optional):
```bash
praisonai --framework autogen --init create movie script about cat in mars
```
## Run
```bash
praisonai
```
or
```bash
python -m praisonai
```
### Specify the agent framework (Optional):
```bash
praisonai --framework autogen
```
### Full Automatic Mode
```bash
praisonai --auto create a movie script about Dog in Moon
```
## User Interface
## PraisonAI User Interfaces:
| Interface | Description | URL |
| --------- | ------------------------------------------ | --------------------------------------------------------------------- |
| **UI** | Multi Agents such as CrewAI or AutoGen | [https://docs.praisonai.com/ui/ui](https://docs.praison.ai/ui/ui) |
| **Chat** | Chat with 100+ LLMs, single AI Agent | [https://docs.praisonai.com/ui/chat](https://docs.praison.ai/ui/chat) |
| **Code** | Chat with entire Codebase, single AI Agent | [https://docs.praisonai.com/ui/code](https://docs.praison.ai/ui/code) |
```bash
pip install -U "praisonai[ui]"
export OPENAI_API_KEY="Enter your API key"
chainlit create-secret
export CHAINLIT_AUTH_SECRET=xxxxxxxx
praisonai ui
```
or
```
python -m praisonai ui
```
## Praison AI Chat
- https://docs.praison.ai/chat/
```bash
pip install "praisonai[chat]"
export OPENAI_API_KEY="Enter your API key"
praisonai chat
```
### Internet Search
Praison AI Chat and Praison AI Code now includes internet search capabilities using Crawl4AI and Tavily, allowing you to retrieve up-to-date information during your conversations.
### Vision Language Model Support
You can now upload images and ask questions based on them using Vision Language Models. This feature enables visual understanding and analysis within your chat sessions.
## Praison AI Code
```bash
pip install "praisonai[code]"
export OPENAI_API_KEY="Enter your API key"
praisonai code
```
### Internet Search
Praison AI Code also includes internet search functionality, enabling you to find relevant code snippets and programming information online.
## Create Custom Tools
- https://docs.praison.ai/tools/custom/
## No Code Options
## Agents Playbook
### Simple Playbook Example
Create `agents.yaml` file and add the code below:
```yaml
framework: crewai
framework: praisonai
topic: Artificial Intelligence
roles:
screenwriter:
@@ -420,62 +501,25 @@ roles:
expected_output: "Complete script ready for production."
```
*To run the playbook:*
```bash
praisonai agents.yaml
```
## Use 100+ Models
- https://docs.praison.ai/models/
<div align="center">
<a href="https://docs.praison.ai">
<p align="center">
<img src="https://img.shields.io/badge/📚_Documentation-Visit_docs.praison.ai-blue?style=for-the-badge&logo=bookstack&logoColor=white" alt="Documentation" />
</p>
</a>
</div>
## Include praisonai package in your project
## Development:
- https://docs.praison.ai/developers/wrapper
- https://docs.praison.ai/developers/wrapper-tools/
## Option 1: Using RAW YAML
```python
from praisonai import PraisonAI
# Example agent_yaml content
agent_yaml = """
framework: "crewai"
topic: "Space Exploration"
roles:
astronomer:
role: "Space Researcher"
goal: "Discover new insights about {topic}"
backstory: "You are a curious and dedicated astronomer with a passion for unraveling the mysteries of the cosmos."
tasks:
investigate_exoplanets:
description: "Research and compile information about exoplanets discovered in the last decade."
expected_output: "A summarized report on exoplanet discoveries, including their size, potential habitability, and distance from Earth."
"""
# Create a PraisonAI instance with the agent_yaml content
praisonai = PraisonAI(agent_yaml=agent_yaml)
# Run PraisonAI
result = praisonai.run()
# Print the result
print(result)
```
## Option 2: Using separate agents.yaml file
Note: Please create agents.yaml file before hand.
```python
from praisonai import PraisonAI
def basic(): # Basic Mode
praisonai = PraisonAI(agent_file="agents.yaml")
praisonai.run()
if __name__ == "__main__":
basic()
```
## Commands to Install Dependencies:
Below is used for development only.
### Using uv
```bash
@@ -500,18 +544,34 @@ uv pip install -r pyproject.toml --extra "crewai,autogen"
- Submit a pull request via GitHub's web interface.
- Await feedback from project maintainers.
## Other Features
- 🔄 Use CrewAI or AutoGen Framework
- 💻 Chat with ENTIRE Codebase
- 🎨 Interactive UIs
- 📄 YAML-based Configuration
- 🛠️ Custom Tool Integration
- 🔍 Internet Search Capability (using Crawl4AI and Tavily)
- 🖼️ Vision Language Model (VLM) Support
- 🎙️ Real-time Voice Interaction
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=MervinPraison/PraisonAI&type=Date)](https://docs.praison.ai)
## License
Praison AI is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
## Video Tutorials
| Topic | Video |
|-------|--------|
| AI Agents with Self Reflection | [![Self Reflection](https://img.youtube.com/vi/vLXobEN2Vc8/0.jpg)](https://www.youtube.com/watch?v=vLXobEN2Vc8) |
| Reasoning Data Generating Agent | [![Reasoning Data](https://img.youtube.com/vi/fUT332Y2zA8/0.jpg)](https://www.youtube.com/watch?v=fUT332Y2zA8) |
| AI Agents with Reasoning | [![Reasoning](https://img.youtube.com/vi/KNDVWGN3TpM/0.jpg)](https://www.youtube.com/watch?v=KNDVWGN3TpM) |
| Multimodal AI Agents | [![Multimodal](https://img.youtube.com/vi/hjAWmUT1qqY/0.jpg)](https://www.youtube.com/watch?v=hjAWmUT1qqY) |
| AI Agents Workflow | [![Workflow](https://img.youtube.com/vi/yWTH44QPl2A/0.jpg)](https://www.youtube.com/watch?v=yWTH44QPl2A) |
| Async AI Agents | [![Async](https://img.youtube.com/vi/VhVQfgo00LE/0.jpg)](https://www.youtube.com/watch?v=VhVQfgo00LE) |
| Mini AI Agents | [![Mini](https://img.youtube.com/vi/OkvYp5aAGSg/0.jpg)](https://www.youtube.com/watch?v=OkvYp5aAGSg) |
| AI Agents with Memory | [![Memory](https://img.youtube.com/vi/1hVfVxvPnnQ/0.jpg)](https://www.youtube.com/watch?v=1hVfVxvPnnQ) |
| Repetitive Agents | [![Repetitive](https://img.youtube.com/vi/dAYGxsjDOPg/0.jpg)](https://www.youtube.com/watch?v=dAYGxsjDOPg) |
| Introduction | [![Introduction](https://img.youtube.com/vi/Fn1lQjC0GO0/0.jpg)](https://www.youtube.com/watch?v=Fn1lQjC0GO0) |
| Tools Overview | [![Tools Overview](https://img.youtube.com/vi/XaQRgRpV7jo/0.jpg)](https://www.youtube.com/watch?v=XaQRgRpV7jo) |
| Custom Tools | [![Custom Tools](https://img.youtube.com/vi/JSU2Rndh06c/0.jpg)](https://www.youtube.com/watch?v=JSU2Rndh06c) |
@@ -524,59 +584,5 @@ Praison AI is an open-sourced software licensed under the **[MIT license](https:
| Training | [![Training](https://img.youtube.com/vi/aLawE8kwCrI/0.jpg)](https://www.youtube.com/watch?v=aLawE8kwCrI) |
| Realtime Voice Interface | [![Realtime](https://img.youtube.com/vi/frRHfevTCSw/0.jpg)](https://www.youtube.com/watch?v=frRHfevTCSw) |
| Call Interface | [![Call](https://img.youtube.com/vi/m1cwrUG2iAk/0.jpg)](https://www.youtube.com/watch?v=m1cwrUG2iAk) |
| Reasoning Extract Agents | [![Reasoning Extract](https://img.youtube.com/vi/2PPamsADjJA/0.jpg)](https://www.youtube.com/watch?v=2PPamsADjJA) |
## License
Praison AI is an open-sourced software licensed under the **[MIT license](https://opensource.org/licenses/MIT)**.
## Local Docker Development with Live Reload
To facilitate local development with live reload, you can use Docker. Follow the steps below:
1. **Create a `Dockerfile.dev`**:
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.18 watchdog
EXPOSE 5555
ENV FLASK_ENV=development
CMD ["flask", "run", "--host=0.0.0.0"]
```
2. **Create a `docker-compose.yml`**:
```yaml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
volumes:
- .:/app
ports:
- "5555:5555"
environment:
FLASK_ENV: development
command: flask run --host=0.0.0.0
watch:
image: alpine:latest
volumes:
- .:/app
command: sh -c "apk add --no-cache inotify-tools && while inotifywait -r -e modify,create,delete /app; do kill -HUP 1; done"
```
3. **Run Docker Compose**:
```bash
docker-compose up
```
This setup will allow you to develop locally with live reload, making it easier to test and iterate on your code.
-8
View File
@@ -1,8 +0,0 @@
1. Make minimal code changes as possible
2. if you are creating function, make sure to name it in more easy, user friendly , optimised manner.
3. Never copy the exact code if presented with a code from other location or file or codebase, just make it optimised
4. Always Follow the principle LESS IS MORE
5. Make it minimal change as possible
6. Firstly try not to make any modification to the existing code as possible
7. Only modify the existing code if its highly required, without that if it cant be done, then add new code section.
8. If you are adding new code, make sure to add it in a way that it can be easily integrated with the existing codebase.
-4
View File
@@ -1,4 +0,0 @@
"""Agent module for AI agents"""
from .agent import Agent
__all__ = ['Agent']
-764
View File
@@ -1,764 +0,0 @@
import os
import time
import json
import logging
import asyncio
from typing import List, Optional, Any, Dict, Union, Literal, TYPE_CHECKING
from rich.console import Console
from rich.live import Live
from openai import AsyncOpenAI
from ..main import (
display_error,
display_tool_call,
display_instruction,
display_interaction,
display_generating,
display_self_reflection,
ReflectionOutput,
client,
error_logs
)
import inspect
if TYPE_CHECKING:
from ..task.task import Task
class Agent:
def _generate_tool_definition(self, function_name):
"""
Generate a tool definition from a function name by inspecting the function.
"""
logging.debug(f"Attempting to generate tool definition for: {function_name}")
# First try to get the tool definition if it exists
tool_def_name = f"{function_name}_definition"
tool_def = globals().get(tool_def_name)
logging.debug(f"Looking for {tool_def_name} in globals: {tool_def is not None}")
if not tool_def:
import __main__
tool_def = getattr(__main__, tool_def_name, None)
logging.debug(f"Looking for {tool_def_name} in __main__: {tool_def is not None}")
if tool_def:
logging.debug(f"Found tool definition: {tool_def}")
return tool_def
# Try to find the function in the agent's tools list first
func = None
for tool in self.tools:
if callable(tool) and getattr(tool, '__name__', '') == function_name:
func = tool
break
logging.debug(f"Looking for {function_name} in agent tools: {func is not None}")
# If not found in tools, try globals and main
if not func:
func = globals().get(function_name)
logging.debug(f"Looking for {function_name} in globals: {func is not None}")
if not func:
import __main__
func = getattr(__main__, function_name, None)
logging.debug(f"Looking for {function_name} in __main__: {func is not None}")
if not func or not callable(func):
logging.debug(f"Function {function_name} not found or not callable")
return None
import inspect
# Langchain tools
if inspect.isclass(func) and hasattr(func, 'run'):
original_func = func
func = func.run
function_name = original_func.__name__
sig = inspect.signature(func)
logging.debug(f"Function signature: {sig}")
# Skip self, *args, **kwargs, so they don't get passed in arguments
parameters_list = []
for name, param in sig.parameters.items():
if name == "self":
continue
if param.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):
continue
parameters_list.append((name, param))
parameters = {
"type": "object",
"properties": {},
"required": []
}
# Parse docstring for parameter descriptions
docstring = inspect.getdoc(func)
logging.debug(f"Function docstring: {docstring}")
param_descriptions = {}
if docstring:
import re
param_section = re.split(r'\s*Args:\s*', docstring)
logging.debug(f"Param section split: {param_section}")
if len(param_section) > 1:
param_lines = param_section[1].split('\n')
for line in param_lines:
line = line.strip()
if line and ':' in line:
param_name, param_desc = line.split(':', 1)
param_descriptions[param_name.strip()] = param_desc.strip()
logging.debug(f"Parameter descriptions: {param_descriptions}")
for name, param in parameters_list:
param_type = "string" # Default type
if param.annotation != inspect.Parameter.empty:
if param.annotation == int:
param_type = "integer"
elif param.annotation == float:
param_type = "number"
elif param.annotation == bool:
param_type = "boolean"
elif param.annotation == list:
param_type = "array"
elif param.annotation == dict:
param_type = "object"
param_info = {"type": param_type}
if name in param_descriptions:
param_info["description"] = param_descriptions[name]
parameters["properties"][name] = param_info
if param.default == inspect.Parameter.empty:
parameters["required"].append(name)
logging.debug(f"Generated parameters: {parameters}")
# Extract description from docstring
description = docstring.split('\n')[0] if docstring else f"Function {function_name}"
tool_def = {
"type": "function",
"function": {
"name": function_name,
"description": description,
"parameters": parameters
}
}
logging.debug(f"Generated tool definition: {tool_def}")
return tool_def
def __init__(
self,
name: Optional[str] = None,
role: Optional[str] = None,
goal: Optional[str] = None,
backstory: Optional[str] = None,
instructions: Optional[str] = None,
llm: Optional[Union[str, Any]] = None,
tools: Optional[List[Any]] = None,
function_calling_llm: Optional[Any] = None,
max_iter: int = 20,
max_rpm: Optional[int] = None,
max_execution_time: Optional[int] = None,
memory: Optional[Any] = None,
verbose: bool = True,
allow_delegation: bool = False,
step_callback: Optional[Any] = None,
cache: bool = True,
system_template: Optional[str] = None,
prompt_template: Optional[str] = None,
response_template: Optional[str] = None,
allow_code_execution: Optional[bool] = False,
max_retry_limit: int = 2,
respect_context_window: bool = True,
code_execution_mode: Literal["safe", "unsafe"] = "safe",
embedder_config: Optional[Dict[str, Any]] = None,
knowledge_sources: Optional[List[Any]] = None,
use_system_prompt: Optional[bool] = True,
markdown: bool = True,
self_reflect: bool = False,
max_reflect: int = 3,
min_reflect: int = 1,
reflect_llm: Optional[str] = None
):
# Handle backward compatibility for required fields
if all(x is None for x in [name, role, goal, backstory, instructions]):
raise ValueError("At least one of name, role, goal, backstory, or instructions must be provided")
# If instructions are provided, use them to set role, goal, and backstory
if instructions:
self.name = name or "Agent"
self.role = role or "Assistant"
self.goal = goal or instructions
self.backstory = backstory or instructions
# Set self_reflect to False by default for instruction-based agents
self.self_reflect = False if self_reflect is None else self_reflect
else:
# Use provided values or defaults
self.name = name or "Agent"
self.role = role or "Assistant"
self.goal = goal or "Help the user with their tasks"
self.backstory = backstory or "I am an AI assistant"
# Default to True for traditional agents if not specified
self.self_reflect = True if self_reflect is None else self_reflect
self.instructions = instructions
# Check for model name in environment variable if not provided
self.llm = llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
self.tools = tools if tools else [] # Store original tools
self.function_calling_llm = function_calling_llm
self.max_iter = max_iter
self.max_rpm = max_rpm
self.max_execution_time = max_execution_time
self.memory = memory
self.verbose = verbose
self.allow_delegation = allow_delegation
self.step_callback = step_callback
self.cache = cache
self.system_template = system_template
self.prompt_template = prompt_template
self.response_template = response_template
self.allow_code_execution = allow_code_execution
self.max_retry_limit = max_retry_limit
self.respect_context_window = respect_context_window
self.code_execution_mode = code_execution_mode
self.embedder_config = embedder_config
self.knowledge_sources = knowledge_sources
self.use_system_prompt = use_system_prompt
self.chat_history = []
self.markdown = markdown
self.max_reflect = max_reflect
self.min_reflect = min_reflect
# Use the same model selection logic for reflect_llm
self.reflect_llm = reflect_llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
self.console = Console() # Create a single console instance for the agent
# Initialize system prompt
self.system_prompt = f"""{self.backstory}\n
Your Role: {self.role}\n
Your Goal: {self.goal}
"""
def generate_task(self) -> 'Task':
"""Generate a Task object from the agent's instructions"""
from ..task.task import Task
description = self.instructions if self.instructions else f"Execute task as {self.role} with goal: {self.goal}"
expected_output = "Complete the assigned task successfully"
return Task(
name=self.name,
description=description,
expected_output=expected_output,
agent=self,
tools=self.tools
)
def execute_tool(self, function_name, arguments):
"""
Execute a tool dynamically based on the function name and arguments.
"""
logging.debug(f"{self.name} executing tool {function_name} with arguments: {arguments}")
# Try to find the function in the agent's tools list first
func = None
for tool in self.tools:
if (callable(tool) and getattr(tool, '__name__', '') == function_name) or \
(inspect.isclass(tool) and tool.__name__ == function_name):
func = tool
break
if func is None:
# If not found in tools, try globals and main
func = globals().get(function_name)
if not func:
import __main__
func = getattr(__main__, function_name, None)
if func:
try:
# If it's a class with run method, instantiate and call run
if inspect.isclass(func) and hasattr(func, 'run'):
instance = func()
# Extract only the parameters that run() expects
run_params = {k: v for k, v in arguments.items()
if k in inspect.signature(instance.run).parameters
and k != 'self'}
return instance.run(**run_params)
# Otherwise treat as regular function
elif callable(func):
return func(**arguments)
except Exception as e:
error_msg = str(e)
logging.error(f"Error executing tool {function_name}: {error_msg}")
return {"error": error_msg}
error_msg = f"Tool '{function_name}' is not callable"
logging.error(error_msg)
return {"error": error_msg}
def clear_history(self):
self.chat_history = []
def __str__(self):
return f"Agent(name='{self.name}', role='{self.role}', goal='{self.goal}')"
def _chat_completion(self, messages, temperature=0.2, tools=None, stream=True):
start_time = time.time()
logging.debug(f"{self.name} sending messages to LLM: {messages}")
formatted_tools = []
if tools is None:
tools = self.tools
if tools:
for tool in tools:
if isinstance(tool, str):
# Generate tool definition for string tool names
tool_def = self._generate_tool_definition(tool)
if tool_def:
formatted_tools.append(tool_def)
else:
logging.warning(f"Could not generate definition for tool: {tool}")
elif isinstance(tool, dict):
formatted_tools.append(tool)
elif hasattr(tool, "to_openai_tool"):
formatted_tools.append(tool.to_openai_tool())
elif callable(tool):
formatted_tools.append(self._generate_tool_definition(tool.__name__))
else:
logging.warning(f"Tool {tool} not recognized")
try:
initial_response = client.chat.completions.create(
model=self.llm,
messages=messages,
temperature=temperature,
tools=formatted_tools if formatted_tools else None,
stream=False
)
tool_calls = getattr(initial_response.choices[0].message, 'tool_calls', None)
if tool_calls:
messages.append({
"role": "assistant",
"content": initial_response.choices[0].message.content,
"tool_calls": tool_calls
})
for tool_call in tool_calls:
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
if self.verbose:
display_tool_call(f"Agent {self.name} is calling function '{function_name}' with arguments: {arguments}")
tool_result = self.execute_tool(function_name, arguments)
results_str = json.dumps(tool_result) if tool_result else "Function returned an empty output"
if self.verbose:
display_tool_call(f"Function '{function_name}' returned: {results_str}")
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": results_str
})
if stream:
response_stream = client.chat.completions.create(
model=self.llm,
messages=messages,
temperature=temperature,
stream=True
)
full_response_text = ""
# Create Live display with proper configuration
with Live(
display_generating("", start_time),
console=self.console,
refresh_per_second=4,
transient=True, # Changed to False to preserve output
vertical_overflow="ellipsis",
auto_refresh=True
) as live:
for chunk in response_stream:
if chunk.choices[0].delta.content:
full_response_text += chunk.choices[0].delta.content
live.update(display_generating(full_response_text, start_time))
# Clear the last generating display with a blank line
self.console.print()
final_response = client.chat.completions.create(
model=self.llm,
messages=messages,
temperature=temperature,
stream=False
)
return final_response
else:
if tool_calls:
final_response = client.chat.completions.create(
model=self.llm,
messages=messages,
temperature=temperature,
stream=False
)
return final_response
else:
return initial_response
except Exception as e:
display_error(f"Error in chat completion: {e}")
return None
def chat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None):
if self.use_system_prompt:
system_prompt = f"""{self.backstory}\n
Your Role: {self.role}\n
Your Goal: {self.goal}
"""
if output_json:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_json.schema_json()}"
elif output_pydantic:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
else:
system_prompt = None
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.extend(self.chat_history)
# Modify prompt if output_json or output_pydantic is specified
original_prompt = prompt
if output_json or output_pydantic:
if isinstance(prompt, str):
prompt += "\nReturn ONLY a valid JSON object. No other text or explanation."
elif isinstance(prompt, list):
# For multimodal prompts, append to the text content
for item in prompt:
if item["type"] == "text":
item["text"] += "\nReturn ONLY a valid JSON object. No other text or explanation."
break
if isinstance(prompt, list):
# If we receive a multimodal prompt list, place it directly in the user message
messages.append({"role": "user", "content": prompt})
else:
messages.append({"role": "user", "content": prompt})
final_response_text = None
reflection_count = 0
start_time = time.time()
while True:
try:
if self.verbose:
# Handle both string and list prompts for instruction display
display_text = prompt
if isinstance(prompt, list):
# Extract text content from multimodal prompt
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
if display_text and str(display_text).strip():
# Pass agent information to display_instruction
agent_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
display_instruction(
f"Agent {self.name} is processing prompt: {display_text}",
console=self.console,
agent_name=self.name,
agent_role=self.role,
agent_tools=agent_tools
)
response = self._chat_completion(messages, temperature=temperature, tools=tools if tools else None)
if not response:
return None
tool_calls = getattr(response.choices[0].message, 'tool_calls', None)
response_text = response.choices[0].message.content.strip()
if tool_calls:
messages.append({
"role": "assistant",
"content": response_text,
"tool_calls": tool_calls
})
for tool_call in tool_calls:
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
if self.verbose:
display_tool_call(f"Agent {self.name} is calling function '{function_name}' with arguments: {arguments}", console=self.console)
tool_result = self.execute_tool(function_name, arguments)
if tool_result:
if self.verbose:
display_tool_call(f"Function '{function_name}' returned: {tool_result}", console=self.console)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(tool_result)
})
else:
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": "Function returned an empty output"
})
response = self._chat_completion(messages, temperature=temperature)
if not response:
return None
response_text = response.choices[0].message.content.strip()
# Handle output_json or output_pydantic if specified
if output_json or output_pydantic:
# Add to chat history and return raw response
self.chat_history.append({"role": "user", "content": original_prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
if self.verbose:
display_interaction(original_prompt, response_text, markdown=self.markdown,
generation_time=time.time() - start_time, console=self.console)
return response_text
if not self.self_reflect:
self.chat_history.append({"role": "user", "content": original_prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
if self.verbose:
logging.debug(f"Agent {self.name} final response: {response_text}")
display_interaction(original_prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
return response_text
reflection_prompt = f"""
Reflect on your previous response: '{response_text}'.
Identify any flaws, improvements, or actions.
Provide a "satisfactory" status ('yes' or 'no').
Output MUST be JSON with 'reflection' and 'satisfactory'.
"""
logging.debug(f"{self.name} reflection attempt {reflection_count+1}, sending prompt: {reflection_prompt}")
messages.append({"role": "user", "content": reflection_prompt})
try:
reflection_response = client.beta.chat.completions.parse(
model=self.reflect_llm if self.reflect_llm else self.llm,
messages=messages,
temperature=temperature,
response_format=ReflectionOutput
)
reflection_output = reflection_response.choices[0].message.parsed
if self.verbose:
display_self_reflection(f"Agent {self.name} self reflection (using {self.reflect_llm if self.reflect_llm else self.llm}): reflection='{reflection_output.reflection}' satisfactory='{reflection_output.satisfactory}'", console=self.console)
messages.append({"role": "assistant", "content": f"Self Reflection: {reflection_output.reflection} Satisfactory?: {reflection_output.satisfactory}"})
# Only consider satisfactory after minimum reflections
if reflection_output.satisfactory == "yes" and reflection_count >= self.min_reflect - 1:
if self.verbose:
display_self_reflection("Agent marked the response as satisfactory after meeting minimum reflections", console=self.console)
self.chat_history.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
return response_text
# Check if we've hit max reflections
if reflection_count >= self.max_reflect - 1:
if self.verbose:
display_self_reflection("Maximum reflection count reached, returning current response", console=self.console)
self.chat_history.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
return response_text
logging.debug(f"{self.name} reflection count {reflection_count + 1}, continuing reflection process")
messages.append({"role": "user", "content": "Now regenerate your response using the reflection you made"})
response = self._chat_completion(messages, temperature=temperature, tools=None, stream=True)
response_text = response.choices[0].message.content.strip()
reflection_count += 1
continue # Continue the loop for more reflections
except Exception as e:
display_error(f"Error in parsing self-reflection json {e}. Retrying", console=self.console)
logging.error("Reflection parsing failed.", exc_info=True)
messages.append({"role": "assistant", "content": f"Self Reflection failed."})
reflection_count += 1
continue # Continue even after error to try again
except Exception as e:
display_error(f"Error in chat: {e}", console=self.console)
return None
def clean_json_output(self, output: str) -> str:
"""Clean and extract JSON from response text."""
cleaned = output.strip()
# Remove markdown code blocks if present
if cleaned.startswith("```json"):
cleaned = cleaned[len("```json"):].strip()
if cleaned.startswith("```"):
cleaned = cleaned[len("```"):].strip()
if cleaned.endswith("```"):
cleaned = cleaned[:-3].strip()
return cleaned
async def achat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None):
"""Async version of chat method"""
try:
# Build system prompt
system_prompt = self.system_prompt
if output_json:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_json.schema_json()}"
elif output_pydantic:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {output_pydantic.schema_json()}"
# Build messages
if isinstance(prompt, str):
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt + ("\nReturn ONLY a valid JSON object. No other text or explanation." if (output_json or output_pydantic) else "")}
]
else:
# For multimodal prompts
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
]
if output_json or output_pydantic:
# Add JSON instruction to text content
for item in messages[-1]["content"]:
if item["type"] == "text":
item["text"] += "\nReturn ONLY a valid JSON object. No other text or explanation."
break
# Display instruction with agent info if verbose
if self.verbose:
display_text = prompt
if isinstance(prompt, list):
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
if display_text and str(display_text).strip():
agent_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
await adisplay_instruction(
f"Agent {self.name} is processing prompt: {display_text}",
console=self.console,
agent_name=self.name,
agent_role=self.role,
agent_tools=agent_tools
)
# Format tools if provided
formatted_tools = []
if tools:
for tool in tools:
if isinstance(tool, str):
tool_def = self._generate_tool_definition(tool)
if tool_def:
formatted_tools.append(tool_def)
elif isinstance(tool, dict):
formatted_tools.append(tool)
elif hasattr(tool, "to_openai_tool"):
formatted_tools.append(tool.to_openai_tool())
elif callable(tool):
formatted_tools.append(self._generate_tool_definition(tool.__name__))
# Create async OpenAI client
async_client = AsyncOpenAI()
# Make the API call based on the type of request
if tools:
response = await async_client.chat.completions.create(
model=self.llm,
messages=messages,
temperature=temperature,
tools=formatted_tools
)
return await self._achat_completion(response, tools)
elif output_json or output_pydantic:
response = await async_client.chat.completions.create(
model=self.llm,
messages=messages,
temperature=temperature,
response_format={"type": "json_object"}
)
# Return the raw response
return response.choices[0].message.content
else:
response = await async_client.chat.completions.create(
model=self.llm,
messages=messages,
temperature=temperature
)
return response.choices[0].message.content
except Exception as e:
display_error(f"Error in chat completion: {e}")
return None
async def _achat_completion(self, response, tools):
"""Async version of _chat_completion method"""
try:
message = response.choices[0].message
if not hasattr(message, 'tool_calls') or not message.tool_calls:
return message.content
results = []
for tool_call in message.tool_calls:
try:
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
# Find the matching tool
tool = next((t for t in tools if t.__name__ == function_name), None)
if not tool:
display_error(f"Tool {function_name} not found")
continue
# Check if the tool is async
if asyncio.iscoroutinefunction(tool):
result = await tool(**arguments)
else:
# Run sync function in executor to avoid blocking
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, lambda: tool(**arguments))
results.append(result)
except Exception as e:
display_error(f"Error executing tool {function_name}: {e}")
results.append(None)
# If we have results, format them into a response
if results:
formatted_results = "\n".join([str(r) for r in results if r is not None])
if formatted_results:
messages = [
{"role": "system", "content": self.system_prompt},
{"role": "assistant", "content": "Here are the tool results:"},
{"role": "user", "content": formatted_results + "\nPlease process these results and provide a final response."}
]
try:
async_client = AsyncOpenAI()
final_response = await async_client.chat.completions.create(
model=self.llm,
messages=messages,
temperature=0.2
)
return final_response.choices[0].message.content
except Exception as e:
display_error(f"Error in final chat completion: {e}")
return formatted_results
return formatted_results
return None
except Exception as e:
display_error(f"Error in _achat_completion: {e}")
return None
def run(self):
"""Alias for start() method"""
return self.start()
-534
View File
@@ -1,534 +0,0 @@
import logging
import asyncio
from typing import Dict, Optional, List, Any, AsyncGenerator
from pydantic import BaseModel
from ..agent.agent import Agent
from ..task.task import Task
from ..main import display_error, client
class LoopItems(BaseModel):
items: List[Any]
class Process:
def __init__(self, tasks: Dict[str, Task], agents: List[Agent], manager_llm: Optional[str] = None, verbose: bool = False):
self.tasks = tasks
self.agents = agents
self.manager_llm = manager_llm
self.verbose = verbose
async def aworkflow(self) -> AsyncGenerator[str, None]:
"""Async version of workflow method"""
# Build workflow relationships first
for task in self.tasks.values():
if task.next_tasks:
for next_task_name in task.next_tasks:
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
if next_task:
next_task.previous_tasks.append(task.name)
# Find start task
start_task = None
for task_id, task in self.tasks.items():
if task.is_start:
start_task = task
break
if not start_task:
start_task = list(self.tasks.values())[0]
logging.info("No start task marked, using first task")
current_task = start_task
visited_tasks = set()
loop_data = {} # Store loop-specific data
while current_task and current_task.id not in visited_tasks:
task_id = current_task.id
logging.info(f"Executing workflow task: {current_task.name if current_task.name else task_id}")
# Add context from previous tasks to description
if current_task.previous_tasks or current_task.context:
context = "\nInput data from previous tasks:"
# Add data from previous tasks in workflow
for prev_name in current_task.previous_tasks:
prev_task = next((t for t in self.tasks.values() if t.name == prev_name), None)
if prev_task and prev_task.result:
# Handle loop data
if current_task.task_type == "loop":
# create a loop manager Agent
loop_manager = Agent(
name="Loop Manager",
role="Loop data processor",
goal="Process loop data and convert it to list format",
backstory="Expert at handling loop data and converting it to proper format",
llm=self.manager_llm,
verbose=self.verbose,
markdown=True
)
# get the loop data convert it to list using calling Agent class chat
loop_prompt = f"""
Process this data into a list format:
{prev_task.result.raw}
Return a JSON object with an 'items' array containing the items to process.
"""
if current_task.async_execution:
loop_data_str = await loop_manager.achat(
prompt=loop_prompt,
output_json=LoopItems
)
else:
loop_data_str = loop_manager.chat(
prompt=loop_prompt,
output_json=LoopItems
)
try:
# The response will already be parsed into LoopItems model
loop_data[f"loop_{current_task.name}"] = {
"items": loop_data_str.items,
"index": 0,
"remaining": len(loop_data_str.items)
}
context += f"\nCurrent loop item: {loop_data_str.items[0]}"
except Exception as e:
display_error(f"Failed to process loop data: {e}")
context += f"\n{prev_name}: {prev_task.result.raw}"
else:
context += f"\n{prev_name}: {prev_task.result.raw}"
# Add data from context tasks
if current_task.context:
for ctx_task in current_task.context:
if ctx_task.result and ctx_task.name != current_task.name:
context += f"\n{ctx_task.name}: {ctx_task.result.raw}"
# Update task description with context
current_task.description = current_task.description + context
# Execute task using existing run_task method
yield task_id
visited_tasks.add(task_id)
# Handle loop progression
if current_task.task_type == "loop":
loop_key = f"loop_{current_task.name}"
if loop_key in loop_data:
loop_info = loop_data[loop_key]
loop_info["index"] += 1
has_more = loop_info["remaining"] > 0
# Update result to trigger correct condition
if current_task.result:
result = current_task.result.raw
if has_more:
result += "\nmore"
else:
result += "\ndone"
current_task.result.raw = result
# Determine next task based on result
next_task = None
if current_task.result:
if current_task.task_type in ["decision", "loop"]:
result = current_task.result.raw.lower()
# Check conditions
for condition, tasks in current_task.condition.items():
if condition.lower() in result and tasks:
next_task_name = tasks[0]
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
# For loops, allow revisiting the same task
if next_task and next_task.id == current_task.id:
visited_tasks.discard(current_task.id)
break
if not next_task and current_task.next_tasks:
next_task_name = current_task.next_tasks[0]
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
current_task = next_task
if not current_task:
logging.info("Workflow execution completed")
break
async def asequential(self) -> AsyncGenerator[str, None]:
"""Async version of sequential method"""
for task_id in self.tasks:
if self.tasks[task_id].status != "completed":
yield task_id
async def ahierarchical(self) -> AsyncGenerator[str, None]:
"""Async version of hierarchical method"""
logging.debug(f"Starting hierarchical task execution with {len(self.tasks)} tasks")
manager_agent = Agent(
name="Manager",
role="Project manager",
goal="Manage the entire flow of tasks and delegate them to the right agent",
backstory="Expert project manager to coordinate tasks among agents",
llm=self.manager_llm,
verbose=self.verbose,
markdown=True,
self_reflect=False
)
class ManagerInstructions(BaseModel):
task_id: int
agent_name: str
action: str
manager_task = Task(
name="manager_task",
description="Decide the order of tasks and which agent executes them",
expected_output="All tasks completed successfully",
agent=manager_agent
)
manager_task_id = yield manager_task
logging.info(f"Created manager task with ID {manager_task_id}")
completed_count = 0
total_tasks = len(self.tasks) - 1
logging.info(f"Need to complete {total_tasks} tasks (excluding manager task)")
while completed_count < total_tasks:
tasks_summary = []
for tid, tk in self.tasks.items():
if tk.name == "manager_task":
continue
task_info = {
"task_id": tid,
"name": tk.name,
"description": tk.description,
"status": tk.status if tk.status else "not started",
"agent": tk.agent.name if tk.agent else "No agent"
}
tasks_summary.append(task_info)
logging.info(f"Task {tid} status: {task_info}")
manager_prompt = f"""
Here is the current status of all tasks except yours (manager_task):
{tasks_summary}
Provide a JSON with the structure:
{{
"task_id": <int>,
"agent_name": "<string>",
"action": "<execute or stop>"
}}
"""
try:
logging.info("Requesting manager instructions...")
if manager_task.async_execution:
manager_response = await client.beta.chat.completions.parse(
model=self.manager_llm,
messages=[
{"role": "system", "content": manager_task.description},
{"role": "user", "content": manager_prompt}
],
temperature=0.7,
response_format=ManagerInstructions
)
else:
manager_response = client.beta.chat.completions.parse(
model=self.manager_llm,
messages=[
{"role": "system", "content": manager_task.description},
{"role": "user", "content": manager_prompt}
],
temperature=0.7,
response_format=ManagerInstructions
)
parsed_instructions = manager_response.choices[0].message.parsed
logging.info(f"Manager instructions: {parsed_instructions}")
except Exception as e:
display_error(f"Manager parse error: {e}")
logging.error(f"Manager parse error: {str(e)}", exc_info=True)
break
selected_task_id = parsed_instructions.task_id
selected_agent_name = parsed_instructions.agent_name
action = parsed_instructions.action
logging.info(f"Manager selected task_id={selected_task_id}, agent={selected_agent_name}, action={action}")
if action.lower() == "stop":
logging.info("Manager decided to stop task execution")
break
if selected_task_id not in self.tasks:
error_msg = f"Manager selected invalid task id {selected_task_id}"
display_error(error_msg)
logging.error(error_msg)
break
original_agent = self.tasks[selected_task_id].agent.name if self.tasks[selected_task_id].agent else "None"
for a in self.agents:
if a.name == selected_agent_name:
self.tasks[selected_task_id].agent = a
logging.info(f"Changed agent for task {selected_task_id} from {original_agent} to {selected_agent_name}")
break
if self.tasks[selected_task_id].status != "completed":
logging.info(f"Starting execution of task {selected_task_id}")
yield selected_task_id
logging.info(f"Finished execution of task {selected_task_id}, status: {self.tasks[selected_task_id].status}")
if self.tasks[selected_task_id].status == "completed":
completed_count += 1
logging.info(f"Task {selected_task_id} completed. Total completed: {completed_count}/{total_tasks}")
self.tasks[manager_task.id].status = "completed"
if self.verbose >= 1:
logging.info("All tasks completed under manager supervision.")
logging.info("Hierarchical task execution finished")
def workflow(self):
"""Synchronous version of workflow method"""
# Build workflow relationships first
for task in self.tasks.values():
if task.next_tasks:
for next_task_name in task.next_tasks:
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
if next_task:
next_task.previous_tasks.append(task.name)
# Find start task
start_task = None
for task_id, task in self.tasks.items():
if task.is_start:
start_task = task
break
if not start_task:
start_task = list(self.tasks.values())[0]
logging.info("No start task marked, using first task")
current_task = start_task
visited_tasks = set()
loop_data = {} # Store loop-specific data
while current_task and current_task.id not in visited_tasks:
task_id = current_task.id
logging.info(f"Executing workflow task: {current_task.name if current_task.name else task_id}")
# Add context from previous tasks to description
if current_task.previous_tasks or current_task.context:
context = "\nInput data from previous tasks:"
# Add data from previous tasks in workflow
for prev_name in current_task.previous_tasks:
prev_task = next((t for t in self.tasks.values() if t.name == prev_name), None)
if prev_task and prev_task.result:
# Handle loop data
if current_task.task_type == "loop":
# create a loop manager Agent
loop_manager = Agent(
name="Loop Manager",
role="Loop data processor",
goal="Process loop data and convert it to list format",
backstory="Expert at handling loop data and converting it to proper format",
llm=self.manager_llm,
verbose=self.verbose,
markdown=True
)
# get the loop data convert it to list using calling Agent class chat
loop_prompt = f"""
Process this data into a list format:
{prev_task.result.raw}
Return a JSON object with an 'items' array containing the items to process.
"""
loop_data_str = loop_manager.chat(
prompt=loop_prompt,
output_json=LoopItems
)
try:
# The response will already be parsed into LoopItems model
loop_data[f"loop_{current_task.name}"] = {
"items": loop_data_str.items,
"index": 0,
"remaining": len(loop_data_str.items)
}
context += f"\nCurrent loop item: {loop_data_str.items[0]}"
except Exception as e:
display_error(f"Failed to process loop data: {e}")
context += f"\n{prev_name}: {prev_task.result.raw}"
else:
context += f"\n{prev_name}: {prev_task.result.raw}"
# Add data from context tasks
if current_task.context:
for ctx_task in current_task.context:
if ctx_task.result and ctx_task.name != current_task.name:
context += f"\n{ctx_task.name}: {ctx_task.result.raw}"
# Update task description with context
current_task.description = current_task.description + context
# Execute task using existing run_task method
yield task_id
visited_tasks.add(task_id)
# Handle loop progression
if current_task.task_type == "loop":
loop_key = f"loop_{current_task.name}"
if loop_key in loop_data:
loop_info = loop_data[loop_key]
loop_info["index"] += 1
has_more = loop_info["remaining"] > 0
# Update result to trigger correct condition
if current_task.result:
result = current_task.result.raw
if has_more:
result += "\nmore"
else:
result += "\ndone"
current_task.result.raw = result
# Determine next task based on result
next_task = None
if current_task.result:
if current_task.task_type in ["decision", "loop"]:
result = current_task.result.raw.lower()
# Check conditions
for condition, tasks in current_task.condition.items():
if condition.lower() in result and tasks:
next_task_name = tasks[0]
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
# For loops, allow revisiting the same task
if next_task and next_task.id == current_task.id:
visited_tasks.discard(current_task.id)
break
if not next_task and current_task.next_tasks:
next_task_name = current_task.next_tasks[0]
next_task = next((t for t in self.tasks.values() if t.name == next_task_name), None)
current_task = next_task
if not current_task:
logging.info("Workflow execution completed")
break
def sequential(self):
"""Synchronous version of sequential method"""
for task_id in self.tasks:
if self.tasks[task_id].status != "completed":
yield task_id
def hierarchical(self):
"""Synchronous version of hierarchical method"""
logging.debug(f"Starting hierarchical task execution with {len(self.tasks)} tasks")
manager_agent = Agent(
name="Manager",
role="Project manager",
goal="Manage the entire flow of tasks and delegate them to the right agent",
backstory="Expert project manager to coordinate tasks among agents",
llm=self.manager_llm,
verbose=self.verbose,
markdown=True,
self_reflect=False
)
class ManagerInstructions(BaseModel):
task_id: int
agent_name: str
action: str
manager_task = Task(
name="manager_task",
description="Decide the order of tasks and which agent executes them",
expected_output="All tasks completed successfully",
agent=manager_agent
)
manager_task_id = yield manager_task
logging.info(f"Created manager task with ID {manager_task_id}")
completed_count = 0
total_tasks = len(self.tasks) - 1
logging.info(f"Need to complete {total_tasks} tasks (excluding manager task)")
while completed_count < total_tasks:
tasks_summary = []
for tid, tk in self.tasks.items():
if tk.name == "manager_task":
continue
task_info = {
"task_id": tid,
"name": tk.name,
"description": tk.description,
"status": tk.status if tk.status else "not started",
"agent": tk.agent.name if tk.agent else "No agent"
}
tasks_summary.append(task_info)
logging.info(f"Task {tid} status: {task_info}")
manager_prompt = f"""
Here is the current status of all tasks except yours (manager_task):
{tasks_summary}
Provide a JSON with the structure:
{{
"task_id": <int>,
"agent_name": "<string>",
"action": "<execute or stop>"
}}
"""
try:
logging.info("Requesting manager instructions...")
manager_response = client.beta.chat.completions.parse(
model=self.manager_llm,
messages=[
{"role": "system", "content": manager_task.description},
{"role": "user", "content": manager_prompt}
],
temperature=0.7,
response_format=ManagerInstructions
)
parsed_instructions = manager_response.choices[0].message.parsed
logging.info(f"Manager instructions: {parsed_instructions}")
except Exception as e:
display_error(f"Manager parse error: {e}")
logging.error(f"Manager parse error: {str(e)}", exc_info=True)
break
selected_task_id = parsed_instructions.task_id
selected_agent_name = parsed_instructions.agent_name
action = parsed_instructions.action
logging.info(f"Manager selected task_id={selected_task_id}, agent={selected_agent_name}, action={action}")
if action.lower() == "stop":
logging.info("Manager decided to stop task execution")
break
if selected_task_id not in self.tasks:
error_msg = f"Manager selected invalid task id {selected_task_id}"
display_error(error_msg)
logging.error(error_msg)
break
original_agent = self.tasks[selected_task_id].agent.name if self.tasks[selected_task_id].agent else "None"
for a in self.agents:
if a.name == selected_agent_name:
self.tasks[selected_task_id].agent = a
logging.info(f"Changed agent for task {selected_task_id} from {original_agent} to {selected_agent_name}")
break
if self.tasks[selected_task_id].status != "completed":
logging.info(f"Starting execution of task {selected_task_id}")
yield selected_task_id
logging.info(f"Finished execution of task {selected_task_id}, status: {self.tasks[selected_task_id].status}")
if self.tasks[selected_task_id].status == "completed":
completed_count += 1
logging.info(f"Task {selected_task_id} completed. Total completed: {completed_count}/{total_tasks}")
self.tasks[manager_task.id].status = "completed"
if self.verbose >= 1:
logging.info("All tasks completed under manager supervision.")
logging.info("Hierarchical task execution finished")
-1590
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.40 gunicorn markdown
RUN pip install flask praisonai==2.0.61 gunicorn markdown
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+124
View File
@@ -0,0 +1,124 @@
---
title: "AI Agents"
description: "Overview of all available PraisonAI agents and their capabilities"
icon: "robot"
---
PraisonAI provides a diverse set of specialized agents for various tasks. Each agent is designed with specific capabilities and tools to handle different types of tasks effectively.
```mermaid
graph LR
%% Define the main flow
Start([▶ Start]) --> Agent1
Agent1 --> Process[⚙ Process]
Process --> Agent2
Agent2 --> Output([✓ Output])
Process -.-> Agent1
%% Define subgraphs for agents and their tasks
subgraph Agent1[ ]
Task1[📋 Task]
AgentIcon1[🤖 AI Agent]
Tools1[🔧 Tools]
Task1 --- AgentIcon1
AgentIcon1 --- Tools1
end
subgraph Agent2[ ]
Task2[📋 Task]
AgentIcon2[🤖 AI Agent]
Tools2[🔧 Tools]
Task2 --- AgentIcon2
AgentIcon2 --- Tools2
end
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Start,Output,Task1,Task2 input
class Process,AgentIcon1,AgentIcon2 process
class Tools1,Tools2 tools
class Agent1,Agent2 transparent
```
## Data & Analysis
<CardGroup cols={2}>
<Card title="Data Analyst" icon="chart-line" href="/agents/data-analyst">
Analyze data from various sources, create visualizations, and generate insights.
</Card>
<Card title="Finance" icon="money-bill-trend-up" href="/agents/finance">
Track stocks, analyze financial data, and provide investment recommendations.
</Card>
<Card title="Research" icon="magnifying-glass-chart" href="/agents/research">
Conduct comprehensive research and analysis across various topics.
</Card>
<Card title="Wikipedia" icon="book" href="/agents/wikipedia">
Search and extract information from Wikipedia articles.
</Card>
</CardGroup>
## Media & Content
<CardGroup cols={2}>
<Card title="Image Analysis" icon="image" href="/agents/image">
Analyze and understand visual content from images.
</Card>
<Card title="Image to Text" icon="text" href="/agents/image-to-text">
Convert images to textual descriptions and extract text content.
</Card>
<Card title="Video" icon="video" href="/agents/video">
Analyze video content and extract meaningful information.
</Card>
<Card title="Markdown" icon="markdown" href="/agents/markdown">
Generate and format content in Markdown syntax.
</Card>
</CardGroup>
## Search & Recommendations
<CardGroup cols={2}>
<Card title="Web Search" icon="globe" href="/agents/websearch">
Perform intelligent web searches and gather information.
</Card>
<Card title="Recommendation" icon="thumbs-up" href="/agents/recommendation">
Generate personalized recommendations based on preferences.
</Card>
<Card title="Shopping" icon="shop" href="/agents/shopping">
Compare prices and find the best deals across stores.
</Card>
<Card title="Planning" icon="calendar" href="/agents/planning">
Create travel plans and detailed itineraries.
</Card>
</CardGroup>
## Development
<CardGroup cols={2}>
<Card title="Programming" icon="code" href="/agents/programming">
Write, analyze, and debug code across multiple languages.
</Card>
<Card title="Single Agent" icon="circle-1" href="/agents/single">
Simple, focused agent for basic tasks without external tools.
</Card>
</CardGroup>
## Getting Started
Each agent can be easily initialized and customized for your specific needs. Here's a basic example:
```python
from praisonaiagents import Agent
# Create an agent with specific instructions
agent = Agent(instructions="Your task-specific instructions")
# Start the agent with a task
response = agent.start("Your task description")
```
For more detailed information about each agent, click on the respective cards above.
+120
View File
@@ -0,0 +1,120 @@
---
title: "Data Analyst Agent"
sidebarTitle: "Data Analyst"
description: "Learn how to create AI agents for data analysis and insights generation."
icon: "chart-line"
---
```mermaid
flowchart LR
In[Data Source] --> Reader[Data Reader]
Reader --> Analyzer[Data Analyzer]
Analyzer --> Generator[Insights Generator]
Generator --> Out[Output]
style In fill:#8B0000,color:#fff
style Reader fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Data Analyst Agent can read data from various sources, analyze it, and generate insights.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `data_analysis.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import (
read_csv, read_excel, write_csv, write_excel,
filter_data, get_summary, group_by, pivot_table
)
agent = Agent(
instructions="You are a Data Analyst Agent",
tools=[
read_csv, read_excel, write_csv, write_excel,
filter_data, get_summary, group_by, pivot_table
]
)
# Start analysis with a specific task
agent.start(f"""
Read the data from the csv file {os.path.join(os.path.dirname(__file__), "tesla-stock-price.csv")}
Analyse the data and give me the insights
read_csv to read the file
""")
```
</Step>
</Steps>
## Understanding Data Analysis Workflow
The Data Analyst Agent is designed to perform comprehensive data analysis tasks using a suite of specialized tools. Here's how it works:
1. **Data Reading**: The agent can read data from various sources:
- CSV files using `read_csv`
- Excel files using `read_excel`
2. **Data Analysis**: Multiple analysis tools are available:
- `filter_data`: Filter datasets based on conditions
- `get_summary`: Generate statistical summaries
- `group_by`: Group data by specific columns
- `pivot_table`: Create pivot tables for analysis
3. **Data Export**: Results can be exported to:
- CSV format using `write_csv`
- Excel format using `write_excel`
## Features
<CardGroup cols={2}>
<Card title="Multiple Data Sources" icon="table">
Support for both CSV and Excel file formats.
</Card>
<Card title="Analysis Tools" icon="calculator">
Comprehensive suite of analysis tools including filtering, summarization, and pivoting.
</Card>
<Card title="Data Export" icon="file-export">
Export capabilities to various formats.
</Card>
<Card title="Automated Insights" icon="lightbulb">
Automatic generation of data insights and patterns.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Analyzing stock data
agent.start("""
1. Read 'stock_data.csv'
2. Filter data for the last 30 days
3. Calculate daily returns
4. Generate summary statistics
5. Export results to 'analysis_results.xlsx'
""")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex analysis workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
- Check out other specialized agents like the [Finance Agent](/agents/finance) for specific use cases
+97
View File
@@ -0,0 +1,97 @@
---
title: "Finance Agent"
sidebarTitle: "Finance"
description: "Learn how to create AI agents for financial analysis and investment recommendations."
icon: "money-bill-trend-up"
---
```mermaid
flowchart LR
In[Request] --> Price[Stock Price]
Price --> Info[Stock Info]
Info --> History[Historical Data]
History --> Out[Investment Advice]
style In fill:#8B0000,color:#fff
style Price fill:#2E8B57,color:#fff
style Info fill:#2E8B57,color:#fff
style History fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Finance Agent can analyze stock market data and provide investment recommendations.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `finance_analysis.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import get_stock_price, get_stock_info, get_historical_data
agent = Agent(
instructions="You are a Research Agent",
tools=[get_stock_price, get_stock_info, get_historical_data]
)
agent.start("Understand current stock price and historical data of Apple and Google. Tell me if I can invest in them")
```
</Step>
</Steps>
## Understanding Financial Analysis
The Finance Agent specializes in stock market analysis and investment recommendations using three key components:
1. **Real-time Price Data**: Uses `get_stock_price` to fetch current market prices
2. **Company Information**: Retrieves company details using `get_stock_info`
3. **Historical Analysis**: Analyzes trends with `get_historical_data`
## Features
<CardGroup cols={2}>
<Card title="Real-time Data" icon="clock">
Access to current stock market prices and information.
</Card>
<Card title="Company Analysis" icon="building">
Detailed company information and fundamentals.
</Card>
<Card title="Historical Trends" icon="chart-line">
Analysis of historical price movements and patterns.
</Card>
<Card title="Investment Advice" icon="money-bill">
AI-powered investment recommendations.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Analyzing specific stocks
agent.start("""
1. Get current prices for AAPL and GOOGL
2. Retrieve company information
3. Analyze 6-month historical data
4. Provide investment recommendations
""")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex financial analysis
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendation accuracy
- Check out the [Data Analyst Agent](/agents/data-analyst) for detailed data analysis capabilities
+140
View File
@@ -0,0 +1,140 @@
---
title: "Image to Text Agent"
sidebarTitle: "Image to Text"
description: "Learn how to create AI agents for converting images to textual descriptions and extracting text from images."
icon: "text"
---
```mermaid
flowchart LR
In[Image Input] --> OCR[Text Extractor]
OCR --> Analyzer[Content Analyzer]
Analyzer --> Generator[Description Generator]
Generator --> Out[Text Output]
style In fill:#8B0000,color:#fff
style OCR fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Image-to-Text Agent can extract text from images and generate comprehensive descriptions.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `image_to_text.py`:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create Image-to-Text Agent
image_text_agent = Agent(
name="ImageTextConverter",
role="Image Text Extraction Specialist",
goal="Convert image content to textual descriptions and extract text",
backstory="""You are an expert in OCR and image understanding.
You excel at extracting text from images and generating detailed descriptions.""",
llm="gpt-4o-mini",
self_reflect=False
)
# Create text extraction task
extraction_task = Task(
name="extract_text",
description="Extract all text from this image and describe its layout.",
expected_output="Extracted text and layout description",
agent=image_text_agent,
images=["document.jpg"]
)
# Create description task
description_task = Task(
name="generate_description",
description="Generate a detailed description of the image content.",
expected_output="Comprehensive description of visual elements",
agent=image_text_agent,
images=["scene.jpg"]
)
# Create PraisonAIAgents instance
agents = PraisonAIAgents(
agents=[image_text_agent],
tasks=[extraction_task, description_task],
process="sequential",
verbose=1
)
# Run analysis
agents.start()
```
</Step>
</Steps>
## Understanding Image-to-Text Conversion
The Image-to-Text Agent combines multiple capabilities to convert visual content into textual form:
1. **OCR Processing**: Extracts text from images using optical character recognition
2. **Layout Analysis**: Understands the spatial arrangement of text and visual elements
3. **Content Description**: Generates natural language descriptions of image content
4. **Text Formatting**: Preserves text formatting and structure where possible
## Features
<CardGroup cols={2}>
<Card title="Text Extraction" icon="text">
Advanced OCR capabilities for text extraction.
</Card>
<Card title="Layout Understanding" icon="table-layout">
Analysis of text and content layout.
</Card>
<Card title="Content Description" icon="pen-to-square">
Detailed descriptions of visual content.
</Card>
<Card title="Format Preservation" icon="paragraph">
Maintains text formatting and structure.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Processing a document image
document_task = Task(
name="process_document",
description="Extract text and analyze document layout",
expected_output="Extracted text with layout information",
agent=image_text_agent,
images=["business_document.jpg"]
)
# Run single task
agents = PraisonAIAgents(
agents=[image_text_agent],
tasks=[document_task],
process="sequential"
)
agents.start()
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex document processing
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving text extraction accuracy
- Check out the [Image Agent](/agents/image) for pure image analysis capabilities
+139
View File
@@ -0,0 +1,139 @@
---
title: "Image Analysis Agent"
sidebarTitle: "Image Analysis"
description: "Learn how to create AI agents for image analysis and visual content understanding."
icon: "image"
---
```mermaid
flowchart LR
In[Image Input] --> Analyzer[Image Analyzer]
Analyzer --> Detector[Object Detector]
Detector --> Generator[Description Generator]
Generator --> Out[Analysis Output]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Detector fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Image Analysis Agent can process and analyze visual content, detect objects, and generate detailed descriptions.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `image_analysis.py`:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create Image Analysis Agent
image_agent = Agent(
name="ImageAnalyst",
role="Image Analysis Specialist",
goal="Analyze images and videos to extract meaningful information",
backstory="""You are an expert in computer vision and image analysis.
You excel at describing images, detecting objects, and understanding visual content.""",
llm="gpt-4o-mini",
self_reflect=False
)
# Create tasks for different types of analysis
task1 = Task(
name="analyze_landmark",
description="Describe this famous landmark and its architectural features.",
expected_output="Detailed description of the landmark's architecture and significance",
agent=image_agent,
images=["https://example.com/landmark.jpg"]
)
task2 = Task(
name="analyze_local_image",
description="What objects can you see in this image? Describe their arrangement.",
expected_output="Detailed description of objects and their spatial relationships",
agent=image_agent,
images=["local_image.jpg"]
)
# Create PraisonAIAgents instance
agents = PraisonAIAgents(
agents=[image_agent],
tasks=[task1, task2],
process="sequential",
verbose=1
)
# Run analysis
agents.start()
```
</Step>
</Steps>
## Understanding Image Analysis
The Image Analysis Agent is designed to process and understand visual content through several key capabilities:
1. **Image Input**: Supports both URL and local file inputs
2. **Object Detection**: Identifies and locates objects within images
3. **Architectural Analysis**: Specialized in analyzing architectural features
4. **Spatial Understanding**: Describes spatial relationships between objects
## Features
<CardGroup cols={2}>
<Card title="Multiple Input Sources" icon="images">
Support for both URL and local image files.
</Card>
<Card title="Object Detection" icon="magnifying-glass">
Advanced object detection and recognition.
</Card>
<Card title="Architectural Analysis" icon="building">
Specialized analysis of architectural features.
</Card>
<Card title="Detailed Descriptions" icon="pen">
Generation of comprehensive visual descriptions.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Analyzing a landmark image
landmark_task = Task(
name="analyze_famous_landmark",
description="Analyze this historical landmark",
expected_output="Architectural details and historical significance",
agent=image_agent,
images=["https://example.com/landmark.jpg"]
)
# Run single task
agents = PraisonAIAgents(
agents=[image_agent],
tasks=[landmark_task],
process="sequential"
)
agents.start()
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex image analysis workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
- Check out the [Video Agent](/agents/video) for video content analysis
+120
View File
@@ -0,0 +1,120 @@
---
title: "Markdown Agent"
sidebarTitle: "Markdown"
description: "Learn how to create AI agents for generating and formatting content in Markdown."
icon: "markdown"
---
```mermaid
flowchart LR
In[Content Request] --> Generator[Content Generator]
Generator --> Formatter[Markdown Formatter]
Formatter --> Validator[Format Validator]
Validator --> Out[Markdown Output]
style In fill:#8B0000,color:#fff
style Generator fill:#2E8B57,color:#fff
style Formatter fill:#2E8B57,color:#fff
style Validator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Markdown Agent can generate and format content in Markdown syntax.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `markdown_generator.py`:
```python
from praisonaiagents import Agent
# Create Markdown Agent
markdown_agent = Agent(
name="MarkdownWriter",
role="Markdown Content Specialist",
goal="Generate well-formatted content in Markdown syntax",
instructions="You are a Markdown Agent, output in markdown format",
llm="gpt-4o-mini",
self_reflect=False
)
# Generate content
response = markdown_agent.start(
"Write a blog post about artificial intelligence"
)
# Save to file
with open('blog_post.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Markdown Generation
The Markdown Agent specializes in creating properly formatted Markdown content:
1. **Content Generation**: Creates original content based on prompts
2. **Markdown Formatting**: Applies proper Markdown syntax
3. **Structure Validation**: Ensures correct formatting
4. **Document Organization**: Creates well-structured documents
## Features
<CardGroup cols={2}>
<Card title="Content Creation" icon="pen-to-square">
Generates original, well-structured content.
</Card>
<Card title="Markdown Syntax" icon="code">
Proper implementation of Markdown formatting.
</Card>
<Card title="Document Structure" icon="sitemap">
Organized document hierarchy and sections.
</Card>
<Card title="Format Validation" icon="check">
Ensures correct Markdown syntax usage.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Generate a technical documentation
agent = Agent(
instructions="You are a Markdown Agent, output in markdown format"
)
# Generate API documentation
response = agent.start("""
Create technical documentation for a REST API with:
- Introduction
- Authentication
- Endpoints
- Examples
""")
# Save documentation
with open('api_docs.md', 'w') as f:
f.write(response)
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex document generation
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving content quality
- Check out the [Documentation Agent](/agents/documentation) for specialized documentation generation
+109
View File
@@ -0,0 +1,109 @@
---
title: "Planning Agent"
sidebarTitle: "Planning"
description: "Learn how to create AI agents for trip planning and itinerary generation."
icon: "calendar"
---
```mermaid
flowchart LR
In[Request] --> Search[Web Search]
Search --> Analyzer[Options Analyzer]
Analyzer --> Generator[Plan Generator]
Generator --> Out[Itinerary]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Planning Agent can search for travel options and create detailed itineraries.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `travel_planner.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Planning Agent
planning_agent = Agent(
name="TravelPlanner",
role="Travel Planning Specialist",
goal="Create comprehensive travel plans and itineraries",
instructions="You are a Planning Agent",
tools=[duckduckgo]
)
# Generate travel plan
response = planning_agent.start(
"I want to go to London next week, find me a good hotel and flight"
)
# Save plan
with open('travel_plan.txt', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Travel Planning
The Planning Agent combines multiple capabilities to create comprehensive travel plans:
1. **Web Search**: Uses DuckDuckGo to find current travel options
2. **Options Analysis**: Evaluates and compares different choices
3. **Plan Generation**: Creates detailed itineraries
4. **Recommendations**: Provides personalized suggestions
## Features
<CardGroup cols={2}>
<Card title="Flight Search" icon="plane">
Finds and compares flight options.
</Card>
<Card title="Hotel Booking" icon="hotel">
Recommends suitable accommodations.
</Card>
<Card title="Itinerary Creation" icon="calendar-days">
Generates detailed travel schedules.
</Card>
<Card title="Real-time Data" icon="clock">
Uses current pricing and availability.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Create a weekend trip plan
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(instructions="You are a Planning Agent", tools=[duckduckgo])
agent.start("I want to go London next week, find me a good hotel and flight")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex travel planning
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendations
- Check out the [Research Agent](/agents/research) for detailed destination research
+125
View File
@@ -0,0 +1,125 @@
---
title: "Programming Agent"
sidebarTitle: "Programming"
description: "Learn how to create AI agents for code development, analysis, and execution."
icon: "code"
---
```mermaid
flowchart LR
In[Code Request] --> Analyzer[Code Analyzer]
Analyzer --> Generator[Code Generator]
Generator --> Executor[Code Executor]
Executor --> Debugger[Code Debugger]
Debugger --> Out[Output]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Executor fill:#2E8B57,color:#fff
style Debugger fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Programming Agent can analyze, generate, execute, and debug code.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `code_assistant.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import execute_code, analyze_code, format_code, lint_code, disassemble_code # Code Tools
from praisonaiagents.tools import execute_command, list_processes, kill_process, get_system_info # Shell Tools
from praisonaiagents.tools import duckduckgo # Web Search Tool
agent = Agent(
instructions="You are a Programming Agent", self_reflect=True, min_reflect=5, max_reflect=10,
tools=[execute_code, analyze_code, format_code, lint_code, disassemble_code, execute_command, list_processes, kill_process, get_system_info, duckduckgo]
)
agent.start(
"Write a python script using yfinance to find the stock price of Tesla"
"First check if required packages are installed"
"Run it using execute_code"
"execute_command if you want to run any terminal command"
"search internet using duckduckgo if you want to know update python package information"
"Analyse the output using analyze_code and fix error if required"
"if no package is installed, install it"
"then run the code"
)
```
</Step>
</Steps>
## Understanding Code Development
The Programming Agent combines multiple tools for comprehensive code development:
1. **Code Tools**:
- `execute_code`: Run Python code
- `analyze_code`: Analyze code structure
- `format_code`: Format code to standards
- `lint_code`: Check code quality
- `disassemble_code`: View bytecode
2. **Shell Tools**:
- `execute_command`: Run terminal commands
- `list_processes`: View running processes
- `kill_process`: Terminate processes
- `get_system_info`: System information
3. **Web Tools**:
- `duckduckgo`: Search for programming resources
## Features
<CardGroup cols={2}>
<Card title="Code Execution" icon="play">
Run and test code directly.
</Card>
<Card title="Code Analysis" icon="magnifying-glass-code">
Analyze and improve code quality.
</Card>
<Card title="System Integration" icon="terminal">
Execute system commands and manage processes.
</Card>
<Card title="Package Management" icon="box">
Handle dependencies and installations.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Create and run a data analysis script
response = agent.start("""
1. Create a script that:
- Uses pandas for data analysis
- Reads a CSV file
- Performs basic statistics
- Creates a visualization
2. Check and install required packages
3. Execute and analyze the results
""")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex development workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving code quality
- Check out the [Data Analyst Agent](/agents/data-analyst) for specialized data analysis
+109
View File
@@ -0,0 +1,109 @@
---
title: "Recommendation Agent"
sidebarTitle: "Recommendation"
description: "Learn how to create AI agents for personalized recommendations across various domains."
icon: "thumbs-up"
---
```mermaid
flowchart LR
In[User Preferences] --> Search[Content Search]
Search --> Analyzer[Preference Analyzer]
Analyzer --> Generator[Recommendation Generator]
Generator --> Out[Recommendations]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Recommendation Agent can analyze preferences and generate personalized recommendations.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `recommendation_system.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Recommendation Agent
recommendation_agent = Agent(
name="RecommendationEngine",
role="Recommendation Specialist",
goal="Generate personalized recommendations based on preferences",
instructions="You are a Recommendation Agent",
tools=[duckduckgo]
)
# Get recommendations
response = recommendation_agent.start(
"Recommend me a good movie to watch in 2025"
)
# Save recommendations
with open('recommendations.txt', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Recommendation System
The Recommendation Agent uses multiple approaches to generate personalized suggestions:
1. **Content Search**: Uses DuckDuckGo to find current options
2. **Preference Analysis**: Understands user preferences
3. **Recommendation Generation**: Creates personalized suggestions
4. **Content Filtering**: Filters based on relevance and quality
## Features
<CardGroup cols={2}>
<Card title="Personalization" icon="user">
Tailored recommendations based on preferences.
</Card>
<Card title="Real-time Data" icon="clock">
Up-to-date content and information.
</Card>
<Card title="Multi-domain" icon="layer-group">
Recommendations across various categories.
</Card>
<Card title="Content Filtering" icon="filter">
Quality-based content selection.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Get personalized recommendations
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(instructions="You are a Recommendation Agent", tools=[duckduckgo])
agent.start("Recommend me a good movie to watch in 2025")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex recommendation systems
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendation accuracy
- Check out the [Research Agent](/agents/research) for detailed content research
+108
View File
@@ -0,0 +1,108 @@
---
title: "Research Agent"
sidebarTitle: "Research"
description: "Learn how to create AI agents for conducting comprehensive research and analysis."
icon: "magnifying-glass-chart"
---
```mermaid
flowchart LR
In[Research Query] --> Search[Web Search]
Search --> Analyzer[Content Analyzer]
Analyzer --> Synthesizer[Information Synthesizer]
Synthesizer --> Out[Research Report]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Synthesizer fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Research Agent can gather, analyze, and synthesize information from various sources.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `research_assistant.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Research Agent
research_agent = Agent(
name="ResearchAssistant",
role="Research Specialist",
goal="Conduct comprehensive research and analysis",
instructions="You are a Research Agent",
tools=[duckduckgo]
)
# Conduct research
response = research_agent.start(
"Research about AI developments in 2024"
)
# Save research findings
with open('research_report.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Research Process
The Research Agent employs a systematic approach to information gathering and analysis:
1. **Web Search**: Uses DuckDuckGo to find relevant sources
2. **Content Analysis**: Evaluates source credibility and relevance
3. **Information Synthesis**: Combines findings into coherent insights
4. **Report Generation**: Creates structured research reports
## Features
<CardGroup cols={2}>
<Card title="Web Research" icon="globe">
Comprehensive online information gathering.
</Card>
<Card title="Content Analysis" icon="microscope">
In-depth evaluation of sources.
</Card>
<Card title="Information Synthesis" icon="layer-group">
Integration of multiple sources.
</Card>
<Card title="Report Generation" icon="file-lines">
Structured research documentation.
</Card>
</CardGroup>
## Example Usage
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(instructions="You are a Research Agent", tools=[duckduckgo])
agent.start("Research about AI 2024")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex research projects
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving research quality
- Check out the [Data Analyst Agent](/agents/data-analyst) for data-driven research
+109
View File
@@ -0,0 +1,109 @@
---
title: "Shopping Agent"
sidebarTitle: "Shopping"
description: "Learn how to create AI agents for price comparison and shopping assistance."
icon: "shop"
---
```mermaid
flowchart LR
In[Product Query] --> Search[Store Search]
Search --> Analyzer[Price Analyzer]
Analyzer --> Comparator[Price Comparator]
Comparator --> Out[Price Report]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Comparator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Shopping Agent can search for products, compare prices, and provide shopping recommendations.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `shopping_assistant.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Shopping Agent
shopping_agent = Agent(
name="ShoppingAssistant",
role="Shopping Specialist",
goal="Find the best prices and deals across stores",
instructions="You are a Shopping Agent",
tools=[duckduckgo]
)
# Search for product prices
response = shopping_agent.start(
"I want to buy iPhone 16 Pro Max, check 5 stores and give me price in table"
)
# Save price comparison
with open('price_comparison.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Shopping Assistant
The Shopping Agent combines multiple capabilities for effective price comparison:
1. **Store Search**: Uses DuckDuckGo to find retailers
2. **Price Analysis**: Gathers pricing information
3. **Price Comparison**: Compares prices across stores
4. **Deal Finding**: Identifies special offers and discounts
## Features
<CardGroup cols={2}>
<Card title="Price Comparison" icon="scale-balanced">
Compare prices across multiple stores.
</Card>
<Card title="Deal Detection" icon="tag">
Find special offers and discounts.
</Card>
<Card title="Store Analysis" icon="store">
Evaluate retailer reliability.
</Card>
<Card title="Price Tracking" icon="chart-line">
Monitor price changes over time.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Compare product prices
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(instructions="You are a Shopping Agent", tools=[duckduckgo])
agent.start("I want to buy iPhone 16 Pro Max, check 5 stores and give me price in table")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex shopping research
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving price accuracy
- Check out the [Research Agent](/agents/research) for detailed product research
+102
View File
@@ -0,0 +1,102 @@
---
title: "Single Agent"
sidebarTitle: "Single"
description: "Learn how to create a basic single-purpose AI agent for simple tasks."
icon: "circle-1"
---
```mermaid
flowchart LR
In[Input] --> Agent[Single Agent]
Agent --> Out[Output]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how to create and use a simple single-purpose agent.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `simple_agent.py`:
```python
from praisonaiagents import Agent
agent = Agent(instructions="You are a Markdown Agent, output in markdown format")
agent.start("Write a blog post about AI")
```
</Step>
</Steps>
## Understanding Single Agent
The Single Agent is the simplest form of PraisonAI agent:
1. **Simple Setup**: Minimal configuration required
2. **Single Purpose**: Focused on one specific task
3. **Direct Execution**: Straightforward input-output flow
4. **No Dependencies**: No external tools required
## Features
<CardGroup cols={2}>
<Card title="Simple Setup" icon="square-1">
Minimal configuration needed.
</Card>
<Card title="Focused Task" icon="bullseye">
Single-purpose execution.
</Card>
<Card title="Quick Start" icon="bolt">
Rapid implementation.
</Card>
<Card title="No Tools" icon="toolbox">
No external dependencies.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Create a content generation agent
from praisonaiagents import Agent
# Create content agent
agent = Agent(
instructions="You are a Content Generation Agent, create engaging content"
)
# Generate content
response = agent.start("""
Write a short story about:
- A future world
- With advanced AI
- And human collaboration
""")
# Save the story
with open('ai_story.txt', 'w') as f:
f.write(response)
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for more complex workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving output quality
- Check out other specialized agents like the [Markdown Agent](/agents/markdown) for specific use cases
+149
View File
@@ -0,0 +1,149 @@
---
title: "Video Agent"
sidebarTitle: "Video"
description: "Learn how to create AI agents for video analysis and content understanding."
icon: "video"
---
```mermaid
flowchart LR
In[Video Input] --> Analyzer[Content Analyzer]
Analyzer --> Detector[Object Detector]
Detector --> Transcriber[Text Transcriber]
Transcriber --> Out[Analysis Report]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Detector fill:#2E8B57,color:#fff
style Transcriber fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Video Agent can analyze video content, detect objects, and extract meaningful information.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `video_analyzer.py`:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create Video Analysis Agent
video_agent = Agent(
name="VideoAnalyst",
role="Video Analysis Specialist",
goal="Analyze videos to extract meaningful information",
backstory="""You are an expert in computer vision and video analysis.
You excel at describing content, detecting objects, and understanding context.""",
llm="gpt-4o-mini",
self_reflect=False
)
# Create video analysis task
analysis_task = Task(
name="analyze_video",
description="""Analyze this video and provide:
1. Summary of main events
2. Key objects and people
3. Text and important information
4. Context and setting""",
expected_output="Comprehensive video analysis",
agent=video_agent,
images=["video.mp4"]
)
# Create PraisonAIAgents instance
agents = PraisonAIAgents(
agents=[video_agent],
tasks=[analysis_task],
process="sequential",
verbose=1
)
# Run analysis
agents.start()
```
</Step>
</Steps>
## Understanding Video Analysis
The Video Agent combines multiple capabilities for comprehensive video understanding:
1. **Content Analysis**: Analyzes video scenes and events
2. **Object Detection**: Identifies objects and people
3. **Text Extraction**: Captures text shown in videos
4. **Context Understanding**: Interprets settings and situations
## Features
<CardGroup cols={2}>
<Card title="Scene Analysis" icon="film">
Detailed analysis of video scenes.
</Card>
<Card title="Object Detection" icon="cube">
Identification of objects and people.
</Card>
<Card title="Text Extraction" icon="closed-captioning">
Capture of text and captions.
</Card>
<Card title="Context Analysis" icon="sitemap">
Understanding of video context.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Analyze a presentation video
from praisonaiagents import Agent, Task, PraisonAIAgents
video_agent = Agent(
name="VideoAnalyst",
role="Video Analysis Specialist",
goal="Extract information from presentation videos",
llm="gpt-4o-mini"
)
# Create presentation analysis task
presentation_task = Task(
name="analyze_presentation",
description="""Analyze this presentation video:
1. Extract key points
2. Capture slide content
3. Note speaker's main arguments
4. Summarize Q&A session""",
expected_output="Detailed presentation summary",
agent=video_agent,
images=["presentation.mp4"]
)
# Run analysis
agents = PraisonAIAgents(
agents=[video_agent],
tasks=[presentation_task],
process="sequential"
)
agents.start()
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex video analysis
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
- Check out the [Image Agent](/agents/image) for still image analysis
+124
View File
@@ -0,0 +1,124 @@
---
title: "Web Search Agent"
sidebarTitle: "Web Search"
description: "Learn how to create AI agents for intelligent web searching and information gathering."
icon: "globe"
---
```mermaid
flowchart LR
In[Search Query] --> Search[Web Search]
Search --> Filter[Content Filter]
Filter --> Summarizer[Content Summarizer]
Summarizer --> Out[Search Results]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Filter fill:#2E8B57,color:#fff
style Summarizer fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Web Search Agent can perform intelligent searches and process web content.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `web_search.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Web Search Agent
search_agent = Agent(
name="WebSearcher",
role="Web Search Specialist",
goal="Perform intelligent web searches and gather information",
instructions="You are a Web Search Agent",
tools=[duckduckgo]
)
# Perform search
response = search_agent.start(
"Search about AI developments in 2024"
)
# Save search results
with open('search_results.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Web Search
The Web Search Agent employs sophisticated search strategies:
1. **Query Processing**: Optimizes search queries
2. **Content Filtering**: Filters relevant results
3. **Information Extraction**: Extracts key information
4. **Result Summarization**: Summarizes findings
## Features
<CardGroup cols={2}>
<Card title="Smart Search" icon="magnifying-glass">
Intelligent query processing.
</Card>
<Card title="Content Filtering" icon="filter">
Relevance-based filtering.
</Card>
<Card title="Information Extraction" icon="scissors">
Key information extraction.
</Card>
<Card title="Result Summary" icon="list">
Concise result summaries.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Perform topic research
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(
instructions="You are a Web Search Agent",
tools=[duckduckgo]
)
# Research specific topic
response = agent.start("""
Search for information about quantum computing:
- Recent breakthroughs
- Leading companies
- Current applications
- Future predictions
""")
# Save research results
with open('quantum_computing_research.md', 'w') as f:
f.write(response)
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex search workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving search relevance
- Check out the [Research Agent](/agents/research) for comprehensive research capabilities
+139
View File
@@ -0,0 +1,139 @@
---
title: "Wikipedia Agent"
sidebarTitle: "Wikipedia"
description: "Learn how to create AI agents for searching and extracting information from Wikipedia."
icon: "book"
---
```mermaid
flowchart LR
In[Query] --> Search[Wiki Search]
Search --> Page[Page Retrieval]
Page --> Summary[Content Summary]
Summary --> Out[Knowledge Output]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Page fill:#2E8B57,color:#fff
style Summary fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Wikipedia Agent can search, retrieve, and summarize Wikipedia content.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `wikipedia_assistant.py`:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import (
wiki_search,
wiki_summary,
wiki_page,
wiki_random,
wiki_language
)
# Create Wikipedia Agent
wiki_agent = Agent(
name="WikipediaAssistant",
role="Wikipedia Research Specialist",
goal="Extract and summarize Wikipedia content",
instructions="You are a Wikipedia Agent",
tools=[
wiki_search,
wiki_summary,
wiki_page,
wiki_random,
wiki_language
],
self_reflect=True,
min_reflect=3,
max_reflect=5
)
# Research a topic
response = wiki_agent.start("""
What is the history of AI?
First search the history of AI
Read the page of the history of AI
Get the summary of the page
""")
# Save research results
with open('ai_history.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Wikipedia Research
The Wikipedia Agent provides comprehensive Wikipedia access through multiple tools:
1. **Wiki Search**: `wiki_search` for finding relevant articles
2. **Page Access**: `wiki_page` for retrieving full articles
3. **Summarization**: `wiki_summary` for concise overviews
4. **Random Articles**: `wiki_random` for discovering content
5. **Language Support**: `wiki_language` for multilingual access
## Features
<CardGroup cols={2}>
<Card title="Article Search" icon="magnifying-glass">
Find relevant Wikipedia articles.
</Card>
<Card title="Content Retrieval" icon="book-open">
Access complete article content.
</Card>
<Card title="Summarization" icon="compress">
Generate concise article summaries.
</Card>
<Card title="Multilingual" icon="language">
Access content in multiple languages.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Research a scientific topic
from praisonaiagents import Agent
from praisonaiagents.tools import wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language
agent = Agent(
instructions="You are a Wikipedia Agent",
tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language],
self_reflect=True,
min_reflect=3,
max_reflect=5,
)
agent.start(
"What is the history of AI?"
"First search the history of AI"
"Read the page of the history of AI"
"Get the summary of the page"
)
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex Wikipedia research
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving research quality
- Check out the [Research Agent](/agents/research) for broader research capabilities
+1 -1
View File
@@ -110,7 +110,7 @@ Loads environment variables from .env file or system and sets them.</p>
file.write(&#34;FROM python:3.11-slim\n&#34;)
file.write(&#34;WORKDIR /app\n&#34;)
file.write(&#34;COPY . .\n&#34;)
file.write(&#34;RUN pip install flask praisonai==2.0.40 gunicorn markdown\n&#34;)
file.write(&#34;RUN pip install flask praisonai==2.0.61 gunicorn markdown\n&#34;)
file.write(&#34;EXPOSE 8080\n&#34;)
file.write(&#39;CMD [&#34;gunicorn&#34;, &#34;-b&#34;, &#34;0.0.0.0:8080&#34;, &#34;api:app&#34;]\n&#39;)
+25 -103
View File
@@ -4,11 +4,8 @@ description: "Understanding Agents in PraisonAI"
icon: "user"
---
<Note>
Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.
</Note>
# Understanding Agents
Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.
```mermaid
graph LR
@@ -19,45 +16,34 @@ graph LR
Agent2 --> Output([✓ Output])
Process -.-> Agent1
%% Styling for main elements
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
style Process fill:#5C80BC,stroke:#7C90A0,color:#fff
%% Define subgraphs for agents and their tasks
subgraph Agent1[" "]
subgraph Agent1[ ]
Task1[📋 Task]
AgentIcon1[🤖 AI Agent]
Tools1[🔧 Tools]
Task1 --- AgentIcon1
AgentIcon1 --- Tools1
style Task1 fill:#2D3047,stroke:#7C90A0,color:#fff
style AgentIcon1 fill:#5C80BC,stroke:#7C90A0,color:#fff
style Tools1 fill:#2D3047,stroke:#7C90A0,color:#fff
end
subgraph Agent2[" "]
subgraph Agent2[ ]
Task2[📋 Task]
AgentIcon2[🤖 AI Agent]
Tools2[🔧 Tools]
Task2 --- AgentIcon2
AgentIcon2 --- Tools2
style Task2 fill:#2D3047,stroke:#7C90A0,color:#fff
style AgentIcon2 fill:#5C80BC,stroke:#7C90A0,color:#fff
style Tools2 fill:#2D3047,stroke:#7C90A0,color:#fff
end
%% Style for agent containers
style Agent1 fill:#1B1F3B,stroke:#7C90A0,color:#fff
style Agent2 fill:#1B1F3B,stroke:#7C90A0,color:#fff
%% Global styles
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
linkStyle default stroke:#7C90A0,stroke-width:2px
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Start,Output,Task1,Task2 input
class Process,AgentIcon1,AgentIcon2 process
class Tools1,Tools2 tools
class Agent1,Agent2 transparent
```
## Key Components
@@ -126,86 +112,22 @@ graph LR
<Step title="Create Agent">
Create `app.py`:
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent, Task, PraisonAIAgents
```python Single Agent
from praisonaiagents import Agent
# Create an agent
researcher = Agent(
name="Researcher",
role="Senior Research Analyst",
goal="Uncover cutting-edge developments in AI",
backstory="You are an expert at a technology research group",
verbose=True,
llm="gpt-4o"
)
agent = Agent(instructions="Your are a helpful AI assistant")
agent.start("Write a movie script about a robot in Mars")
```
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
```python Multi Agents
from praisonaiagents import Agent, PraisonAIAgents
# Run the agents
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
verbose=False
)
research_agent = Agent(instructions="Research about AI")
summarise_agent = Agent(instructions="Summarise research agent's findings")
result = agents.start()
```
```python Multiple Agents
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create multiple agents
researcher = Agent(
name="Researcher",
role="Senior Research Analyst",
goal="Uncover cutting-edge developments in AI",
backstory="You are an expert at a technology research group",
verbose=True,
llm="gpt-4o",
markdown=True
)
writer = Agent(
name="Writer",
role="Tech Content Strategist",
goal="Craft compelling content on tech advancements",
backstory="You are a content strategist",
llm="gpt-4o",
markdown=True
)
# Define multiple tasks
task1 = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
task2 = Task(
name="writing_task",
description="Create a blog post about AI advancements",
expected_output="A blog post",
agent=writer
)
# Run with hierarchical process
agents = PraisonAIAgents(
agents=[researcher, writer],
tasks=[task1, task2],
verbose=False,
process="hierarchical",
manager_llm="gpt-4o"
)
result = agents.start()
```
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
agents.start()
```
</CodeGroup>
</Step>
+241
View File
@@ -0,0 +1,241 @@
---
title: "AI Agents with Knowledge"
sidebarTitle: "Knowledge"
description: "Learn how to create AI agents with custom knowledge bases"
icon: "book"
---
```mermaid
flowchart LR
subgraph In[Input]
PDF[PDF]
TXT[TXT]
MD[MD]
end
subgraph Router[Vector Store]
DB[(Vector DB)]
end
subgraph Out[Agents]
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
In --> Router
Router --> A1
Router --> A2
Router --> A3
style In fill:#8B0000,color:#fff
style Router fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|---------|--------------------------------|---------------------------|
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
| Purpose | Provide static reference information | Store dynamic context and interactions |
| Storage | Read-only knowledge base | Read-write memory store |
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
## Quick Start
<Steps>
<Step title="Install Package">
Install PraisonAI Agents with knowledge support:
```bash
pip install "praisonaiagents[knowledge]"
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key:
```bash
export OPENAI_API_KEY=xxxxx
```
</Step>
<Step title="Create Script">
Create a new file `app.py`:
```python
from praisonaiagents import Agent
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"]
)
agent.start("What is KAG in one line?")
```
</Step>
</Steps>
## Basic Usage
The simplest way to create a knowledge-based agent is without any configuration:
```python
from praisonaiagents import Agent
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"]
)
agent.start("What is KAG in one line?")
```
## Advanced Configuration
For more control over the knowledge base, you can specify a configuration:
```python
from praisonaiagents import Agent
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "custom_knowledge",
"path": ".praison",
}
}
}
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"],
knowledge_config=config
)
agent.start("What is KAG in one line?")
```
## Multi-Agent Knowledge System
For more complex scenarios, you can create a knowledge-based system with multiple agents:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import logging
import os
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Define the configuration for the Knowledge instance
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "knowledge_test",
"path": ".praison",
}
}
}
# Create an agent with knowledge capabilities
knowledge_agent = Agent(
name="KnowledgeAgent",
role="Information Specialist",
goal="Store and retrieve knowledge efficiently",
backstory="Expert in managing and utilizing stored knowledge",
knowledge=["sample.pdf"],
knowledge_config=config,
verbose=True
)
# Define a task for the agent
knowledge_task = Task(
name="knowledge_task",
description="Who is Mervin Praison?",
expected_output="Answer to the question",
agent=knowledge_agent
)
# Create and start the agents
agents = PraisonAIAgents(
agents=[knowledge_agent],
tasks=[knowledge_task],
process="sequential",
user_id="user1"
)
# Start execution
result = agents.start()
```
## Understanding Knowledge Configuration
<AccordionGroup>
<Accordion title="Vector Store Options">
- **Provider**: Choose between different vector store backends (e.g., "chroma")
- **Collection Name**: Name for your knowledge collection
- **Path**: Location to store the vector database
</Accordion>
<Accordion title="Supported File Types">
- PDF documents (*.pdf)
- Text files (*.txt)
- Markdown files (*.md, *.mdx)
- And more...
</Accordion>
<Accordion title="Multi-Agent Setup">
- **Role**: Define specialized roles for knowledge agents
- **Goal**: Set specific knowledge management objectives
- **Process**: Choose between sequential or parallel execution
</Accordion>
</AccordionGroup>
## Features
<CardGroup cols={2}>
<Card title="Custom Knowledge" icon="book">
Import your own documents and data as knowledge sources
</Card>
<Card title="Vector Storage" icon="database">
Efficient storage and retrieval of knowledge embeddings
</Card>
<Card title="Multiple Sources" icon="layer-group">
Combine multiple documents and file types
</Card>
<Card title="Persistent Storage" icon="hard-drive">
Save and reuse knowledge bases across sessions
</Card>
</CardGroup>
## Best Practices
1. **Document Preparation**
- Clean and well-formatted documents work best
- Break large documents into smaller chunks
- Use consistent formatting
2. **Knowledge Organization**
- Group related documents together
- Use meaningful file names
- Keep knowledge bases focused and relevant
3. **Performance Optimization**
- Monitor vector store size
- Clean up unused collections
- Use appropriate chunk sizes
4. **Multi-Agent Coordination**
- Define clear roles and responsibilities
- Set appropriate logging levels for debugging
- Use unique collection names for different agent groups
## Next Steps
- Learn about [Memory Management](/concepts/memory) for long-term recall
- Explore [Tool Integration](/concepts/tools) for enhanced capabilities
- Check out [Examples](/examples) for implementation ideas
+43 -12
View File
@@ -5,6 +5,48 @@ description: "Learn how to create AI agents with memory capabilities for maintai
icon: "brain"
---
```mermaid
flowchart TB
subgraph Memory
direction TB
STM[Short Term]
LTM[Long Term]
end
subgraph Store
direction TB
DB[(Vector DB)]
end
Input[Input] ---> Agents
subgraph Agents
direction LR
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
Agents ---> Output[Output]
Memory <--> Store
Store <--> A1
Store <--> A2
Store <--> A3
style Memory fill:#189AB4,color:#fff
style Store fill:#2E8B57,color:#fff
style Agents fill:#8B0000,color:#fff
style Input fill:#8B0000,color:#fff
style Output fill:#8B0000,color:#fff
```
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|---------|--------------------------------|---------------------------|
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
| Purpose | Provide static reference information | Store dynamic context and interactions |
| Storage | Read-only knowledge base | Read-write memory store |
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
## Quick Start
<Tabs>
@@ -396,16 +438,6 @@ PraisonAI's memory system includes several types of memory:
- Semantic search capabilities with RAG
- Quality-based storage decisions
</Card>
<Card title="Entity Memory" icon="diagram-project">
- Store information about specific entities
- Track relationships and attributes
- Specialized search for entity information
</Card>
<Card title="User Memory" icon="user">
- Store user-specific information
- Personalized context for each user
- Persistent across sessions
</Card>
</CardGroup>
### Memory Quality Control
@@ -437,5 +469,4 @@ results = agents.memory.search_long_term(
query="search query",
min_quality=0.8, # Only return high-quality matches
limit=5 # Maximum number of results
)
```
)
+78
View File
@@ -36,6 +36,24 @@ Process types in PraisonAI define how tasks are executed and how agents collabor
## Sequential Process
```mermaid
graph LR
Input[Input] --> A1
subgraph Agents
direction LR
A1[Agent 1] --> A2[Agent 2] --> A3[Agent 3]
end
A3 --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class A1,A2,A3 process
class Agents transparent
```
The simplest form of task execution where tasks are performed one after another.
<Card>
@@ -57,6 +75,39 @@ The simplest form of task execution where tasks are performed one after another.
## Hierarchical Process
```mermaid
graph TB
Input[Input] --> Manager
subgraph Agents
Manager[Manager Agent]
subgraph Workers
direction LR
W1[Worker 1]
W2[Worker 2]
W3[Worker 3]
end
Manager --> W1
Manager --> W2
Manager --> W3
end
W1 --> Manager
W2 --> Manager
W3 --> Manager
Manager --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Manager,W1,W2,W3 process
class Agents,Workers transparent
```
Uses a manager agent to coordinate task execution and agent assignments.
<Card>
@@ -79,6 +130,33 @@ Uses a manager agent to coordinate task execution and agent assignments.
## Workflow Process
```mermaid
graph LR
Input[Input] --> Start
subgraph Workflow
direction LR
Start[Start] --> C1{Condition}
C1 --> |Yes| A1[Agent 1]
C1 --> |No| A2[Agent 2]
A1 --> Join
A2 --> Join
Join --> A3[Agent 3]
end
A3 --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef decision fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Start,A1,A2,A3,Join process
class C1 decision
class Workflow transparent
```
Advanced process type supporting complex task relationships and conditional execution.
<Card>
+30 -3
View File
@@ -4,9 +4,36 @@ description: "Understanding Tasks in PraisonAI"
icon: "list-check"
---
<Note>
Tasks are the fundamental units of work in PraisonAI, defining what needs to be done, how it should be done, and who should do it.
</Note>
# Understanding Tasks
Tasks are units of work that agents execute. Each task has a clear goal, input requirements, and expected outputs.
```mermaid
graph LR
Input[Input] ---> Task
subgraph Task
direction LR
Role[Role]
Goal[Goal]
Story[Backstory]
Expected[Expected Output]
Role --> Goal
Goal --> Story
Story --> Expected
end
Task ---> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Role,Goal,Story,Expected process
class Task transparent
```
## Core Components
+41 -4
View File
@@ -1,12 +1,49 @@
---
title: "Tools"
description: "Understanding Tools in PraisonAI"
title: "AI Agents with Tools"
sidebarTitle: "Tools"
description: "Learn how to create AI agents that can use tools to interact with external systems and perform actions."
icon: "screwdriver-wrench"
---
# Understanding Tools
```mermaid
flowchart TB
subgraph Tools
direction TB
T3[Internet Search]
T1[Code Execution]
T2[Formatting]
end
Tools in PraisonAI are functions that agents can use to interact with external systems, perform computations, or access data. They extend the capabilities of agents beyond just language processing.
Input[Input] ---> Agents
subgraph Agents
direction LR
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
Agents ---> Output[Output]
T3 --> A1
T1 --> A2
T2 --> A3
style Tools fill:#189AB4,color:#fff
style Agents fill:#8B0000,color:#fff
style Input fill:#8B0000,color:#fff
style Output fill:#8B0000,color:#fff
```
| Feature | [Knowledge](/concepts/knowledge) | [Tools](/concepts/tools) |
|---------|--------------------------------|---------------------------|
| Purpose | Static reference information | Dynamic interaction capabilities |
| Access | Read-only reference | Execute actions and commands |
| Updates | Manual through files | Real-time through tool calls |
| Storage | Knowledge base | Assigned to specific agents |
| Persistence | Permanent until changed | Available during agent execution |
## Quick Start
Tools are functions that agents can use to interact with external systems and perform actions. They are essential for creating agents that can do more than just process text.
## Creating Custom Tool
<Steps>
+75
View File
@@ -0,0 +1,75 @@
---
title: 'Local Development'
description: 'Set up local development environment with Docker and live reload'
---
## Logging
```bash
export LOGLEVEL=info
```
Advanced logging:
```bash
export LOGLEVEL=debug
```
## Local Docker Development with Live Reload
To facilitate local development with live reload, you can use Docker. Follow the steps below:
### 1. Create Dockerfile.dev
<CodeGroup>
```dockerfile Dockerfile.dev
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.18 watchdog
EXPOSE 5555
ENV FLASK_ENV=development
CMD ["flask", "run", "--host=0.0.0.0"]
```
</CodeGroup>
### 2. Create docker-compose.yml
<CodeGroup>
```yaml docker-compose.yml
version: '3.8'
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
volumes:
- .:/app
ports:
- "5555:5555"
environment:
FLASK_ENV: development
command: flask run --host=0.0.0.0
watch:
image: alpine:latest
volumes:
- .:/app
command: sh -c "apk add --no-cache inotify-tools && while inotifywait -r -e modify,create,delete /app; do kill -HUP 1; done"
```
</CodeGroup>
### 3. Run Docker Compose
<CodeGroup>
```bash Terminal
docker-compose up
```
</CodeGroup>
This setup will allow you to develop locally with live reload, making it easier to test and iterate on your code.
+244
View File
@@ -0,0 +1,244 @@
---
title: "Adaptive Learning"
description: "Learn how to create AI agents for personalized adaptive learning experiences."
icon: "graduation-cap"
---
```mermaid
flowchart LR
In[In] --> Assessor[Student Assessor]
Assessor --> Generator[Content Generator]
Generator --> Evaluator[Performance Evaluator]
Evaluator --> Adapter[Difficulty Adapter]
Adapter --> |decrease/increase| Generator
Adapter --> |maintain| Out[Out]
style In fill:#8B0000,color:#fff
style Assessor fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Evaluator fill:#2E8B57,color:#fff
style Adapter fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
Learn how to implement an adaptive learning system using AI agents for personalized education and dynamic content adjustment.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict
def assess_student_level():
"""Simulates student assessment"""
levels = ["beginner", "intermediate", "advanced"]
current_time = int(time.time())
return levels[current_time % 3]
def generate_content(level: str):
"""Simulates content generation"""
content_types = {
"beginner": "basic concepts and examples",
"intermediate": "practice problems and applications",
"advanced": "complex scenarios and projects"
}
return content_types.get(level, "basic concepts")
def evaluate_performance():
"""Simulates performance evaluation"""
scores = ["low", "medium", "high"]
current_time = int(time.time())
return scores[current_time % 3]
def adapt_difficulty(performance: str):
"""Simulates difficulty adaptation"""
adaptations = {
"low": "decrease",
"medium": "maintain",
"high": "increase"
}
return adaptations.get(performance, "maintain")
# Create specialized agents
assessor = Agent(
name="Student Assessor",
role="Level Assessment",
goal="Assess student's current level",
instructions="Evaluate student's knowledge and skills",
tools=[assess_student_level]
)
generator = Agent(
name="Content Generator",
role="Content Creation",
goal="Generate appropriate learning content",
instructions="Create content based on student's level",
tools=[generate_content]
)
evaluator = Agent(
name="Performance Evaluator",
role="Performance Assessment",
goal="Evaluate student's performance",
instructions="Assess learning outcomes",
tools=[evaluate_performance]
)
adapter = Agent(
name="Difficulty Adapter",
role="Content Adaptation",
goal="Adapt content difficulty",
instructions="Adjust difficulty based on performance",
tools=[adapt_difficulty]
)
# Create workflow tasks
assessment_task = Task(
name="assess_level",
description="Assess student's current level",
expected_output="Student's proficiency level",
agent=assessor,
is_start=True,
next_tasks=["generate_content"]
)
generation_task = Task(
name="generate_content",
description="Generate appropriate content",
expected_output="Learning content",
agent=generator,
next_tasks=["evaluate_performance"]
)
evaluation_task = Task(
name="evaluate_performance",
description="Evaluate student's performance",
expected_output="Performance assessment",
agent=evaluator,
next_tasks=["adapt_difficulty"]
)
adaptation_task = Task(
name="adapt_difficulty",
description="Adapt content difficulty",
expected_output="Difficulty adjustment",
agent=adapter,
task_type="decision",
condition={
"decrease": ["generate_content"],
"maintain": "",
"increase": ["generate_content"]
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[assessor, generator, evaluator, adapter],
tasks=[assessment_task, generation_task, evaluation_task, adaptation_task],
process="workflow",
verbose=True
)
def main():
print("\nStarting Adaptive Learning Workflow...")
print("=" * 50)
# Run workflow
results = workflow.start()
# Print results
print("\nAdaptive Learning Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
main()
```
</Step>
<Step title="Start Agents">
Run your adaptive learning system:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
</Note>
## Understanding Adaptive Learning
<Card title="What is Adaptive Learning?" icon="question">
Adaptive learning enables:
- Personalized learning experiences
- Dynamic content adjustment
- Performance-based progression
- Continuous skill assessment
- Intelligent difficulty scaling
</Card>
## Features
<CardGroup cols={2}>
<Card title="Student Assessment" icon="user-graduate">
Evaluate student proficiency:
- Knowledge level assessment
- Skill gap identification
- Learning style analysis
</Card>
<Card title="Content Generation" icon="book">
Create personalized content:
- Level-appropriate materials
- Custom learning paths
- Interactive exercises
</Card>
<Card title="Performance Tracking" icon="chart-line">
Monitor learning progress:
- Real-time evaluation
- Progress tracking
- Achievement metrics
</Card>
<Card title="Dynamic Adaptation" icon="sliders">
Adjust learning experience:
- Difficulty scaling
- Content optimization
- Pace adjustment
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
Learn about chaining prompts for complex workflows
</Card>
<Card title="Evaluator Optimizer" icon="gauge" href="/features/evaluator-optimiser">
Explore how to optimize and evaluate solutions
</Card>
</CardGroup>
+297
View File
@@ -0,0 +1,297 @@
---
title: "Climate Impact"
description: "Learn how to create AI agents for climate impact analysis and adaptation strategies."
icon: "cloud-sun"
---
```mermaid
flowchart LR
In[In] --> Monitor[Environmental Monitor]
Monitor --> Urban[Urban Analyzer]
Urban --> Climate[Climate Modeler]
Climate --> Impact[Impact Predictor]
Impact --> Strategy[Strategy Generator]
Strategy --> Out[Out]
style In fill:#8B0000,color:#fff
style Monitor fill:#2E8B57,color:#fff
style Urban fill:#2E8B57,color:#fff
style Climate fill:#2E8B57,color:#fff
style Impact fill:#2E8B57,color:#fff
style Strategy fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Climate Impact Analysis?
Climate Impact Analysis is a systematic process of collecting environmental data, analyzing urban factors, modeling microclimates, predicting impacts, and generating adaptation strategies. This helps cities and communities understand and prepare for climate change effects, ensuring sustainable urban development and public health.
## Features
<CardGroup cols={2}>
<Card title="Environmental Monitoring" icon="temperature-high">
Collection of temperature, humidity, and air quality data with trend analysis.
</Card>
<Card title="Urban Analysis" icon="city">
Assessment of building density, green spaces, traffic flow, and heat islands.
</Card>
<Card title="Climate Modeling" icon="chart-line">
Microclimate modeling for different urban locations with temperature and air quality impacts.
</Card>
<Card title="Impact Prediction" icon="chart-mixed">
Prediction of health impacts, energy consumption, and livability scores.
</Card>
<Card title="Adaptation Strategies" icon="leaf">
Generation of location-specific strategies for climate adaptation.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def collect_environmental_data():
"""Simulates environmental data collection"""
data = {
"temperature": {
"current": 25 + (time.time() % 10),
"historical": [24, 25, 26, 24, 23],
"trend": "increasing"
},
"humidity": {
"current": 60 + (time.time() % 20),
"historical": [65, 62, 58, 63, 61],
"trend": "stable"
},
"air_quality": {
"pm25": 35 + (time.time() % 15),
"co2": 415 + (time.time() % 30),
"trend": "deteriorating"
}
}
return data
def analyze_urban_factors():
"""Simulates urban environment analysis"""
factors = {
"building_density": 75 + (time.time() % 20),
"green_spaces": 25 + (time.time() % 10),
"traffic_flow": {
"peak_hours": [8, 17],
"congestion_level": "high"
},
"heat_islands": [
{"location": "downtown", "intensity": "high"},
{"location": "industrial", "intensity": "medium"}
]
}
return factors
def model_microclimate(env_data: Dict, urban_factors: Dict):
"""Models microclimate conditions"""
models = []
locations = ["downtown", "residential", "industrial", "parks"]
for location in locations:
models.append({
"location": location,
"temperature_delta": 2 + (time.time() % 3),
"air_quality_impact": "moderate" if "park" in location else "significant",
"humidity_variation": 5 + (time.time() % 5)
})
return models
def predict_impacts(models: List[Dict]):
"""Predicts climate impacts"""
predictions = []
for model in models:
predictions.append({
"location": model["location"],
"health_impact": "high" if model["air_quality_impact"] == "significant" else "medium",
"energy_consumption": {
"cooling_need": model["temperature_delta"] * 10,
"trend": "increasing" if model["temperature_delta"] > 2.5 else "stable"
},
"livability_score": 70 - (model["temperature_delta"] * 5)
})
return predictions
def generate_adaptation_strategies(predictions: List[Dict]):
"""Generates adaptation strategies"""
strategies = []
for pred in predictions:
if pred["health_impact"] == "high":
strategies.append({
"location": pred["location"],
"actions": [
"increase_green_spaces",
"traffic_reduction",
"building_retrofitting"
],
"priority": "immediate",
"cost_estimate": "high"
})
else:
strategies.append({
"location": pred["location"],
"actions": [
"tree_planting",
"cool_roofs"
],
"priority": "medium",
"cost_estimate": "moderate"
})
return strategies
# Create specialized agents
environmental_monitor = Agent(
name="Environmental Monitor",
role="Data Collection",
goal="Collect environmental data",
instructions="Monitor and collect climate data",
tools=[collect_environmental_data]
)
urban_analyzer = Agent(
name="Urban Analyzer",
role="Urban Analysis",
goal="Analyze urban environment",
instructions="Assess urban factors affecting climate",
tools=[analyze_urban_factors]
)
climate_modeler = Agent(
name="Climate Modeler",
role="Climate Modeling",
goal="Model microclimate conditions",
instructions="Create detailed climate models",
tools=[model_microclimate]
)
impact_predictor = Agent(
name="Impact Predictor",
role="Impact Analysis",
goal="Predict climate impacts",
instructions="Assess potential climate impacts",
tools=[predict_impacts]
)
strategy_generator = Agent(
name="Strategy Generator",
role="Strategy Development",
goal="Generate adaptation strategies",
instructions="Develop climate adaptation strategies",
tools=[generate_adaptation_strategies]
)
# Create workflow tasks
monitoring_task = Task(
name="collect_data",
description="Collect environmental data",
expected_output="Environmental measurements",
agent=environmental_monitor,
is_start=True,
next_tasks=["analyze_urban"]
)
urban_task = Task(
name="analyze_urban",
description="Analyze urban factors",
expected_output="Urban analysis",
agent=urban_analyzer,
next_tasks=["model_climate"]
)
modeling_task = Task(
name="model_climate",
description="Model microclimate",
expected_output="Climate models",
agent=climate_modeler,
context=[monitoring_task, urban_task],
next_tasks=["predict_impacts"]
)
prediction_task = Task(
name="predict_impacts",
description="Predict climate impacts",
expected_output="Impact predictions",
agent=impact_predictor,
next_tasks=["generate_strategies"]
)
strategy_task = Task(
name="generate_strategies",
description="Generate adaptation strategies",
expected_output="Adaptation strategies",
agent=strategy_generator,
task_type="decision",
condition={
"immediate": ["collect_data"], # Continuous monitoring for high priority
"medium": "", # End workflow for medium priority
"low": "" # End workflow for low priority
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[environmental_monitor, urban_analyzer, climate_modeler,
impact_predictor, strategy_generator],
tasks=[monitoring_task, urban_task, modeling_task,
prediction_task, strategy_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Climate Impact Prediction Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nClimate Impact Analysis Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+203
View File
@@ -0,0 +1,203 @@
---
title: "Code Analysis Agent"
description: "Learn how to create AI agents for comprehensive code analysis and quality assessment."
icon: "code-merge"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Code Analyzer]
Analyzer --> Quality[Quality Assessment]
Quality --> Metrics[Core Metrics]
Metrics --> Technical[Technical Review]
Technical --> Recommendations[Recommendations]
Recommendations --> Out[Out]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Quality fill:#2E8B57,color:#fff
style Metrics fill:#2E8B57,color:#fff
style Technical fill:#2E8B57,color:#fff
style Recommendations fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Code Analysis?
Code Analysis is a systematic process of evaluating source code to assess its quality, maintainability, performance, and security. This helps developers and organizations maintain high code standards and identify areas for improvement.
## Features
<CardGroup cols={2}>
<Card title="Quality Assessment" icon="chart-simple">
Comprehensive evaluation of code quality with numerical scoring.
</Card>
<Card title="Core Metrics Analysis" icon="gauge">
Analysis of architecture, maintainability, performance, and security.
</Card>
<Card title="Technical Assessment" icon="code">
Review of tech stack, complexity, and best practices adherence.
</Card>
<Card title="Risk Assessment" icon="shield">
Identification of potential risks and security vulnerabilities.
</Card>
<Card title="Recommendations" icon="lightbulb">
Actionable suggestions for improvements and enhancements.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents gitingest
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `code_analysis.py` with the following code:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
from gitingest import ingest
class CodeMetrics(BaseModel):
category: str
score: int
findings: List[str]
class CodeAnalysisReport(BaseModel):
overall_quality: int
code_metrics: List[CodeMetrics]
architecture_score: int
maintainability_score: int
performance_score: int
security_score: int
test_coverage: int
key_strengths: List[str]
improvement_areas: List[str]
tech_stack: List[str]
recommendations: List[str]
complexity_metrics: Dict[str, int]
best_practices: List[Dict[str, str]]
potential_risks: List[str]
documentation_quality: int
code_analyzer = Agent(
role="Code Analysis Expert",
goal="Provide comprehensive code evaluation and recommendations",
backstory="""Expert code analyst specializing in architecture review,
best practices, and technical debt assessment.""",
verbose=True
)
code_analysis_task = Task(
description="""Analyze code repository and provide structured evaluation:
1. Overall Quality (0-100)
2. Core Metrics Analysis:
- Architecture and Design
- Code Maintainability
- Performance Optimization
- Security Practices
- Test Coverage
3. Technical Assessment:
- Technology Stack Review
- Code Complexity Analysis
- Best Practices Adherence
- Risk Assessment
4. Recommendations:
- Key Improvements
- Architecture Suggestions
- Security Enhancements""",
expected_output="Detailed code analysis report with metrics and recommendations",
agent=code_analyzer,
output_pydantic=CodeAnalysisReport
)
def analyze_code(code_source: str) -> CodeAnalysisReport:
"""
Analyze code from directory path or GitHub URL
"""
# Ingest code content
summary, tree, content = ingest(code_source)
# Concatenate context into structured format
context_text = f"""
CODE REPOSITORY ANALYSIS
=======================
SUMMARY
-------
{summary}
REPOSITORY STRUCTURE
-------------------
{tree}
SOURCE CODE
-----------
{content}
"""
# Initialize and run analysis
agents = PraisonAIAgents(
agents=[code_analyzer],
tasks=[code_analysis_task]
)
return agents.start(context_text)
if __name__ == "__main__":
# Example usage
code_source = "https://github.com/openai/openai-python/tree/main/src/openai/cli/_api/chat" # GitHub URL or local directory
result = analyze_code(code_source)
print(result)
```
</Step>
</Steps>
## Understanding the Output
The code analysis generates a comprehensive report with the following components:
- Overall Quality Score (0-100)
- Core Metrics Analysis
- Architecture and Design Score
- Code Maintainability Score
- Performance Score
- Security Score
- Test Coverage Percentage
- Technical Assessment
- Technology Stack
- Complexity Metrics
- Best Practices Review
- Risk Assessment
- Recommendations
- Key Improvements
- Architecture Suggestions
- Security Enhancements
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
<Card title="API Reference" icon="code" href="/api-reference">
Explore the complete API documentation
</Card>
</CardGroup>
+207
View File
@@ -0,0 +1,207 @@
---
title: "Code Review"
sidebarTitle: "Code Review"
description: "Learn how to create AI agents for automated code review and issue resolution."
icon: "code"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Code Analyzer]
Analyzer --> Suggester[Fix Suggester]
Suggester --> Applier[Fix Applier]
Applier -->|fixed| Out[Out]
Applier -->|manual_review| Suggester
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Suggester fill:#2E8B57,color:#fff
style Applier fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how AI agents can automate code review, from analysis through fix suggestion and application.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import List, Dict
def analyze_code_changes():
"""Simulates code analysis"""
issues = [
{"type": "style", "severity": "low", "file": "main.py"},
{"type": "security", "severity": "high", "file": "auth.py"},
{"type": "performance", "severity": "medium", "file": "data.py"}
]
return issues[int(time.time()) % 3]
def suggest_fixes(issue: Dict):
"""Simulates fix suggestions"""
fixes = {
"style": "Apply PEP 8 formatting",
"security": "Implement input validation",
"performance": "Use list comprehension"
}
return fixes.get(issue["type"], "Review manually")
def apply_automated_fix(fix: str):
"""Simulates applying automated fixes"""
success = int(time.time()) % 2 == 0
return "fixed" if success else "manual_review"
# Create specialized agents
analyzer = Agent(
name="Code Analyzer",
role="Code analysis",
goal="Analyze code changes and identify issues",
instructions="Review code changes and report issues",
tools=[analyze_code_changes]
)
fix_suggester = Agent(
name="Fix Suggester",
role="Solution provider",
goal="Suggest fixes for identified issues",
instructions="Provide appropriate fix suggestions",
tools=[suggest_fixes]
)
fix_applier = Agent(
name="Fix Applier",
role="Fix implementation",
goal="Apply suggested fixes automatically when possible",
instructions="Implement suggested fixes and report results",
tools=[apply_automated_fix]
)
# Create workflow tasks
analysis_task = Task(
name="analyze_code",
description="Analyze code changes for issues",
expected_output="Identified code issues",
agent=analyzer,
is_start=True,
next_tasks=["suggest_fixes"]
)
suggestion_task = Task(
name="suggest_fixes",
description="Suggest fixes for identified issues",
expected_output="Fix suggestions",
agent=fix_suggester,
next_tasks=["apply_fixes"]
)
fix_task = Task(
name="apply_fixes",
description="Apply suggested fixes",
expected_output="Fix application status",
agent=fix_applier,
task_type="decision",
condition={
"fixed": "",
"manual_review": ["suggest_fixes"] # Loop back for manual review
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[analyzer, fix_suggester, fix_applier],
tasks=[analysis_task, suggestion_task, fix_task],
process="workflow",
verbose=True
)
def main():
print("\nStarting Code Review Workflow...")
print("=" * 50)
# Run workflow
results = workflow.start()
# Print results
print("\nCode Review Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
main()
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
- Basic understanding of Python
</Note>
## Understanding Code Review
<Card title="What is Code Review?" icon="question">
Automated code review workflow enables:
- Automated issue detection
- Intelligent fix suggestions
- Automated fix application
- Manual review routing when needed
</Card>
## Features
<CardGroup cols={2}>
<Card title="Issue Detection" icon="magnifying-glass">
Automatically identify code issues and their severity.
</Card>
<Card title="Fix Suggestions" icon="lightbulb">
Generate appropriate fix suggestions based on issue type.
</Card>
<Card title="Automated Fixes" icon="wand-magic-sparkles">
Apply fixes automatically when possible.
</Card>
<Card title="Manual Review" icon="user-check">
Route complex issues for manual review.
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
Learn about sequential prompt execution
</Card>
<Card title="Evaluator Optimizer" icon="magnifying-glass-chart" href="/features/evaluator-optimiser">
Explore optimization techniques
</Card>
</CardGroup>
+316
View File
@@ -0,0 +1,316 @@
---
title: "Crypto Validator"
description: "Learn how to create AI agents for post-quantum cryptographic scheme validation and security analysis."
icon: "key"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Crypto Analyzer]
Analyzer --> Quantum[Attack Simulator]
Analyzer --> Perf[Performance Benchmarker]
Quantum --> Security[Implementation Assessor]
Perf --> Security
Security --> Compliance[Compliance Validator]
Compliance --> Out[Out]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Quantum fill:#2E8B57,color:#fff
style Perf fill:#2E8B57,color:#fff
style Security fill:#2E8B57,color:#fff
style Compliance fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Post-Quantum Cryptography?
Post-quantum cryptography focuses on developing cryptographic systems that are secure against both quantum and classical computers. This involves analyzing cryptographic schemes, simulating quantum attacks, and ensuring compliance with security standards.
## Features
<CardGroup cols={2}>
<Card title="Cryptographic Analysis" icon="shield-check">
Analyze quantum-resistant cryptographic schemes including lattice-based encryption and multivariate signatures.
</Card>
<Card title="Attack Simulation" icon="bug">
Test resistance against quantum attacks including Grover's algorithm and Shor's algorithm.
</Card>
<Card title="Performance Testing" icon="gauge-high">
Benchmark key generation, encryption/decryption speeds, and throughput metrics.
</Card>
<Card title="Security Assessment" icon="lock">
Evaluate implementation security including side-channel resistance and hardening measures.
</Card>
<Card title="Compliance Validation" icon="certificate">
Verify compliance with NIST PQC, Common Criteria, and FIPS standards.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_cryptographic_scheme():
"""Simulates cryptographic scheme analysis"""
schemes = [
{
"name": "lattice_based",
"type": "encryption",
"key_size": 2048,
"security_level": "AES-256 equivalent",
"parameters": {
"lattice_dimension": 1024,
"modulus": "q = 2^32 - 1",
"error_distribution": "discrete_gaussian"
}
},
{
"name": "multivariate",
"type": "signature",
"key_size": 4096,
"security_level": "SHA-384 equivalent",
"parameters": {
"variables": 128,
"equations": 128,
"field_size": "2^8"
}
}
]
return schemes[int(time.time()) % 2]
def simulate_quantum_attacks(scheme: Dict):
"""Simulates quantum attack scenarios"""
attacks = {
"grover_search": {
"effectiveness": "reduced",
"quantum_speedup": "quadratic",
"estimated_qubits": 2048,
"time_complexity": "O(2^n/2)"
},
"shor_algorithm": {
"effectiveness": "ineffective",
"quantum_speedup": "none",
"vulnerability": "resistant",
"classical_hardness": "maintained"
},
"quantum_hidden_subgroup": {
"effectiveness": "partial",
"applicability": "limited",
"mitigation": "parameter_adjustment"
}
}
return attacks
def benchmark_performance(scheme: Dict):
"""Benchmarks cryptographic performance"""
benchmarks = {
"key_generation": {
"time": 0.5 + (time.time() % 1) / 10, # seconds
"memory": 128 + (int(time.time()) % 64) # MB
},
"encryption_speed": {
"small_message": 0.001 + (time.time() % 1) / 1000, # seconds
"large_message": 0.1 + (time.time() % 1) / 10 # seconds
},
"decryption_speed": {
"small_message": 0.002 + (time.time() % 1) / 1000,
"large_message": 0.15 + (time.time() % 1) / 10
},
"throughput": {
"encryption": 100 + (int(time.time()) % 50), # MB/s
"decryption": 80 + (int(time.time()) % 40) # MB/s
}
}
return benchmarks
def assess_implementation(scheme: Dict, benchmarks: Dict):
"""Assesses implementation security"""
assessment = {
"side_channel_resistance": {
"timing_attacks": "protected",
"power_analysis": "partial_vulnerability",
"cache_attacks": "mitigated"
},
"implementation_hardening": {
"constant_time": True,
"memory_protection": True,
"error_handling": "secure"
},
"compiler_optimizations": {
"safety": "verified",
"performance_impact": -0.05 + (time.time() % 1) / 10
}
}
return assessment
def validate_compliance(scheme: Dict, assessment: Dict):
"""Validates compliance and standards"""
compliance = {
"nist_pqc": {
"status": "submitted",
"round": 3,
"requirements_met": True
},
"common_criteria": {
"evaluation_level": "EAL4+",
"protection_profile": "compliant"
},
"fips_140_3": {
"security_level": 3,
"validation_status": "in_process"
}
}
return compliance
# Create specialized agents
crypto_analyzer = Agent(
name="Crypto Analyzer",
role="Cryptographic Analysis",
goal="Analyze cryptographic schemes",
instructions="Evaluate quantum-resistant cryptographic schemes",
tools=[analyze_cryptographic_scheme]
)
attack_simulator = Agent(
name="Attack Simulator",
role="Attack Simulation",
goal="Simulate quantum attacks",
instructions="Test resistance against quantum attacks",
tools=[simulate_quantum_attacks]
)
performance_benchmarker = Agent(
name="Performance Benchmarker",
role="Performance Testing",
goal="Benchmark cryptographic performance",
instructions="Measure performance metrics",
tools=[benchmark_performance]
)
implementation_assessor = Agent(
name="Implementation Assessor",
role="Implementation Assessment",
goal="Assess implementation security",
instructions="Evaluate implementation security",
tools=[assess_implementation]
)
compliance_validator = Agent(
name="Compliance Validator",
role="Compliance Validation",
goal="Validate standards compliance",
instructions="Verify compliance with standards",
tools=[validate_compliance]
)
# Create workflow tasks
analysis_task = Task(
name="analyze_crypto",
description="Analyze cryptographic scheme",
expected_output="Cryptographic analysis",
agent=crypto_analyzer,
is_start=True,
next_tasks=["simulate_attacks", "benchmark_performance"]
)
attack_task = Task(
name="simulate_attacks",
description="Simulate quantum attacks",
expected_output="Attack simulation results",
agent=attack_simulator,
next_tasks=["assess_implementation"]
)
benchmark_task = Task(
name="benchmark_performance",
description="Benchmark performance",
expected_output="Performance benchmarks",
agent=performance_benchmarker,
next_tasks=["assess_implementation"]
)
assessment_task = Task(
name="assess_implementation",
description="Assess implementation",
expected_output="Implementation assessment",
agent=implementation_assessor,
context=[attack_task, benchmark_task],
next_tasks=["validate_compliance"]
)
compliance_task = Task(
name="validate_compliance",
description="Validate compliance",
expected_output="Compliance validation",
agent=compliance_validator,
task_type="decision",
condition={
"compliant": "", # End workflow if compliant
"non_compliant": ["assess_implementation"] # Reassess if non-compliant
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[crypto_analyzer, attack_simulator, performance_benchmarker,
implementation_assessor, compliance_validator],
tasks=[analysis_task, attack_task, benchmark_task,
assessment_task, compliance_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Quantum-Resistant Cryptography Validation Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nCryptography Validation Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+206
View File
@@ -0,0 +1,206 @@
---
title: Customer Service
sidebar_title: Customer Service
icon: "user-group"
---
```mermaid
flowchart LR
In[In] --> Classifier[Query Classifier]
Classifier --> Handler[Query Handler]
Handler --> Evaluator[Satisfaction Evaluator]
Evaluator --> Optimizer[Response Optimizer]
Optimizer --> Out[Out]
Optimizer --> Classifier
style In fill:#8B0000,color:#fff
style Out fill:#8B0000,color:#fff
style Classifier fill:#2E8B57,color:#fff
style Handler fill:#2E8B57,color:#fff
style Evaluator fill:#2E8B57,color:#fff
style Optimizer fill:#2E8B57,color:#fff
```
Learn how to create AI agents for automated customer service and response optimization.
## Quick Start
1. Install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
2. Set your OpenAI API key:
```bash
export OPENAI_API_KEY=your_api_key_here
```
3. Create a file named `app.py`:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
def classify_query():
"""Simulates query classification"""
query_types = [
{"type": "technical", "priority": "high", "complexity": "complex"},
{"type": "billing", "priority": "medium", "complexity": "simple"},
{"type": "general", "priority": "low", "complexity": "simple"}
]
return query_types[int(time.time()) % 3]
def handle_query(query: Dict):
"""Simulates query handling"""
responses = {
"technical": "Technical support solution provided",
"billing": "Billing inquiry resolved",
"general": "General information provided"
}
return responses.get(query["type"], "Query forwarded to specialist")
def evaluate_satisfaction():
"""Simulates satisfaction evaluation"""
scores = ["satisfied", "neutral", "unsatisfied"]
return scores[int(time.time()) % 3]
def optimize_response(satisfaction: str):
"""Simulates response optimization"""
optimizations = {
"satisfied": "maintain_approach",
"neutral": "minor_adjustments",
"unsatisfied": "major_revision"
}
return optimizations.get(satisfaction, "review_process")
# Create specialized agents
classifier = Agent(
name="Query Classifier",
role="Query Classification",
goal="Classify incoming customer queries",
instructions="Analyze and categorize customer queries",
tools=[classify_query]
)
handler = Agent(
name="Query Handler",
role="Query Resolution",
goal="Handle customer queries appropriately",
instructions="Provide appropriate responses to queries",
tools=[handle_query]
)
evaluator = Agent(
name="Satisfaction Evaluator",
role="Satisfaction Assessment",
goal="Evaluate customer satisfaction",
instructions="Assess response effectiveness",
tools=[evaluate_satisfaction]
)
optimizer = Agent(
name="Response Optimizer",
role="Service Optimization",
goal="Optimize service based on feedback",
instructions="Improve response strategies",
tools=[optimize_response]
)
# Create workflow tasks
classification_task = Task(
name="classify_query",
description="Classify customer query",
expected_output="Query classification",
agent=classifier,
is_start=True,
task_type="decision",
condition={
"high": ["handle_query", "evaluate_satisfaction"],
"medium": ["handle_query", "evaluate_satisfaction"],
"low": ["handle_query"]
}
)
handling_task = Task(
name="handle_query",
description="Handle customer query",
expected_output="Query response",
agent=handler,
next_tasks=["evaluate_satisfaction"]
)
evaluation_task = Task(
name="evaluate_satisfaction",
description="Evaluate customer satisfaction",
expected_output="Satisfaction level",
agent=evaluator,
next_tasks=["optimize_response"]
)
optimization_task = Task(
name="optimize_response",
description="Optimize response strategy",
expected_output="Optimization recommendations",
agent=optimizer,
task_type="decision",
condition={
"major_revision": ["classify_query"],
"minor_adjustments": "",
"maintain_approach": ""
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[classifier, handler, evaluator, optimizer],
tasks=[classification_task, handling_task, evaluation_task, optimization_task],
process="workflow",
verbose=True
)
def main():
print("\nStarting Customer Service Optimization Workflow...")
print("=" * 50)
# Run workflow
results = workflow.start()
# Print results
print("\nCustomer Service Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
main()
```
4. Run the system:
```bash
python app.py
```
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key
</Note>
## Understanding Customer Service
The customer service workflow demonstrates how AI agents can automate and optimize customer support operations. The system uses specialized agents to classify queries, handle responses, evaluate satisfaction, and continuously improve service quality through feedback-driven optimization.
## Features
- **Query Classification**: Automatically categorizes customer inquiries based on type, priority, and complexity
- **Intelligent Response Handling**: Provides appropriate responses based on query classification
- **Satisfaction Evaluation**: Assesses customer satisfaction with provided solutions
- **Response Optimization**: Continuously improves service quality through feedback analysis
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining)
- Explore [Evaluator Optimizer](/features/evaluator-optimiser)
+302
View File
@@ -0,0 +1,302 @@
---
title: "DeFi Market Maker"
description: "Learn how to create AI agents for decentralized finance market making and arbitrage."
icon: "chart-line"
---
```mermaid
flowchart LR
In[In] --> Market[Market Analyzer]
Market --> Arbitrage[Arbitrage Detector]
Market --> Liquidity[Liquidity Optimizer]
Arbitrage --> Risk[Risk Assessor]
Liquidity --> Risk
Risk --> Executor[Trade Executor]
Executor --> Out[Out]
style In fill:#8B0000,color:#fff
style Market fill:#2E8B57,color:#fff
style Arbitrage fill:#2E8B57,color:#fff
style Liquidity fill:#2E8B57,color:#fff
style Risk fill:#2E8B57,color:#fff
style Executor fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is DeFi Market Making?
Decentralized Finance (DeFi) market making involves providing liquidity to decentralized exchanges and automatically executing trades to capture arbitrage opportunities. This requires real-time analysis of market conditions, optimization of liquidity positions, and risk management.
## Features
<CardGroup cols={2}>
<Card title="Market Analysis" icon="chart-candlestick">
Real-time analysis of liquidity pools, market volatility, trading volumes, and gas prices.
</Card>
<Card title="Arbitrage Detection" icon="magnifying-glass-dollar">
Identification of profitable trading opportunities across different liquidity pools.
</Card>
<Card title="Liquidity Optimization" icon="water">
Optimization of liquidity distribution and pool ratios for maximum efficiency.
</Card>
<Card title="Risk Assessment" icon="shield-halved">
Comprehensive risk analysis including impermanent loss and smart contract risks.
</Card>
<Card title="Trade Execution" icon="money-bill-transfer">
Automated execution of optimized trades with performance monitoring.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_market_conditions():
"""Simulates market analysis"""
conditions = {
"liquidity_pools": {
"pool_A": {
"token_0": {"balance": 1000000, "price": 1.0},
"token_1": {"balance": 500000, "price": 2.0},
"total_value_locked": 2000000
},
"pool_B": {
"token_0": {"balance": 800000, "price": 1.0},
"token_1": {"balance": 400000, "price": 2.0},
"total_value_locked": 1600000
}
},
"market_volatility": 0.15 + (time.time() % 10) / 100,
"trading_volume_24h": 5000000 + (time.time() % 1000000),
"gas_prices": 50 + (time.time() % 30)
}
return conditions
def detect_arbitrage():
"""Simulates arbitrage opportunity detection"""
opportunities = [
{
"path": ["pool_A", "pool_B"],
"profit_potential": 0.02 + (time.time() % 5) / 100,
"required_capital": 10000,
"execution_cost": 50,
"risk_level": "low"
},
{
"path": ["pool_B", "pool_C"],
"profit_potential": 0.03 + (time.time() % 5) / 100,
"required_capital": 20000,
"execution_cost": 75,
"risk_level": "medium"
}
]
return opportunities[int(time.time()) % 2]
def optimize_liquidity(market_conditions: Dict):
"""Optimizes liquidity distribution"""
optimizations = {
"pool_A": {
"target_ratio": 2.0,
"suggested_actions": [
{
"action": "rebalance",
"token": "token_1",
"amount": 10000,
"direction": "add"
}
],
"expected_improvement": 0.05
},
"pool_B": {
"target_ratio": 1.8,
"suggested_actions": [
{
"action": "rebalance",
"token": "token_0",
"amount": 5000,
"direction": "remove"
}
],
"expected_improvement": 0.03
}
}
return optimizations
def assess_risks(arbitrage: Dict, optimizations: Dict):
"""Assesses potential risks"""
risk_assessment = {
"impermanent_loss_risk": 0.1 + (time.time() % 5) / 100,
"smart_contract_risk": "low",
"market_manipulation_risk": "medium" if arbitrage["profit_potential"] > 0.025 else "low",
"gas_price_risk": "high" if arbitrage["execution_cost"] > 60 else "medium",
"mitigation_strategies": [
"implement_slippage_protection",
"set_maximum_gas_price",
"use_multiple_liquidity_sources"
]
}
return risk_assessment
def execute_trades(arbitrage: Dict, risks: Dict):
"""Simulates trade execution"""
execution_results = {
"status": "success" if time.time() % 2 == 0 else "failed",
"executed_volume": arbitrage["required_capital"] * 0.95,
"actual_profit": arbitrage["profit_potential"] * 0.9,
"gas_used": arbitrage["execution_cost"] * 1.1,
"timestamp": time.time()
}
return execution_results
# Create specialized agents
market_analyzer = Agent(
name="Market Analyzer",
role="Market Analysis",
goal="Analyze market conditions",
instructions="Monitor and analyze DeFi market conditions",
tools=[analyze_market_conditions]
)
arbitrage_detector = Agent(
name="Arbitrage Detector",
role="Arbitrage Detection",
goal="Detect arbitrage opportunities",
instructions="Identify profitable trading opportunities",
tools=[detect_arbitrage]
)
liquidity_optimizer = Agent(
name="Liquidity Optimizer",
role="Liquidity Optimization",
goal="Optimize liquidity distribution",
instructions="Optimize pool liquidity ratios",
tools=[optimize_liquidity]
)
risk_assessor = Agent(
name="Risk Assessor",
role="Risk Assessment",
goal="Assess trading risks",
instructions="Evaluate potential risks and mitigation strategies",
tools=[assess_risks]
)
trade_executor = Agent(
name="Trade Executor",
role="Trade Execution",
goal="Execute optimized trades",
instructions="Execute trades based on analysis",
tools=[execute_trades]
)
# Create workflow tasks
market_task = Task(
name="analyze_market",
description="Analyze market conditions",
expected_output="Market analysis",
agent=market_analyzer,
is_start=True,
next_tasks=["detect_arbitrage", "optimize_liquidity"]
)
arbitrage_task = Task(
name="detect_arbitrage",
description="Detect arbitrage opportunities",
expected_output="Arbitrage opportunities",
agent=arbitrage_detector,
next_tasks=["assess_risks"]
)
liquidity_task = Task(
name="optimize_liquidity",
description="Optimize liquidity",
expected_output="Liquidity optimization",
agent=liquidity_optimizer,
context=[market_task],
next_tasks=["assess_risks"]
)
risk_task = Task(
name="assess_risks",
description="Assess trading risks",
expected_output="Risk assessment",
agent=risk_assessor,
context=[arbitrage_task, liquidity_task],
next_tasks=["execute_trades"]
)
execution_task = Task(
name="execute_trades",
description="Execute trades",
expected_output="Trade execution results",
agent=trade_executor,
task_type="decision",
condition={
"success": ["analyze_market"], # Continue monitoring if successful
"failed": ["optimize_liquidity"] # Reoptimize if failed
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[market_analyzer, arbitrage_detector, liquidity_optimizer,
risk_assessor, trade_executor],
tasks=[market_task, arbitrage_task, liquidity_task,
risk_task, execution_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting DeFi Market Making Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nMarket Making Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+241
View File
@@ -0,0 +1,241 @@
---
title: "Emergency Response"
sidebarTitle: "Emergency Response"
description: "Learn how to create AI agents for coordinated emergency response and resource management."
icon: "truck-medical"
---
```mermaid
flowchart LR
In[In] --> Router[Emergency Router]
Router -->|critical/high| Dispatcher[Resource Dispatcher]
Router -->|medium/low| Dispatcher
Dispatcher --> Monitor[Response Monitor]
Monitor -->|ongoing| Coordinator[Response Coordinator]
Monitor -->|completed| Out[Out]
Coordinator --> Out
style In fill:#8B0000,color:#fff
style Router fill:#2E8B57,color:#fff
style Dispatcher fill:#2E8B57,color:#fff
style Monitor fill:#2E8B57,color:#fff
style Coordinator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how AI agents can coordinate emergency response, from initial assessment through resource dispatch and response monitoring.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
def assess_emergency(incident: Dict):
"""Simulates emergency assessment"""
severity_levels = ["low", "medium", "high", "critical"]
current_time = int(time.time())
severity = severity_levels[current_time % 4]
print(f"Incident assessed with {severity} severity")
return severity
def dispatch_resources(severity: str):
"""Simulates resource dispatch"""
resources = {
"low": ["local_police"],
"medium": ["local_police", "ambulance"],
"high": ["local_police", "ambulance", "fire"],
"critical": ["local_police", "ambulance", "fire", "special_units"]
}
dispatched = resources.get(severity, ["local_police"])
print(f"Dispatching resources: {dispatched}")
return dispatched
def monitor_response():
"""Simulates response monitoring"""
current_time = int(time.time())
status = "completed" if current_time % 3 == 0 else "ongoing"
return status
# Create specialized agents
router = Agent(
name="Emergency Router",
role="Emergency Assessment",
goal="Evaluate emergency severity and type",
instructions="Assess incident and determine required response",
tools=[assess_emergency]
)
dispatcher = Agent(
name="Resource Dispatcher",
role="Resource Management",
goal="Coordinate and dispatch appropriate resources",
instructions="Deploy resources based on emergency assessment",
tools=[dispatch_resources]
)
monitor = Agent(
name="Response Monitor",
role="Response Tracking",
goal="Track response progress and effectiveness",
instructions="Monitor ongoing response and provide status updates",
tools=[monitor_response]
)
synthesizer = Agent(
name="Response Coordinator",
role="Response Synthesis",
goal="Coordinate multi-agency response",
instructions="Synthesize information and coordinate overall response"
)
# Create workflow tasks
assessment_task = Task(
name="assess_emergency",
description="Evaluate emergency severity and type",
expected_output="Emergency severity level",
agent=router,
is_start=True,
task_type="decision",
condition={
"critical": ["dispatch_resources", "monitor_response"],
"high": ["dispatch_resources", "monitor_response"],
"medium": ["dispatch_resources"],
"low": ["dispatch_resources"]
}
)
dispatch_task = Task(
name="dispatch_resources",
description="Deploy appropriate emergency resources",
expected_output="List of dispatched resources",
agent=dispatcher,
next_tasks=["monitor_response"]
)
monitor_task = Task(
name="monitor_response",
description="Track response progress",
expected_output="Response status",
agent=monitor,
task_type="decision",
condition={
"ongoing": ["coordinate_response"],
"completed": ""
}
)
coordinate_task = Task(
name="coordinate_response",
description="Coordinate overall emergency response",
expected_output="Coordinated response plan",
agent=synthesizer,
context=[assessment_task, dispatch_task, monitor_task]
)
# Create workflow
workflow = PraisonAIAgents(
agents=[router, dispatcher, monitor, synthesizer],
tasks=[assessment_task, dispatch_task, monitor_task, coordinate_task],
process="workflow",
verbose=True
)
def main():
# Simulate emergency incident
incident = {
"type": "fire",
"location": "123 Main St",
"reported_time": time.time()
}
print("\nStarting Emergency Response Workflow...")
print("=" * 50)
# Run workflow
results = workflow.start(initial_input=incident)
# Print results
print("\nEmergency Response Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
main()
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
- Basic understanding of Python
</Note>
## Understanding Emergency Response
<Card title="What is Emergency Response?" icon="question">
Emergency response workflow enables:
- Dynamic severity assessment
- Automated resource dispatch
- Real-time response monitoring
- Multi-agency coordination
</Card>
## Features
<CardGroup cols={2}>
<Card title="Severity Assessment" icon="gauge-high">
Automatically evaluate incident severity and type.
</Card>
<Card title="Resource Management" icon="truck">
Dispatch appropriate resources based on severity.
</Card>
<Card title="Response Monitoring" icon="eye">
Track response progress and effectiveness.
</Card>
<Card title="Response Coordination" icon="people-group">
Coordinate multi-agency response efforts.
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
Learn about sequential prompt execution
</Card>
<Card title="Evaluator Optimizer" icon="magnifying-glass-chart" href="/features/evaluator-optimiser">
Explore optimization techniques
</Card>
</CardGroup>
+189
View File
@@ -0,0 +1,189 @@
---
title: "Examples"
sidebarTitle: "Examples"
description: "Explore real-world examples and use cases built with PraisonAI Agents."
icon: "code"
---
## Use Cases
<CardGroup cols={2}>
<Card
title="Predictive Maintenance"
icon="wrench"
href="/examples/predictive-maintenance"
>
Learn how to create AI agents for predictive maintenance and equipment monitoring.
</Card>
<Card
title="Emergency Response"
icon="truck-medical"
href="/examples/emergency-response"
>
Learn how to create AI agents for coordinated emergency response and resource management.
</Card>
<Card
title="Code Review"
icon="code"
href="/examples/code-review"
>
Learn how to create AI agents for automated code review and issue resolution.
</Card>
<Card
title="Adaptive Learning"
icon="graduation-cap"
href="/examples/adaptive-learning"
>
Learn how to create AI agents for personalized adaptive learning experiences.
</Card>
<Card
title="Supply Chain"
icon="truck"
href="/examples/supply-chain"
>
Learn how to create AI agents for supply chain risk management and mitigation.
</Card>
<Card
title="Customer Service"
icon="headset"
href="/examples/customer-service"
>
Learn how to create AI agents for automated customer service and support.
</Card>
<Card
title="Fraud Detection"
icon="shield-check"
href="/examples/fraud-detection"
>
Learn how to create AI agents for real-time fraud detection and alert management.
</Card>
<Card
title="Healthcare Diagnosis"
icon="stethoscope"
href="/examples/healthcare-diagnosis"
>
Learn how to create AI agents for medical diagnosis and treatment recommendations.
</Card>
<Card
title="Smart City"
icon="city"
href="/examples/smart-city"
>
Learn how to create AI agents for smart city resource optimization and management.
</Card>
<Card
title="Multilingual Content"
icon="language"
href="/examples/multilingual-content"
>
Learn how to create AI agents for multilingual content generation and cultural adaptation.
</Card>
<Card
title="Climate Impact"
icon="cloud-sun"
href="/examples/climate-impact"
>
Learn how to create AI agents for climate impact analysis and adaptation strategies.
</Card>
<Card
title="Space Mission"
icon="rocket"
href="/examples/space-mission"
>
Learn how to create AI agents for space mission planning and resource optimization.
</Card>
<Card
title="Neural Architecture"
icon="network-wired"
href="/examples/neural-architecture"
>
Learn how to create AI agents for neural architecture search and optimization.
</Card>
<Card
title="DeFi Market Maker"
icon="money-bill-trend-up"
href="/examples/defi-market-maker"
>
Learn how to create AI agents for decentralized finance market making and liquidity provision.
</Card>
<Card
title="Quantum Optimiser"
icon="atom"
href="/examples/quantum-optimiser"
>
Learn how to create AI agents for quantum computing optimization and algorithm design.
</Card>
<Card
title="Medicine Protocol"
icon="prescription-bottle-medical"
href="/examples/medicine-protocol"
>
Learn how to create AI agents for medical protocol optimization and drug discovery.
</Card>
<Card
title="Crypto Validator"
icon="key"
href="/examples/crypto-validator"
>
Learn how to create AI agents for cryptocurrency validation and blockchain security.
</Card>
<Card
title="Research Assistant"
icon="microscope"
href="/examples/research-assistant"
>
Learn how to create AI agents for research analysis and experiment design.
</Card>
<Card
title="Vulnerability Detection"
icon="shield-check"
href="/examples/vulnerability-detection"
>
Learn how to create AI agents for vulnerability detection and analysis.
</Card>
<Card
title="Healthcare Diagnosis"
icon="stethoscope"
href="/examples/healthcare-diagnosis"
>
Learn how to create AI agents for medical diagnosis and treatment recommendations.
</Card>
</CardGroup>
## What's Next?
<CardGroup cols={2}>
<Card
title="Features"
icon="stars"
href="/features/promptchaining"
>
Explore advanced features like prompt chaining and parallel execution
</Card>
<Card
title="API Reference"
icon="code"
href="/api-reference"
>
View the complete API reference documentation
</Card>
</CardGroup>
+237
View File
@@ -0,0 +1,237 @@
---
title: "Fraud Detection"
sidebarTitle: "Fraud Detection"
description: "Learn how to create AI agents for real-time fraud detection and alert management."
icon: "shield-check"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Transaction Analyzer]
Analyzer -->|high risk| Verifier[Identity Verifier]
Analyzer -->|all risks| Checker[Pattern Checker]
Checker --> Generator[Alert Generator]
Verifier --> Generator
Generator --> Out[Out]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Verifier fill:#2E8B57,color:#fff
style Checker fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how AI agents can detect fraud in real-time, from transaction analysis through alert generation.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_transaction():
"""Simulates transaction analysis"""
transactions = [
{"type": "credit_card", "amount": 5000, "location": "foreign", "risk": "high"},
{"type": "wire", "amount": 2000, "location": "domestic", "risk": "medium"},
{"type": "online", "amount": 500, "location": "domestic", "risk": "low"}
]
return transactions[int(time.time()) % 3]
def check_patterns(transaction: Dict):
"""Simulates pattern checking"""
patterns = {
"high": ["unusual_location", "large_amount"],
"medium": ["frequency_anomaly"],
"low": ["within_normal_limits"]
}
return patterns.get(transaction["risk"], ["unknown"])
def verify_identity():
"""Simulates identity verification"""
results = ["verified", "suspicious", "failed"]
return results[int(time.time()) % 3]
def generate_alert(verification: str, patterns: List[str]):
"""Simulates alert generation"""
if verification == "failed" or "unusual_location" in patterns:
return "high_priority_alert"
elif verification == "suspicious":
return "medium_priority_alert"
return "low_priority_alert"
# Create specialized agents
transaction_analyzer = Agent(
name="Transaction Analyzer",
role="Transaction Analysis",
goal="Analyze transactions for suspicious patterns",
instructions="Monitor and analyze financial transactions",
tools=[analyze_transaction]
)
pattern_checker = Agent(
name="Pattern Checker",
role="Pattern Detection",
goal="Identify suspicious patterns",
instructions="Check for known fraud patterns",
tools=[check_patterns]
)
identity_verifier = Agent(
name="Identity Verifier",
role="Identity Verification",
goal="Verify transaction identities",
instructions="Perform identity verification checks",
tools=[verify_identity]
)
alert_generator = Agent(
name="Alert Generator",
role="Alert Management",
goal="Generate appropriate alerts",
instructions="Create and prioritize alerts",
tools=[generate_alert]
)
# Create workflow tasks
analysis_task = Task(
name="analyze_transaction",
description="Analyze transaction details",
expected_output="Transaction analysis",
agent=transaction_analyzer,
is_start=True,
task_type="decision",
condition={
"high": ["check_patterns", "verify_identity"],
"medium": ["check_patterns"],
"low": ["check_patterns"]
}
)
pattern_task = Task(
name="check_patterns",
description="Check for suspicious patterns",
expected_output="Identified patterns",
agent=pattern_checker,
next_tasks=["generate_alert"],
async_execution=True
)
verification_task = Task(
name="verify_identity",
description="Verify transaction identity",
expected_output="Verification result",
agent=identity_verifier,
next_tasks=["generate_alert"],
async_execution=True
)
alert_task = Task(
name="generate_alert",
description="Generate fraud alert",
expected_output="Alert priority",
agent=alert_generator,
context=[pattern_task, verification_task]
)
# Create workflow
workflow = PraisonAIAgents(
agents=[transaction_analyzer, pattern_checker, identity_verifier, alert_generator],
tasks=[analysis_task, pattern_task, verification_task, alert_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Fraud Detection Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nFraud Detection Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
- Basic understanding of Python
</Note>
## Understanding Fraud Detection
<Card title="What is Fraud Detection?" icon="question">
Automated fraud detection workflow enables:
- Real-time transaction monitoring
- Pattern-based detection
- Identity verification
- Prioritized alert generation
</Card>
## Features
<CardGroup cols={2}>
<Card title="Transaction Analysis" icon="magnifying-glass">
Analyze transactions for risk levels and suspicious patterns.
</Card>
<Card title="Pattern Detection" icon="chart-line">
Identify known fraud patterns and anomalies.
</Card>
<Card title="Identity Verification" icon="user-check">
Verify transaction identities for high-risk cases.
</Card>
<Card title="Alert Management" icon="bell">
Generate and prioritize fraud alerts.
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
Learn about sequential prompt execution
</Card>
<Card title="Evaluator Optimizer" icon="magnifying-glass-chart" href="/features/evaluator-optimiser">
Explore optimization techniques
</Card>
</CardGroup>
+265
View File
@@ -0,0 +1,265 @@
---
title: "Hackathon Judge Agent"
description: "Learn how to create AI agents for evaluating hackathon projects through video demonstrations."
icon: "trophy"
---
```mermaid
flowchart LR
In[In] --> Judge[Hackathon Judge]
Judge --> Scores[Project Scores]
Scores --> Analysis[Detailed Analysis]
Analysis --> Feedback[Feedback]
Feedback --> Recommendations[Recommendations]
Recommendations --> Out[Out]
style In fill:#8B0000,color:#fff
style Judge fill:#2E8B57,color:#fff
style Scores fill:#2E8B57,color:#fff
style Analysis fill:#2E8B57,color:#fff
style Feedback fill:#2E8B57,color:#fff
style Recommendations fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Hackathon Project Evaluation?
Hackathon Project Evaluation is an automated process for assessing hackathon projects through video demonstrations. It provides comprehensive scoring across multiple dimensions including innovation, technical complexity, and presentation quality, helping organizers make informed decisions and providing valuable feedback to participants.
## Features
<CardGroup cols={2}>
<Card title="Project Scoring" icon="star">
Comprehensive scoring system across multiple dimensions (0-100).
</Card>
<Card title="Technical Analysis" icon="microchip">
Evaluation of technical complexity and implementation quality.
</Card>
<Card title="Innovation Assessment" icon="lightbulb">
Analysis of creativity and unique project features.
</Card>
<Card title="Market Analysis" icon="chart-line">
Assessment of market potential and scalability.
</Card>
<Card title="Detailed Feedback" icon="comments">
Constructive feedback and specific recommendations for improvement.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents opencv-python moviepy
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `hackathon_judge.py` with the following code:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from pydantic import BaseModel
from typing import List, Dict
import os
import json
class ProjectEvaluation(BaseModel):
innovation_score: int # 0-100
technical_complexity: int # 0-100
presentation_quality: int # 0-100
user_experience: int # 0-100
completeness: int # 0-100
overall_score: int # 0-100
key_strengths: List[str]
areas_for_improvement: List[str]
notable_features: List[str]
technical_highlights: List[str]
recommendations: List[str]
market_potential: str
scalability_assessment: str
# Create Vision Analysis Agent
hackathon_judge = Agent(
name="HackathonJudge",
role="Technical Project Evaluator",
goal="Evaluate hackathon projects through video demonstrations",
backstory="""You are an experienced hackathon judge and technical expert.
You excel at evaluating innovation, technical implementation, and presentation quality.
You provide constructive feedback and identify both strengths and areas for improvement.""",
llm="gpt-4o-mini", # Using vision-capable model
self_reflect=False,
knowledge=""
)
def evaluate_project(video_path: str) -> ProjectEvaluation:
"""
Evaluate a hackathon project based on its video demonstration
"""
evaluation_task = Task(
name="project_evaluation",
description="""Analyze this hackathon project video demonstration and provide a comprehensive evaluation:
1. Score the following aspects (0-100):
- Innovation and Creativity
- Technical Complexity
- Presentation Quality
- User Experience
- Project Completeness
2. Identify:
- Key strengths and standout features
- Areas that could be improved
- Notable technical implementations
- Market potential and scalability
3. Provide:
- Specific recommendations for improvement
- Technical suggestions
- Potential future enhancements""",
expected_output="Detailed project evaluation with scores and feedback",
agent=hackathon_judge,
output_pydantic=ProjectEvaluation,
images=[video_path] # Video input for multimodal analysis
)
# Initialize and run evaluation
agents = PraisonAIAgents(
agents=[hackathon_judge],
tasks=[evaluation_task],
process="sequential",
verbose=True
)
response = agents.start()
try:
# If response contains task_results, extract the Pydantic model directly
if isinstance(response, dict) and 'task_results' in response:
task_output = response['task_results'][0]
if hasattr(task_output, 'pydantic'):
return task_output.pydantic
elif hasattr(task_output, 'raw'):
# Extract JSON from raw string if it's wrapped in ```json
raw_text = task_output.raw
if raw_text.startswith('```json'):
raw_text = raw_text.split('\n', 1)[1].rsplit('\n', 1)[0]
evaluation_data = json.loads(raw_text)
else:
evaluation_data = json.loads(task_output) if isinstance(task_output, str) else task_output
# If response is a string, try to parse it as JSON
elif isinstance(response, str):
evaluation_data = json.loads(response)
# If response is a dict with task_status
elif isinstance(response, dict) and 'task_status' in response:
content = response['task_status']
if isinstance(content, dict):
evaluation_data = content
else:
evaluation_data = json.loads(content) if isinstance(content, str) else content
else:
evaluation_data = response
print(f"Debug - Parsed evaluation_data: {evaluation_data}")
# Create and return ProjectEvaluation instance
return ProjectEvaluation(
innovation_score=int(evaluation_data.get('innovation_score', 0)),
technical_complexity=int(evaluation_data.get('technical_complexity', 0)),
presentation_quality=int(evaluation_data.get('presentation_quality', 0)),
user_experience=int(evaluation_data.get('user_experience', 0)),
completeness=int(evaluation_data.get('completeness', 0)),
overall_score=int(evaluation_data.get('overall_score', 0)),
key_strengths=evaluation_data.get('key_strengths', []),
areas_for_improvement=evaluation_data.get('areas_for_improvement', []),
notable_features=evaluation_data.get('notable_features', []),
technical_highlights=evaluation_data.get('technical_highlights', []),
recommendations=evaluation_data.get('recommendations', []),
market_potential=str(evaluation_data.get('market_potential', '')),
scalability_assessment=str(evaluation_data.get('scalability_assessment', ''))
)
except Exception as e:
print(f"Debug - Raw response: {response}")
print(f"Error processing response: {e}")
raise
if __name__ == "__main__":
# Example usage
current_dir = os.path.dirname(os.path.abspath(__file__))
video_path = os.path.join(current_dir, "presentation.mp4")
result = evaluate_project(video_path) # Now returns ProjectEvaluation directly
print("\nHackathon Project Evaluation")
print("===========================")
print(f"\nOverall Score: {result.overall_score}/100")
print("\nDetailed Scores:")
print(f"Innovation: {result.innovation_score}/100")
print(f"Technical Complexity: {result.technical_complexity}/100")
print(f"Presentation: {result.presentation_quality}/100")
print(f"User Experience: {result.user_experience}/100")
print(f"Completeness: {result.completeness}/100")
print("\nKey Strengths:")
for strength in result.key_strengths:
print(f"- {strength}")
print("\nAreas for Improvement:")
for area in result.areas_for_improvement:
print(f"- {area}")
print("\nTechnical Highlights:")
for highlight in result.technical_highlights:
print(f"- {highlight}")
print("\nRecommendations:")
for rec in result.recommendations:
print(f"- {rec}")
print(f"\nMarket Potential: {result.market_potential}")
print(f"\nScalability Assessment: {result.scalability_assessment}")
```
</Step>
</Steps>
## Understanding the Output
The hackathon project evaluation generates a comprehensive report with the following components:
- Scoring Metrics (0-100)
- Innovation Score
- Technical Complexity
- Presentation Quality
- User Experience
- Project Completeness
- Overall Score
- Qualitative Analysis
- Key Strengths
- Areas for Improvement
- Notable Features
- Technical Highlights
- Strategic Assessment
- Recommendations
- Market Potential
- Scalability Assessment
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
<Card title="API Reference" icon="code" href="/api-reference">
Explore the complete API documentation
</Card>
</CardGroup>
+278
View File
@@ -0,0 +1,278 @@
---
title: "Healthcare Diagnosis"
description: "Learn how to create AI agents for automated medical diagnosis and treatment recommendations."
icon: "stethoscope"
---
```mermaid
flowchart LR
In[In] --> Symptoms[Symptom Analyzer]
Symptoms --> Labs[Lab Processor]
Symptoms --> History[History Analyzer]
Labs --> Diagnosis[Diagnosis Generator]
History --> Diagnosis
Diagnosis --> Treatment[Treatment Recommender]
Treatment --> Out[Out]
style In fill:#8B0000,color:#fff
style Symptoms fill:#2E8B57,color:#fff
style Labs fill:#2E8B57,color:#fff
style History fill:#2E8B57,color:#fff
style Diagnosis fill:#2E8B57,color:#fff
style Treatment fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
Learn how to implement an automated healthcare diagnosis system using AI agents for symptom analysis, lab processing, and treatment recommendations.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
def analyze_symptoms():
"""Simulates symptom analysis"""
cases = [
{"symptoms": ["fever", "cough", "fatigue"], "severity": "high", "duration": "5_days"},
{"symptoms": ["headache", "nausea"], "severity": "medium", "duration": "2_days"},
{"symptoms": ["rash", "itching"], "severity": "low", "duration": "1_week"}
]
return cases[int(time.time()) % 3]
def process_lab_results():
"""Simulates lab result processing"""
results = [
{"blood_count": "abnormal", "inflammation": "high", "markers": "elevated"},
{"blood_count": "normal", "inflammation": "low", "markers": "normal"},
{"blood_count": "normal", "inflammation": "medium", "markers": "elevated"}
]
return results[int(time.time()) % 3]
def analyze_medical_history():
"""Simulates medical history analysis"""
histories = [
{"chronic_conditions": True, "allergies": True, "risk_factors": "high"},
{"chronic_conditions": False, "allergies": True, "risk_factors": "medium"},
{"chronic_conditions": False, "allergies": False, "risk_factors": "low"}
]
return histories[int(time.time()) % 3]
def generate_diagnosis(symptoms: Dict, lab_results: Dict, history: Dict):
"""Simulates diagnosis generation"""
if symptoms["severity"] == "high" and lab_results["markers"] == "elevated":
return {"diagnosis": "serious_condition", "confidence": "high"}
elif symptoms["severity"] == "medium" or lab_results["inflammation"] == "medium":
return {"diagnosis": "moderate_condition", "confidence": "medium"}
return {"diagnosis": "mild_condition", "confidence": "high"}
def recommend_treatment(diagnosis: Dict):
"""Simulates treatment recommendation"""
treatments = {
"serious_condition": ["immediate_intervention", "specialist_referral"],
"moderate_condition": ["medication", "follow_up"],
"mild_condition": ["rest", "observation"]
}
return treatments.get(diagnosis["diagnosis"], ["general_care"])
# Create specialized agents
symptom_analyzer = Agent(
name="Symptom Analyzer",
role="Symptom Analysis",
goal="Analyze patient symptoms",
instructions="Evaluate reported symptoms and their severity",
tools=[analyze_symptoms]
)
lab_processor = Agent(
name="Lab Processor",
role="Lab Analysis",
goal="Process laboratory results",
instructions="Analyze and interpret lab test results",
tools=[process_lab_results]
)
history_analyzer = Agent(
name="History Analyzer",
role="Medical History Analysis",
goal="Analyze patient medical history",
instructions="Review and assess patient medical history",
tools=[analyze_medical_history]
)
diagnosis_generator = Agent(
name="Diagnosis Generator",
role="Diagnosis Generation",
goal="Generate comprehensive diagnosis",
instructions="Combine all inputs to generate diagnosis",
tools=[generate_diagnosis]
)
treatment_recommender = Agent(
name="Treatment Recommender",
role="Treatment Planning",
goal="Recommend appropriate treatment",
instructions="Suggest treatment based on diagnosis",
tools=[recommend_treatment]
)
# Create workflow tasks
symptom_task = Task(
name="analyze_symptoms",
description="Analyze patient symptoms",
expected_output="Symptom analysis",
agent=symptom_analyzer,
is_start=True,
task_type="decision",
condition={
"high": ["process_labs", "analyze_history"],
"medium": ["process_labs", "analyze_history"],
"low": ["process_labs"]
}
)
lab_task = Task(
name="process_labs",
description="Process lab results",
expected_output="Lab analysis",
agent=lab_processor,
next_tasks=["generate_diagnosis"]
)
history_task = Task(
name="analyze_history",
description="Analyze medical history",
expected_output="History analysis",
agent=history_analyzer,
next_tasks=["generate_diagnosis"]
)
diagnosis_task = Task(
name="generate_diagnosis",
description="Generate diagnosis",
expected_output="Diagnosis and confidence level",
agent=diagnosis_generator,
next_tasks=["recommend_treatment"],
context=[symptom_task, lab_task, history_task]
)
treatment_task = Task(
name="recommend_treatment",
description="Recommend treatment",
expected_output="Treatment recommendations",
agent=treatment_recommender,
context=[diagnosis_task]
)
# Create workflow
workflow = PraisonAIAgents(
agents=[symptom_analyzer, lab_processor, history_analyzer,
diagnosis_generator, treatment_recommender],
tasks=[symptom_task, lab_task, history_task, diagnosis_task, treatment_task],
process="workflow",
verbose=True
)
def main():
print("\nStarting Healthcare Diagnosis Workflow...")
print("=" * 50)
# Run workflow
results = workflow.start()
# Print results
print("\nDiagnosis Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
main()
```
</Step>
<Step title="Start Agents">
Run your healthcare diagnosis system:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
</Note>
## Understanding Healthcare Diagnosis
<Card title="What is Healthcare Diagnosis?" icon="question">
Healthcare diagnosis enables:
- Automated symptom analysis
- Lab result processing
- Medical history review
- Diagnosis generation
- Treatment recommendations
</Card>
## Features
<CardGroup cols={2}>
<Card title="Symptom Analysis" icon="stethoscope">
Analyze patient symptoms:
- Severity assessment
- Duration tracking
- Pattern recognition
</Card>
<Card title="Lab Processing" icon="flask">
Process medical tests:
- Blood count analysis
- Inflammation markers
- Test result interpretation
</Card>
<Card title="History Analysis" icon="book-medical">
Review medical history:
- Chronic conditions
- Allergies
- Risk factors
</Card>
<Card title="Treatment Planning" icon="prescription">
Generate treatment plans:
- Immediate interventions
- Medication recommendations
- Follow-up scheduling
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
Learn about chaining prompts for complex workflows
</Card>
<Card title="Evaluator Optimizer" icon="gauge" href="/features/evaluator-optimiser">
Explore how to optimize and evaluate solutions
</Card>
</CardGroup>
+300
View File
@@ -0,0 +1,300 @@
---
title: "Medicine Protocol"
description: "Learn how to create AI agents for personalized medicine protocol generation and analysis."
icon: "stethoscope"
---
```mermaid
flowchart LR
In[In] --> Genetic[Genetic Analyzer]
In --> History[Patient History]
Genetic --> Interaction[Drug Interaction]
History --> Interaction
Interaction --> Protocol[Protocol Generator]
Protocol --> Simulation[Effectiveness Simulator]
Simulation --> Out[Out]
style In fill:#8B0000,color:#fff
style Genetic fill:#2E8B57,color:#fff
style History fill:#2E8B57,color:#fff
style Interaction fill:#2E8B57,color:#fff
style Protocol fill:#2E8B57,color:#fff
style Simulation fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Personalized Medicine?
Personalized medicine is an approach that tailors medical treatment to individual characteristics of each patient. It involves analyzing genetic markers, patient history, and drug interactions to create optimized treatment protocols.
## Features
<CardGroup cols={2}>
<Card title="Genetic Analysis" icon="dna">
Deep analysis of genetic markers including metabolism genes, risk factors, and drug response markers.
</Card>
<Card title="Patient History" icon="notes-medical">
Comprehensive evaluation of medical conditions, medications, allergies, and family history.
</Card>
<Card title="Drug Interaction" icon="pills">
Analysis of potential drug interactions based on genetic data and patient history.
</Card>
<Card title="Protocol Generation" icon="file-medical">
Creation of personalized treatment protocols with dosage adjustments and monitoring plans.
</Card>
<Card title="Treatment Simulation" icon="chart-line">
Prediction of treatment effectiveness, side effects, and adherence probability.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_genetic_markers():
"""Simulates genetic marker analysis"""
markers = {
"metabolism_genes": {
"CYP2D6": "rapid_metabolizer",
"CYP2C19": "normal_metabolizer",
"DPYD": "poor_metabolizer"
},
"risk_factors": {
"cardiovascular": "elevated",
"diabetes": "low",
"autoimmune": "moderate"
},
"drug_response_markers": {
"TPMT": "high_sensitivity",
"HLA-B*5701": "negative",
"UGT1A1": "normal"
}
}
return markers
def evaluate_patient_history():
"""Simulates patient history evaluation"""
history = {
"conditions": [
{"name": "hypertension", "duration": "5_years", "severity": "moderate"},
{"name": "arthritis", "duration": "2_years", "severity": "mild"}
],
"medications": [
{"name": "lisinopril", "response": "good", "side_effects": "minimal"},
{"name": "methotrexate", "response": "moderate", "side_effects": "mild"}
],
"allergies": ["penicillin", "sulfa"],
"family_history": ["diabetes", "heart_disease"]
}
return history
def analyze_drug_interactions(genetic_data: Dict, patient_history: Dict):
"""Analyzes potential drug interactions"""
interactions = []
medications = [med["name"] for med in patient_history["medications"]]
for med in medications:
interactions.append({
"medication": med,
"genetic_impact": "significant" if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer" else "normal",
"risk_level": "high" if med in patient_history["allergies"] else "low",
"monitoring_needed": True if genetic_data["metabolism_genes"]["DPYD"] == "poor_metabolizer" else False
})
return interactions
def generate_protocol(genetic_data: Dict, interactions: List[Dict]):
"""Generates treatment protocol"""
protocol = {
"primary_treatment": {
"medication": "custom_formulation_A",
"dosage": "adjusted_based_on_metabolism",
"frequency": "twice_daily",
"monitoring": {
"type": "blood_levels",
"frequency": "weekly"
}
},
"alternatives": [
{
"medication": "custom_formulation_B",
"conditions": ["genetic_compatibility", "no_interactions"]
}
],
"precautions": []
}
if genetic_data["metabolism_genes"]["CYP2D6"] == "rapid_metabolizer":
protocol["precautions"].append("increase_monitoring_frequency")
if any(i["risk_level"] == "high" for i in interactions):
protocol["precautions"].append("alternative_medication_needed")
return protocol
def simulate_effectiveness(protocol: Dict):
"""Simulates treatment effectiveness"""
simulation = {
"efficacy_prediction": 0.85 + (time.time() % 2) / 10,
"side_effect_risk": 0.15 + (time.time() % 1) / 10,
"adherence_probability": 0.9 + (time.time() % 1) / 10,
"expected_outcomes": [
"symptom_reduction_80_percent",
"minimal_side_effects",
"good_tolerance"
]
}
return simulation
# Create specialized agents
genetic_analyzer = Agent(
name="Genetic Analyzer",
role="Genetic Analysis",
goal="Analyze genetic markers",
instructions="Evaluate genetic markers and variants",
tools=[analyze_genetic_markers]
)
history_analyzer = Agent(
name="History Analyzer",
role="History Analysis",
goal="Analyze patient history",
instructions="Evaluate medical history and conditions",
tools=[evaluate_patient_history]
)
interaction_analyzer = Agent(
name="Interaction Analyzer",
role="Drug Interaction",
goal="Analyze drug interactions",
instructions="Evaluate potential drug interactions",
tools=[analyze_drug_interactions]
)
protocol_generator = Agent(
name="Protocol Generator",
role="Protocol Generation",
goal="Generate treatment protocol",
instructions="Create personalized treatment protocol",
tools=[generate_protocol]
)
effectiveness_simulator = Agent(
name="Effectiveness Simulator",
role="Treatment Simulation",
goal="Simulate treatment effectiveness",
instructions="Predict treatment outcomes",
tools=[simulate_effectiveness]
)
# Create workflow tasks
genetic_task = Task(
name="analyze_genetics",
description="Analyze genetic markers",
expected_output="Genetic analysis",
agent=genetic_analyzer,
is_start=True,
next_tasks=["analyze_history"]
)
history_task = Task(
name="analyze_history",
description="Analyze patient history",
expected_output="History analysis",
agent=history_analyzer,
next_tasks=["analyze_interactions"]
)
interaction_task = Task(
name="analyze_interactions",
description="Analyze drug interactions",
expected_output="Interaction analysis",
agent=interaction_analyzer,
context=[genetic_task, history_task],
next_tasks=["generate_protocol"]
)
protocol_task = Task(
name="generate_protocol",
description="Generate treatment protocol",
expected_output="Treatment protocol",
agent=protocol_generator,
context=[genetic_task, interaction_task],
next_tasks=["simulate_effectiveness"]
)
simulation_task = Task(
name="simulate_effectiveness",
description="Simulate treatment effectiveness",
expected_output="Effectiveness simulation",
agent=effectiveness_simulator,
task_type="decision",
condition={
"high": "", # End workflow if high effectiveness
"medium": ["generate_protocol"], # Adjust protocol if medium
"low": ["analyze_interactions"] # Reanalyze if low
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[genetic_analyzer, history_analyzer, interaction_analyzer,
protocol_generator, effectiveness_simulator],
tasks=[genetic_task, history_task, interaction_task,
protocol_task, simulation_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Personalized Medicine Protocol Generation...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nProtocol Generation Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+276
View File
@@ -0,0 +1,276 @@
---
title: "Multilingual Content"
description: "Learn how to create AI agents for multilingual content generation and cultural adaptation."
icon: "language"
---
```mermaid
flowchart LR
In[In] --> Generator[Content Generator]
Generator --> Translator[Content Translator]
Translator --> Cultural[Cultural Checker]
Cultural --> Adapter[Content Adapter]
Adapter --> Quality[Quality Assessor]
Quality --> Out[Out]
Quality --> Adapter
Quality --> Translator
style In fill:#8B0000,color:#fff
style Generator fill:#2E8B57,color:#fff
style Translator fill:#2E8B57,color:#fff
style Cultural fill:#2E8B57,color:#fff
style Adapter fill:#2E8B57,color:#fff
style Quality fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
Learn how to implement a multilingual content generation system using AI agents for content creation, translation, cultural adaptation, and quality assurance.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
def generate_base_content():
"""Simulates base content generation"""
content_types = [
{"type": "marketing", "tone": "professional", "length": "medium"},
{"type": "technical", "tone": "formal", "length": "long"},
{"type": "social", "tone": "casual", "length": "short"}
]
return content_types[int(time.time()) % 3]
def translate_content(content: Dict):
"""Simulates content translation"""
languages = ["spanish", "french", "german", "japanese", "chinese"]
translations = {lang: f"Translated content in {lang}" for lang in languages}
return translations
def check_cultural_context(translations: Dict):
"""Simulates cultural context verification"""
cultural_issues = {
"spanish": [],
"french": ["idiom_mismatch"],
"german": [],
"japanese": ["formality_level"],
"chinese": ["cultural_reference"]
}
return cultural_issues
def adapt_content(issues: Dict):
"""Simulates content adaptation"""
adaptations = {
"idiom_mismatch": "localized_expression",
"formality_level": "adjusted_tone",
"cultural_reference": "localized_reference"
}
return {lang: [adaptations[issue] for issue in issues]
for lang, issues in issues.items() if issues}
def quality_check():
"""Simulates quality assessment"""
quality_levels = ["high", "medium", "needs_revision"]
return quality_levels[int(time.time()) % 3]
# Create specialized agents
content_generator = Agent(
name="Content Generator",
role="Base Content Creation",
goal="Generate high-quality base content",
instructions="Create engaging base content",
tools=[generate_base_content]
)
translator = Agent(
name="Content Translator",
role="Translation",
goal="Translate content accurately",
instructions="Translate content while maintaining meaning",
tools=[translate_content]
)
cultural_checker = Agent(
name="Cultural Checker",
role="Cultural Verification",
goal="Verify cultural appropriateness",
instructions="Check for cultural sensitivities",
tools=[check_cultural_context]
)
content_adapter = Agent(
name="Content Adapter",
role="Content Adaptation",
goal="Adapt content for cultural fit",
instructions="Modify content based on cultural context",
tools=[adapt_content]
)
quality_assessor = Agent(
name="Quality Assessor",
role="Quality Assessment",
goal="Ensure content quality",
instructions="Assess overall content quality",
tools=[quality_check]
)
# Create workflow tasks
generation_task = Task(
name="generate_content",
description="Generate base content",
expected_output="Base content for translation",
agent=content_generator,
is_start=True,
next_tasks=["translate_content"]
)
translation_task = Task(
name="translate_content",
description="Translate content to target languages",
expected_output="Translated content",
agent=translator,
next_tasks=["check_cultural"]
)
cultural_task = Task(
name="check_cultural",
description="Check cultural appropriateness",
expected_output="Cultural context issues",
agent=cultural_checker,
next_tasks=["adapt_content"]
)
adaptation_task = Task(
name="adapt_content",
description="Adapt content for cultural fit",
expected_output="Culturally adapted content",
agent=content_adapter,
next_tasks=["assess_quality"]
)
quality_task = Task(
name="assess_quality",
description="Assess content quality",
expected_output="Quality assessment",
agent=quality_assessor,
task_type="decision",
condition={
"high": "", # Complete workflow
"medium": ["adapt_content"], # Minor revisions needed
"needs_revision": ["translate_content"] # Major revisions needed
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[content_generator, translator, cultural_checker,
content_adapter, quality_assessor],
tasks=[generation_task, translation_task, cultural_task,
adaptation_task, quality_task],
process="workflow",
verbose=True
)
def main():
print("\nStarting Multilingual Content Generation Workflow...")
print("=" * 50)
# Run workflow
results = workflow.start()
# Print results
print("\nContent Generation Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
main()
```
</Step>
<Step title="Start Agents">
Run your multilingual content generation system:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
</Note>
## Understanding Multilingual Content Generation
<Card title="What is Multilingual Content Generation?" icon="question">
Multilingual content generation enables:
- Base content creation
- Accurate translation
- Cultural context verification
- Content adaptation
- Quality assurance
</Card>
## Features
<CardGroup cols={2}>
<Card title="Content Generation" icon="pen">
Generate base content:
- Marketing content
- Technical documentation
- Social media posts
</Card>
<Card title="Translation" icon="language">
Translate content:
- Multiple languages
- Meaning preservation
- Context awareness
</Card>
<Card title="Cultural Adaptation" icon="globe">
Ensure cultural fit:
- Cultural sensitivity
- Idiom localization
- Reference adaptation
</Card>
<Card title="Quality Control" icon="check">
Quality assurance:
- Content assessment
- Revision workflow
- Continuous improvement
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
Learn about chaining prompts for complex workflows
</Card>
<Card title="Evaluator Optimizer" icon="gauge" href="/features/evaluator-optimiser">
Explore how to optimize and evaluate solutions
</Card>
</CardGroup>
+284
View File
@@ -0,0 +1,284 @@
---
title: "Neural Architecture"
description: "Learn how to create AI agents for neural architecture search and optimization."
icon: "brain"
---
```mermaid
flowchart LR
In[In] --> Hardware[Hardware Analyzer]
Hardware --> Generator[Architecture Generator]
Generator --> Hyperparams[Hyperparameter Optimizer]
Hyperparams --> Performance[Performance Estimator]
Performance --> Deployment[Deployment Optimizer]
Deployment --> Out[Out]
style In fill:#8B0000,color:#fff
style Hardware fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Hyperparams fill:#2E8B57,color:#fff
style Performance fill:#2E8B57,color:#fff
style Deployment fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Neural Architecture Search?
Neural Architecture Search (NAS) is an automated process for designing optimal neural network architectures. It involves analyzing hardware constraints, generating candidate architectures, optimizing hyperparameters, and configuring deployment settings to create efficient and performant models.
## Features
<CardGroup cols={2}>
<Card title="Hardware Analysis" icon="microchip">
Analysis of GPU memory, compute capability, bandwidth, and thermal constraints.
</Card>
<Card title="Architecture Generation" icon="diagram-project">
Creation of candidate architectures including transformers and CNNs with optimized structures.
</Card>
<Card title="Hyperparameter Tuning" icon="sliders">
Optimization of learning rates, batch sizes, optimizers, and regularization parameters.
</Card>
<Card title="Performance Estimation" icon="gauge-high">
Prediction of model accuracy, training time, memory requirements, and FLOPS.
</Card>
<Card title="Deployment Optimization" icon="rocket">
Configuration of quantization, pruning, and batching for efficient deployment.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_hardware_constraints():
"""Simulates hardware analysis"""
constraints = {
"gpu_memory": 16 * 1024, # MB
"compute_capability": "7.5",
"memory_bandwidth": 900, # GB/s
"tensor_cores": True,
"max_power_consumption": 300, # Watts
"thermal_limits": 85 # Celsius
}
return constraints
def generate_architecture_candidates():
"""Generates candidate architectures"""
candidates = [
{
"type": "transformer",
"layers": 12 + (int(time.time()) % 6),
"attention_heads": 8,
"embedding_dim": 512,
"estimated_params": 125_000_000
},
{
"type": "cnn",
"layers": 50 + (int(time.time()) % 50),
"filters": [64, 128, 256, 512],
"estimated_params": 25_000_000
}
]
return candidates[int(time.time()) % 2]
def optimize_hyperparameters(architecture: Dict):
"""Optimizes hyperparameters"""
optimization = {
"learning_rate": 0.001 + (time.time() % 9) / 10000,
"batch_size": 32 * (1 + int(time.time()) % 4),
"optimizer": "adam",
"weight_decay": 0.0001,
"dropout_rate": 0.1 + (time.time() % 3) / 10,
"activation": "gelu" if architecture["type"] == "transformer" else "relu"
}
return optimization
def estimate_performance(architecture: Dict, hyperparams: Dict):
"""Estimates model performance"""
performance = {
"estimated_accuracy": 0.85 + (time.time() % 10) / 100,
"estimated_training_time": {
"hours": 24 + (int(time.time()) % 24),
"gpu_hours": 96
},
"memory_requirements": {
"training": architecture["estimated_params"] * 4 / (1024 * 1024), # GB
"inference": architecture["estimated_params"] * 2 / (1024 * 1024) # GB
},
"flops_count": architecture["estimated_params"] * 2
}
return performance
def optimize_deployment(architecture: Dict, performance: Dict):
"""Optimizes deployment configuration"""
deployment = {
"quantization": {
"method": "dynamic",
"precision": "int8",
"estimated_speedup": 2.5
},
"pruning": {
"method": "magnitude",
"target_sparsity": 0.3,
"estimated_size_reduction": 0.6
},
"batching": {
"max_batch_size": 32,
"dynamic_batching": True
}
}
return deployment
# Create specialized agents
hardware_analyzer = Agent(
name="Hardware Analyzer",
role="Hardware Analysis",
goal="Analyze hardware constraints",
instructions="Evaluate available hardware resources",
tools=[analyze_hardware_constraints]
)
architecture_generator = Agent(
name="Architecture Generator",
role="Architecture Generation",
goal="Generate neural architectures",
instructions="Create candidate neural architectures",
tools=[generate_architecture_candidates]
)
hyperparameter_optimizer = Agent(
name="Hyperparameter Optimizer",
role="Hyperparameter Optimization",
goal="Optimize hyperparameters",
instructions="Find optimal hyperparameter settings",
tools=[optimize_hyperparameters]
)
performance_estimator = Agent(
name="Performance Estimator",
role="Performance Estimation",
goal="Estimate model performance",
instructions="Predict model performance metrics",
tools=[estimate_performance]
)
deployment_optimizer = Agent(
name="Deployment Optimizer",
role="Deployment Optimization",
goal="Optimize deployment settings",
instructions="Configure optimal deployment",
tools=[optimize_deployment]
)
# Create workflow tasks
hardware_task = Task(
name="analyze_hardware",
description="Analyze hardware constraints",
expected_output="Hardware analysis",
agent=hardware_analyzer,
is_start=True,
next_tasks=["generate_architecture"]
)
architecture_task = Task(
name="generate_architecture",
description="Generate architecture candidates",
expected_output="Architecture candidates",
agent=architecture_generator,
next_tasks=["optimize_hyperparameters"]
)
hyperparameter_task = Task(
name="optimize_hyperparameters",
description="Optimize hyperparameters",
expected_output="Hyperparameter settings",
agent=hyperparameter_optimizer,
context=[architecture_task],
next_tasks=["estimate_performance"]
)
performance_task = Task(
name="estimate_performance",
description="Estimate performance",
expected_output="Performance estimates",
agent=performance_estimator,
context=[architecture_task, hyperparameter_task],
next_tasks=["optimize_deployment"]
)
deployment_task = Task(
name="optimize_deployment",
description="Optimize deployment",
expected_output="Deployment configuration",
agent=deployment_optimizer,
context=[architecture_task, performance_task],
task_type="decision",
condition={
"success": ["generate_architecture"], # Try new architecture
"failure": ["optimize_hyperparameters"] # Reoptimize hyperparameters
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[hardware_analyzer, architecture_generator, hyperparameter_optimizer,
performance_estimator, deployment_optimizer],
tasks=[hardware_task, architecture_task, hyperparameter_task,
performance_task, deployment_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Neural Architecture Search Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nArchitecture Search Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+287
View File
@@ -0,0 +1,287 @@
---
title: "Predictive Maintenance"
description: "Learn how to create AI agents for predictive maintenance and equipment monitoring."
icon: "gear"
---
```mermaid
flowchart LR
In[In] --> Monitor[Sensor Monitor]
Monitor --> Analyzer[Performance Analyzer]
Analyzer --> Detector[Anomaly Detector]
Detector --> Predictor[Failure Predictor]
Predictor -->|critical| Scheduler[Maintenance Scheduler]
Predictor -->|warning| Scheduler
Predictor -->|normal| Out[Out]
Scheduler --> Out
style In fill:#8B0000,color:#fff
style Out fill:#8B0000,color:#fff
style Monitor fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Detector fill:#2E8B57,color:#fff
style Predictor fill:#2E8B57,color:#fff
style Scheduler fill:#2E8B57,color:#fff
```
Learn how to implement a predictive maintenance system using AI agents for real-time equipment monitoring and maintenance scheduling.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `predictive_maintenance.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def collect_sensor_data():
"""Simulates sensor data collection"""
sensor_readings = {
"temperature": 75 + (int(time.time()) % 20),
"vibration": 0.5 + (int(time.time()) % 10) / 10,
"pressure": 100 + (int(time.time()) % 50),
"noise_level": 60 + (int(time.time()) % 30)
}
return sensor_readings
def analyze_performance():
"""Simulates performance analysis"""
metrics = {
"efficiency": 0.8 + (int(time.time()) % 20) / 100,
"uptime": 0.95 + (int(time.time()) % 5) / 100,
"output_quality": 0.9 + (int(time.time()) % 10) / 100
}
return metrics
def detect_anomalies(sensor_data: Dict, performance: Dict):
"""Simulates anomaly detection"""
anomalies = []
if sensor_data["temperature"] > 90:
anomalies.append({"type": "temperature_high", "severity": "critical"})
if sensor_data["vibration"] > 1.2:
anomalies.append({"type": "vibration_excess", "severity": "warning"})
if performance["efficiency"] < 0.85:
anomalies.append({"type": "efficiency_low", "severity": "warning"})
return anomalies
def predict_failures(anomalies: List[Dict]):
"""Simulates failure prediction"""
predictions = []
severity_scores = {"critical": 0.9, "warning": 0.6}
for anomaly in anomalies:
predictions.append({
"component": anomaly["type"].split("_")[0],
"probability": severity_scores[anomaly["severity"]],
"timeframe": "24_hours" if anomaly["severity"] == "critical" else "7_days"
})
return predictions
def schedule_maintenance(predictions: List[Dict]):
"""Simulates maintenance scheduling"""
schedule = []
for pred in predictions:
schedule.append({
"component": pred["component"],
"priority": "immediate" if pred["timeframe"] == "24_hours" else "planned",
"estimated_duration": "2_hours",
"required_parts": ["replacement_" + pred["component"]]
})
return schedule
# Create specialized agents
sensor_monitor = Agent(
name="Sensor Monitor",
role="Data Collection",
goal="Collect sensor data",
instructions="Monitor and collect sensor readings",
tools=[collect_sensor_data]
)
performance_analyzer = Agent(
name="Performance Analyzer",
role="Performance Analysis",
goal="Analyze equipment performance",
instructions="Analyze operational metrics",
tools=[analyze_performance]
)
anomaly_detector = Agent(
name="Anomaly Detector",
role="Anomaly Detection",
goal="Detect operational anomalies",
instructions="Identify abnormal patterns",
tools=[detect_anomalies]
)
failure_predictor = Agent(
name="Failure Predictor",
role="Failure Prediction",
goal="Predict potential failures",
instructions="Predict equipment failures",
tools=[predict_failures]
)
maintenance_scheduler = Agent(
name="Maintenance Scheduler",
role="Maintenance Planning",
goal="Schedule maintenance activities",
instructions="Plan and schedule maintenance",
tools=[schedule_maintenance]
)
# Create workflow tasks
sensor_task = Task(
name="collect_data",
description="Collect sensor data",
expected_output="Sensor readings",
agent=sensor_monitor,
is_start=True,
next_tasks=["analyze_performance"],
async_execution=True
)
performance_task = Task(
name="analyze_performance",
description="Analyze performance metrics",
expected_output="Performance analysis",
agent=performance_analyzer,
next_tasks=["detect_anomalies"],
async_execution=True
)
anomaly_task = Task(
name="detect_anomalies",
description="Detect operational anomalies",
expected_output="Detected anomalies",
agent=anomaly_detector,
next_tasks=["predict_failures"],
context=[sensor_task, performance_task]
)
prediction_task = Task(
name="predict_failures",
description="Predict potential failures",
expected_output="Failure predictions",
agent=failure_predictor,
next_tasks=["schedule_maintenance"],
task_type="decision",
condition={
"critical": ["schedule_maintenance"],
"warning": ["schedule_maintenance"],
"normal": ""
}
)
scheduling_task = Task(
name="schedule_maintenance",
description="Schedule maintenance activities",
expected_output="Maintenance schedule",
agent=maintenance_scheduler,
context=[prediction_task]
)
# Create workflow
workflow = PraisonAIAgents(
agents=[sensor_monitor, performance_analyzer, anomaly_detector,
failure_predictor, maintenance_scheduler],
tasks=[sensor_task, performance_task, anomaly_task,
prediction_task, scheduling_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Predictive Maintenance Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nMaintenance Planning Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
<Step title="Start Agents">
Run your predictive maintenance system:
```bash
python predictive_maintenance.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
</Note>
## Understanding Predictive Maintenance
<Card title="What is Predictive Maintenance?" icon="question">
Predictive maintenance using AI agents enables:
- Real-time equipment monitoring
- Performance analysis and anomaly detection
- Failure prediction and prevention
- Automated maintenance scheduling
- Optimized resource allocation
</Card>
## Features
<CardGroup cols={2}>
<Card title="Real-time Monitoring" icon="gauge-high">
Continuous monitoring of equipment sensors and performance metrics.
</Card>
<Card title="Anomaly Detection" icon="triangle-exclamation">
Automated detection of abnormal patterns and potential issues.
</Card>
<Card title="Failure Prediction" icon="chart-line">
Advanced analytics to predict potential equipment failures.
</Card>
<Card title="Maintenance Planning" icon="calendar">
Automated scheduling of maintenance activities based on predictions.
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
Learn about sequential prompt chaining for complex workflows
</Card>
<Card title="Evaluator Optimizer" icon="magnifying-glass" href="/features/evaluator-optimiser">
Explore how to optimize agent outputs through evaluation
</Card>
</CardGroup>
<Note>
For optimal results, ensure your sensor data collection and analysis parameters are properly configured for your specific equipment.
</Note>
+279
View File
@@ -0,0 +1,279 @@
---
title: "Quantum Optimiser"
description: "Learn how to create AI agents for quantum circuit optimization and performance analysis."
icon: "atom"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Circuit Analyzer]
Analyzer --> Finder[Optimization Finder]
Finder --> Optimizer[Circuit Optimizer]
Optimizer --> Benchmarker[Performance Benchmarker]
Benchmarker --> Validator[Results Validator]
Validator --> Out[Out]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Finder fill:#2E8B57,color:#fff
style Optimizer fill:#2E8B57,color:#fff
style Benchmarker fill:#2E8B57,color:#fff
style Validator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Quantum Circuit Optimization?
Quantum circuit optimization is the process of improving quantum algorithms by reducing circuit depth, minimizing gate count, and enhancing execution efficiency while maintaining computational fidelity. This is crucial for making quantum algorithms practical on real quantum hardware.
## Features
<CardGroup cols={2}>
<Card title="Circuit Analysis" icon="microchip">
Deep analysis of quantum circuit metrics including depth, gate counts, and qubit usage.
</Card>
<Card title="Optimization Detection" icon="magnifying-glass">
Identification of optimization opportunities through gate reduction and parallel execution.
</Card>
<Card title="Performance Simulation" icon="gauge-high">
Simulation of optimization results with improvement metrics and success probabilities.
</Card>
<Card title="Benchmark Testing" icon="chart-line">
Comprehensive benchmarking of execution time, fidelity, and resource usage.
</Card>
<Card title="Result Validation" icon="check-double">
Validation of optimization results ensuring performance gains and fidelity maintenance.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_quantum_circuit():
"""Simulates quantum circuit analysis"""
circuit_metrics = {
"depth": 15 + (int(time.time()) % 10),
"gates": {
"single_qubit": 25 + (int(time.time()) % 15),
"two_qubit": 10 + (int(time.time()) % 8),
"measurement": 5 + (int(time.time()) % 3)
},
"qubits": 8 + (int(time.time()) % 4)
}
return circuit_metrics
def identify_optimization_opportunities(metrics: Dict):
"""Identifies potential optimization areas"""
opportunities = []
if metrics["depth"] > 20:
opportunities.append({
"type": "depth_reduction",
"potential": "high",
"technique": "parallel_gates"
})
if metrics["gates"]["two_qubit"] > 15:
opportunities.append({
"type": "gate_reduction",
"potential": "medium",
"technique": "gate_decomposition"
})
return opportunities
def simulate_optimization(opportunities: List[Dict]):
"""Simulates optimization results"""
results = []
for opt in opportunities:
improvement = {
"high": 0.3 + (time.time() % 2) / 10,
"medium": 0.2 + (time.time() % 2) / 10,
"low": 0.1 + (time.time() % 2) / 10
}
results.append({
"type": opt["type"],
"improvement": improvement[opt["potential"]],
"success_probability": 0.8 + (time.time() % 2) / 10
})
return results
def benchmark_performance(original: Dict, optimized: List[Dict]):
"""Benchmarks optimization performance"""
benchmarks = {
"execution_time": {
"original": 100 + (int(time.time()) % 50),
"optimized": 70 + (int(time.time()) % 30)
},
"fidelity": {
"original": 0.9 + (time.time() % 1) / 10,
"optimized": 0.85 + (time.time() % 1) / 10
},
"resource_usage": {
"original": original["qubits"],
"optimized": original["qubits"] - len(optimized)
}
}
return benchmarks
def validate_results(benchmarks: Dict):
"""Validates optimization results"""
validations = {
"performance_gain": (benchmarks["execution_time"]["original"] -
benchmarks["execution_time"]["optimized"]) /
benchmarks["execution_time"]["original"],
"fidelity_maintained": benchmarks["fidelity"]["optimized"] > 0.8,
"resource_efficient": benchmarks["resource_usage"]["optimized"] <
benchmarks["resource_usage"]["original"]
}
return validations
# Create specialized agents
circuit_analyzer = Agent(
name="Circuit Analyzer",
role="Circuit Analysis",
goal="Analyze quantum circuit structure",
instructions="Evaluate quantum circuit metrics",
tools=[analyze_quantum_circuit]
)
optimization_finder = Agent(
name="Optimization Finder",
role="Optimization Discovery",
goal="Identify optimization opportunities",
instructions="Find potential optimization techniques",
tools=[identify_optimization_opportunities]
)
optimizer = Agent(
name="Circuit Optimizer",
role="Circuit Optimization",
goal="Optimize quantum circuit",
instructions="Apply optimization techniques",
tools=[simulate_optimization]
)
benchmarker = Agent(
name="Performance Benchmarker",
role="Performance Analysis",
goal="Benchmark optimization results",
instructions="Measure performance improvements",
tools=[benchmark_performance]
)
validator = Agent(
name="Results Validator",
role="Validation",
goal="Validate optimization results",
instructions="Ensure optimization quality",
tools=[validate_results]
)
# Create workflow tasks
analysis_task = Task(
name="analyze_circuit",
description="Analyze quantum circuit",
expected_output="Circuit metrics",
agent=circuit_analyzer,
is_start=True,
next_tasks=["find_optimizations"]
)
optimization_task = Task(
name="find_optimizations",
description="Find optimization opportunities",
expected_output="Optimization opportunities",
agent=optimization_finder,
next_tasks=["optimize_circuit"]
)
optimization_execution_task = Task(
name="optimize_circuit",
description="Execute circuit optimization",
expected_output="Optimization results",
agent=optimizer,
next_tasks=["benchmark_performance"]
)
benchmark_task = Task(
name="benchmark_performance",
description="Benchmark optimization",
expected_output="Performance metrics",
agent=benchmarker,
next_tasks=["validate_results"],
context=[analysis_task, optimization_execution_task]
)
validation_task = Task(
name="validate_results",
description="Validate optimization results",
expected_output="Validation results",
agent=validator,
task_type="decision",
condition={
"True": "", # End workflow if validation passes
"False": ["find_optimizations"] # Retry optimization if validation fails
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[circuit_analyzer, optimization_finder, optimizer,
benchmarker, validator],
tasks=[analysis_task, optimization_task, optimization_execution_task,
benchmark_task, validation_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Quantum Algorithm Optimization Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nOptimization Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+274
View File
@@ -0,0 +1,274 @@
---
title: "Research Assistant"
description: "Learn how to create AI agents for research analysis and experiment design."
icon: "microscope"
---
```mermaid
flowchart LR
In[In] --> Analyzer[Paper Analyzer]
Analyzer --> Gap[Gap Identifier]
Gap --> Designer[Experiment Designer]
Designer --> Validator[Methodology Validator]
Validator --> Impact[Impact Predictor]
Impact --> Out[Out]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Gap fill:#2E8B57,color:#fff
style Designer fill:#2E8B57,color:#fff
style Validator fill:#2E8B57,color:#fff
style Impact fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Research Analysis?
Research Analysis is a systematic process of analyzing scientific papers, identifying knowledge gaps, designing experiments, validating methodologies, and predicting research impact. This helps researchers make informed decisions about their research direction and experimental design.
## Features
<CardGroup cols={2}>
<Card title="Paper Analysis" icon="book">
Analysis of research papers with topic identification and impact assessment.
</Card>
<Card title="Gap Identification" icon="magnifying-glass">
Discovery of research gaps with significance and potential evaluation.
</Card>
<Card title="Experiment Design" icon="flask">
Creation of experimental methodologies with resource planning.
</Card>
<Card title="Methodology Validation" icon="check-double">
Validation of experimental design with statistical power and feasibility checks.
</Card>
<Card title="Impact Prediction" icon="chart-line">
Prediction of research impact with novelty and breakthrough probability.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_research_papers():
"""Simulates research paper analysis"""
papers = [
{
"topic": "quantum_computing",
"gaps": ["error_correction", "scalability"],
"methodology": "experimental",
"impact_factor": 8.5
},
{
"topic": "machine_learning",
"gaps": ["interpretability", "robustness"],
"methodology": "theoretical",
"impact_factor": 7.8
}
]
return papers[int(time.time()) % 2]
def identify_knowledge_gaps(papers: Dict):
"""Identifies research gaps"""
gaps = []
for gap in papers["gaps"]:
gaps.append({
"area": gap,
"significance": "high" if papers["impact_factor"] > 8 else "medium",
"research_potential": 0.8 + (time.time() % 2) / 10
})
return gaps
def design_experiment(gaps: List[Dict]):
"""Designs experimental methodology"""
experiments = []
for gap in gaps:
experiments.append({
"area": gap["area"],
"methodology": {
"type": "quantitative",
"duration": "3_months",
"resources_needed": ["equipment_A", "dataset_B"],
"expected_outcome": "validation_metrics"
},
"priority": gap["significance"]
})
return experiments
def validate_methodology(experiments: List[Dict]):
"""Validates experimental design"""
validations = []
for exp in experiments:
validations.append({
"area": exp["area"],
"statistical_power": 0.9 + (time.time() % 1) / 10,
"resource_feasibility": 0.8 + (time.time() % 1) / 10,
"ethical_compliance": True,
"recommendations": []
})
return validations
def predict_impact(experiments: List[Dict], validations: List[Dict]):
"""Predicts research impact"""
predictions = []
for exp, val in zip(experiments, validations):
predictions.append({
"area": exp["area"],
"potential_impact": val["statistical_power"] * 10,
"novelty_score": 0.7 + (time.time() % 3) / 10,
"breakthrough_probability": 0.5 + (time.time() % 4) / 10
})
return predictions
# Create specialized agents
paper_analyzer = Agent(
name="Paper Analyzer",
role="Research Analysis",
goal="Analyze research papers",
instructions="Review and analyze scientific papers",
tools=[analyze_research_papers]
)
gap_identifier = Agent(
name="Gap Identifier",
role="Gap Analysis",
goal="Identify knowledge gaps",
instructions="Identify research opportunities",
tools=[identify_knowledge_gaps]
)
experiment_designer = Agent(
name="Experiment Designer",
role="Experimental Design",
goal="Design research experiments",
instructions="Create experimental methodologies",
tools=[design_experiment]
)
methodology_validator = Agent(
name="Methodology Validator",
role="Validation",
goal="Validate experimental design",
instructions="Ensure methodology validity",
tools=[validate_methodology]
)
impact_predictor = Agent(
name="Impact Predictor",
role="Impact Analysis",
goal="Predict research impact",
instructions="Assess potential impact",
tools=[predict_impact]
)
# Create workflow tasks
analysis_task = Task(
name="analyze_papers",
description="Analyze research papers",
expected_output="Paper analysis results",
agent=paper_analyzer,
is_start=True,
next_tasks=["identify_gaps"]
)
gap_task = Task(
name="identify_gaps",
description="Identify knowledge gaps",
expected_output="Research gaps",
agent=gap_identifier,
next_tasks=["design_experiments"]
)
design_task = Task(
name="design_experiments",
description="Design experiments",
expected_output="Experimental designs",
agent=experiment_designer,
next_tasks=["validate_methodology"]
)
validation_task = Task(
name="validate_methodology",
description="Validate methodology",
expected_output="Validation results",
agent=methodology_validator,
next_tasks=["predict_impact"]
)
prediction_task = Task(
name="predict_impact",
description="Predict research impact",
expected_output="Impact predictions",
agent=impact_predictor,
task_type="decision",
condition={
"high": "", # End workflow if high impact
"medium": ["design_experiments"], # Refine if medium impact
"low": ["identify_gaps"] # Restart if low impact
},
context=[design_task, validation_task]
)
# Create workflow
workflow = PraisonAIAgents(
agents=[paper_analyzer, gap_identifier, experiment_designer,
methodology_validator, impact_predictor],
tasks=[analysis_task, gap_task, design_task,
validation_task, prediction_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Research Assistant Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nResearch Analysis Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+301
View File
@@ -0,0 +1,301 @@
---
title: "Smart City"
description: "Learn how to create AI agents for smart city resource management and optimization."
icon: "city"
---
```mermaid
flowchart LR
In[In] --> Monitor[Utility Monitor]
Monitor --> Analyzer[Pattern Analyzer]
Analyzer --> Optimizer[Resource Optimizer]
Optimizer --> Implementation[Implementation Agent]
Implementation --> Feedback[Feedback Monitor]
Feedback --> Monitor
Feedback --> Optimizer
Feedback --> Out[Out]
style In fill:#8B0000,color:#fff
style Monitor fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Optimizer fill:#2E8B57,color:#fff
style Implementation fill:#2E8B57,color:#fff
style Feedback fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
Learn how to implement a smart city resource management system using AI agents for monitoring, analysis, and optimization of city utilities.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
def monitor_utilities():
"""Simulates utility usage monitoring"""
readings = {
"power": {
"consumption": int(time.time()) % 1000,
"peak_hours": ["morning", "evening"],
"grid_load": "medium"
},
"water": {
"consumption": int(time.time()) % 500,
"pressure": "normal",
"quality": "good"
},
"traffic": {
"congestion": "high",
"peak_zones": ["downtown", "industrial"],
"incidents": 2
}
}
return readings
def analyze_patterns():
"""Simulates usage pattern analysis"""
patterns = [
{"type": "daily_cycle", "confidence": 0.85, "trend": "increasing"},
{"type": "weekly_cycle", "confidence": 0.92, "trend": "stable"},
{"type": "seasonal", "confidence": 0.78, "trend": "decreasing"}
]
return patterns[int(time.time()) % 3]
def optimize_resources(readings: Dict, patterns: Dict):
"""Simulates resource optimization"""
optimizations = {
"power": {
"action": "load_balancing",
"target_zones": ["residential", "commercial"],
"expected_savings": "15%"
},
"water": {
"action": "pressure_adjustment",
"target_zones": ["industrial"],
"expected_savings": "8%"
},
"traffic": {
"action": "signal_timing",
"target_zones": ["downtown"],
"expected_impact": "20% reduction"
}
}
return optimizations
def implement_changes(optimizations: Dict):
"""Simulates implementation of optimization changes"""
success_rates = {
"load_balancing": 0.95,
"pressure_adjustment": 0.88,
"signal_timing": 0.85
}
return {"status": "implemented", "success_rate": success_rates[optimizations["power"]["action"]]}
def monitor_feedback():
"""Simulates monitoring of optimization feedback"""
feedbacks = ["positive", "neutral", "negative"]
return feedbacks[int(time.time()) % 3]
# Create specialized agents
utility_monitor = Agent(
name="Utility Monitor",
role="Resource Monitoring",
goal="Monitor city utility usage",
instructions="Track and report utility consumption patterns",
tools=[monitor_utilities]
)
pattern_analyzer = Agent(
name="Pattern Analyzer",
role="Pattern Analysis",
goal="Analyze usage patterns",
instructions="Identify and analyze resource usage patterns",
tools=[analyze_patterns]
)
resource_optimizer = Agent(
name="Resource Optimizer",
role="Resource Optimization",
goal="Optimize resource allocation",
instructions="Generate resource optimization strategies",
tools=[optimize_resources]
)
implementation_agent = Agent(
name="Implementation Agent",
role="Change Implementation",
goal="Implement optimization changes",
instructions="Execute optimization strategies",
tools=[implement_changes]
)
feedback_monitor = Agent(
name="Feedback Monitor",
role="Feedback Monitoring",
goal="Monitor optimization results",
instructions="Track and analyze optimization feedback",
tools=[monitor_feedback]
)
# Create workflow tasks
monitoring_task = Task(
name="monitor_utilities",
description="Monitor utility usage",
expected_output="Current utility readings",
agent=utility_monitor,
is_start=True,
next_tasks=["analyze_patterns"]
)
pattern_task = Task(
name="analyze_patterns",
description="Analyze usage patterns",
expected_output="Usage patterns analysis",
agent=pattern_analyzer,
next_tasks=["optimize_resources"]
)
optimization_task = Task(
name="optimize_resources",
description="Generate optimization strategies",
expected_output="Resource optimization plans",
agent=resource_optimizer,
next_tasks=["implement_changes"],
context=[monitoring_task, pattern_task]
)
implementation_task = Task(
name="implement_changes",
description="Implement optimization changes",
expected_output="Implementation status",
agent=implementation_agent,
next_tasks=["monitor_feedback"]
)
feedback_task = Task(
name="monitor_feedback",
description="Monitor optimization feedback",
expected_output="Optimization feedback",
agent=feedback_monitor,
task_type="decision",
condition={
"negative": ["monitor_utilities"], # Start over if negative feedback
"neutral": ["optimize_resources"], # Adjust optimization if neutral
"positive": "" # End workflow if positive
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[utility_monitor, pattern_analyzer, resource_optimizer,
implementation_agent, feedback_monitor],
tasks=[monitoring_task, pattern_task, optimization_task,
implementation_task, feedback_task],
process="workflow",
verbose=True
)
def main():
print("\nStarting Smart City Resource Optimization Workflow...")
print("=" * 50)
# Run workflow
results = workflow.start()
# Print results
print("\nOptimization Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
main()
```
</Step>
<Step title="Start Agents">
Run your smart city management system:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
</Note>
## Understanding Smart City Management
<Card title="What is Smart City Management?" icon="question">
Smart city management enables:
- Real-time utility monitoring
- Pattern analysis and prediction
- Resource optimization
- Automated implementation
- Continuous feedback monitoring
</Card>
## Features
<CardGroup cols={2}>
<Card title="Utility Monitoring" icon="gauge">
Monitor city utilities:
- Power consumption
- Water usage
- Traffic patterns
</Card>
<Card title="Pattern Analysis" icon="chart-line">
Analyze usage patterns:
- Daily cycles
- Weekly trends
- Seasonal variations
</Card>
<Card title="Resource Optimization" icon="sliders">
Optimize resource allocation:
- Load balancing
- Pressure adjustment
- Traffic signal timing
</Card>
<Card title="Feedback Loop" icon="rotate">
Continuous improvement:
- Implementation tracking
- Success rate monitoring
- Adaptive optimization
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
Learn about chaining prompts for complex workflows
</Card>
<Card title="Evaluator Optimizer" icon="gauge" href="/features/evaluator-optimiser">
Explore how to optimize and evaluate solutions
</Card>
</CardGroup>
+313
View File
@@ -0,0 +1,313 @@
---
title: "Space Mission"
description: "Learn how to create AI agents for space mission planning and resource optimization."
icon: "rocket"
---
```mermaid
flowchart LR
In[In] --> Mission[Mission Analyzer]
Mission --> Resources[Resource Calculator]
Resources --> Contingency[Contingency Planner]
Contingency --> Optimizer[Resource Optimizer]
Optimizer --> Simulator[Scenario Simulator]
Simulator --> Out[Out]
style In fill:#8B0000,color:#fff
style Mission fill:#2E8B57,color:#fff
style Resources fill:#2E8B57,color:#fff
style Contingency fill:#2E8B57,color:#fff
style Optimizer fill:#2E8B57,color:#fff
style Simulator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Space Mission Planning?
Space Mission Planning is a complex process that involves analyzing mission parameters, calculating resource requirements, planning contingencies, optimizing resource allocation, and simulating various scenarios. This ensures the safety and success of space missions by carefully managing resources and preparing for potential emergencies.
## Features
<CardGroup cols={2}>
<Card title="Mission Analysis" icon="satellite">
Analysis of mission duration, crew size, orbital parameters, and objectives.
</Card>
<Card title="Resource Calculation" icon="calculator">
Computation of life support, power, and propellant requirements.
</Card>
<Card title="Contingency Planning" icon="shield">
Planning for power failures, life support malfunctions, and other emergencies.
</Card>
<Card title="Resource Optimization" icon="chart-line">
Optimization of resource allocation with buffers for contingencies.
</Card>
<Card title="Scenario Simulation" icon="vr-cardboard">
Simulation of nominal operations and emergency scenarios.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def analyze_mission_parameters():
"""Simulates mission parameter analysis"""
parameters = {
"duration": 180, # days
"crew_size": 4,
"orbital_parameters": {
"altitude": 400, # km
"inclination": 51.6, # degrees
"period": 92.68 # minutes
},
"mission_objectives": [
"scientific_research",
"satellite_deployment",
"space_station_maintenance"
]
}
return parameters
def calculate_resource_requirements(params: Dict):
"""Calculates required resources"""
requirements = {
"life_support": {
"oxygen": params["duration"] * params["crew_size"] * 0.84, # kg
"water": params["duration"] * params["crew_size"] * 2.5, # liters
"food": params["duration"] * params["crew_size"] * 1.8 # kg
},
"power": {
"daily_consumption": 30 + (params["crew_size"] * 5), # kWh
"peak_demand": 45 + (params["crew_size"] * 8), # kW
"backup_capacity": 72 # hours
},
"propellant": {
"main_engine": 2000, # kg
"attitude_control": 500, # kg
"reserve": 300 # kg
}
}
return requirements
def plan_contingencies(requirements: Dict):
"""Plans contingency scenarios"""
contingencies = [
{
"scenario": "power_failure",
"probability": 0.05,
"impact": "critical",
"resources_needed": {
"backup_power": requirements["power"]["daily_consumption"] * 3,
"repair_equipment": ["solar_panel_kit", "power_distribution_unit"]
}
},
{
"scenario": "life_support_malfunction",
"probability": 0.03,
"impact": "severe",
"resources_needed": {
"oxygen_reserve": requirements["life_support"]["oxygen"] * 0.2,
"repair_parts": ["filter_system", "pressure_regulators"]
}
}
]
return contingencies[int(time.time()) % 2]
def optimize_allocation(requirements: Dict, contingencies: Dict):
"""Optimizes resource allocation"""
allocation = {
"primary_resources": {
"life_support": {
"nominal": requirements["life_support"],
"buffer": 0.15 # 15% buffer
},
"power": {
"nominal": requirements["power"],
"buffer": 0.2 # 20% buffer
}
},
"contingency_resources": {
"type": contingencies["scenario"],
"allocation": contingencies["resources_needed"],
"priority": "high" if contingencies["impact"] == "critical" else "medium"
}
}
return allocation
def simulate_mission_scenarios(allocation: Dict):
"""Simulates various mission scenarios"""
scenarios = {
"nominal_operations": {
"success_rate": 0.95,
"resource_utilization": 0.85,
"efficiency_rating": 0.9
},
"emergency_scenarios": [
{
"type": "power_reduction",
"duration": 48, # hours
"impact": "moderate",
"resolution_success": 0.88
},
{
"type": "life_support_adjustment",
"duration": 24, # hours
"impact": "minor",
"resolution_success": 0.92
}
]
}
return scenarios
# Create specialized agents
mission_analyzer = Agent(
name="Mission Analyzer",
role="Mission Analysis",
goal="Analyze mission parameters",
instructions="Evaluate mission requirements and constraints",
tools=[analyze_mission_parameters]
)
resource_calculator = Agent(
name="Resource Calculator",
role="Resource Calculation",
goal="Calculate resource requirements",
instructions="Determine required resources for mission",
tools=[calculate_resource_requirements]
)
contingency_planner = Agent(
name="Contingency Planner",
role="Contingency Planning",
goal="Plan for contingencies",
instructions="Develop contingency scenarios and plans",
tools=[plan_contingencies]
)
resource_optimizer = Agent(
name="Resource Optimizer",
role="Resource Optimization",
goal="Optimize resource allocation",
instructions="Optimize resource distribution",
tools=[optimize_allocation]
)
scenario_simulator = Agent(
name="Scenario Simulator",
role="Scenario Simulation",
goal="Simulate mission scenarios",
instructions="Simulate various mission scenarios",
tools=[simulate_mission_scenarios]
)
# Create workflow tasks
mission_task = Task(
name="analyze_mission",
description="Analyze mission parameters",
expected_output="Mission parameters",
agent=mission_analyzer,
is_start=True,
next_tasks=["calculate_resources"]
)
resource_task = Task(
name="calculate_resources",
description="Calculate resource requirements",
expected_output="Resource requirements",
agent=resource_calculator,
next_tasks=["plan_contingencies"]
)
contingency_task = Task(
name="plan_contingencies",
description="Plan contingencies",
expected_output="Contingency plans",
agent=contingency_planner,
context=[resource_task],
next_tasks=["optimize_resources"]
)
optimization_task = Task(
name="optimize_resources",
description="Optimize resource allocation",
expected_output="Resource allocation",
agent=resource_optimizer,
context=[resource_task, contingency_task],
next_tasks=["simulate_scenarios"]
)
simulation_task = Task(
name="simulate_scenarios",
description="Simulate scenarios",
expected_output="Simulation results",
agent=scenario_simulator,
task_type="decision",
condition={
"nominal_operations": "", # End workflow if nominal
"emergency_scenarios": ["optimize_resources"] # Reoptimize if emergency
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[mission_analyzer, resource_calculator, contingency_planner,
resource_optimizer, scenario_simulator],
tasks=[mission_task, resource_task, contingency_task,
optimization_task, simulation_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Space Mission Resource Optimization Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nResource Optimization Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+211
View File
@@ -0,0 +1,211 @@
---
title: "Supply Chain"
sidebarTitle: "Supply Chain"
description: "Learn how to create AI agents for supply chain risk management and mitigation."
icon: "truck"
---
```mermaid
flowchart LR
In[In] --> Monitor[Global Monitor]
Monitor -->|high/medium/critical| Analyzer[Impact Analyzer]
Analyzer --> Generator[Strategy Generator]
Generator --> Out[Out]
style In fill:#8B0000,color:#fff
style Monitor fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how AI agents can monitor global events, analyze supply chain impacts, and generate mitigation strategies.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
def monitor_global_events():
"""Simulates monitoring of global events"""
events = [
{"type": "natural_disaster", "severity": "high", "region": "Asia"},
{"type": "political_unrest", "severity": "medium", "region": "Europe"},
{"type": "economic_crisis", "severity": "critical", "region": "Americas"}
]
return events[int(time.time()) % 3]
def analyze_supply_impact(event: Dict):
"""Simulates impact analysis on supply chain"""
impact_matrix = {
"natural_disaster": {"delay": "severe", "cost": "high", "risk_level": 9},
"political_unrest": {"delay": "moderate", "cost": "medium", "risk_level": 6},
"economic_crisis": {"delay": "significant", "cost": "extreme", "risk_level": 8}
}
return impact_matrix.get(event["type"])
def generate_mitigation_strategies(impact: Dict):
"""Simulates generation of mitigation strategies"""
strategies = {
"severe": ["activate_backup_suppliers", "emergency_logistics_routing"],
"moderate": ["increase_buffer_stock", "alternative_transport"],
"significant": ["diversify_suppliers", "hedge_currency_risks"]
}
return strategies.get(impact["delay"], ["review_supply_chain"])
# Create specialized agents
monitor_agent = Agent(
name="Global Monitor",
role="Event Monitoring",
goal="Monitor and identify global events affecting supply chain",
instructions="Track and report significant global events",
tools=[monitor_global_events]
)
impact_analyzer = Agent(
name="Impact Analyzer",
role="Impact Assessment",
goal="Analyze event impact on supply chain",
instructions="Assess potential disruptions and risks",
tools=[analyze_supply_impact]
)
strategy_generator = Agent(
name="Strategy Generator",
role="Strategy Development",
goal="Generate mitigation strategies",
instructions="Develop strategies to address identified risks",
tools=[generate_mitigation_strategies]
)
# Create workflow tasks
monitoring_task = Task(
name="monitor_events",
description="Monitor global events affecting supply chain",
expected_output="Identified global events",
agent=monitor_agent,
is_start=True,
task_type="decision",
condition={
"high": ["analyze_impact"],
"medium": ["analyze_impact"],
"critical": ["analyze_impact"]
}
)
impact_task = Task(
name="analyze_impact",
description="Analyze impact on supply chain",
expected_output="Impact assessment",
agent=impact_analyzer,
next_tasks=["generate_strategies"]
)
strategy_task = Task(
name="generate_strategies",
description="Generate mitigation strategies",
expected_output="List of mitigation strategies",
agent=strategy_generator,
context=[monitoring_task, impact_task]
)
# Create workflow
workflow = PraisonAIAgents(
agents=[monitor_agent, impact_analyzer, strategy_generator],
tasks=[monitoring_task, impact_task, strategy_task],
process="workflow",
verbose=True
)
def main():
print("\nStarting Supply Chain Risk Management Workflow...")
print("=" * 50)
# Run workflow
results = workflow.start()
# Print results
print("\nRisk Management Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
main()
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
- Basic understanding of Python
</Note>
## Understanding Supply Chain Risk Management
<Card title="What is Supply Chain Risk Management?" icon="question">
Automated supply chain risk management workflow enables:
- Real-time global event monitoring
- Impact assessment and risk analysis
- Strategy generation for risk mitigation
- Proactive supply chain optimization
</Card>
## Features
<CardGroup cols={2}>
<Card title="Event Monitoring" icon="globe">
Monitor global events that could affect supply chain operations.
</Card>
<Card title="Impact Analysis" icon="chart-line">
Assess potential disruptions and quantify risks to the supply chain.
</Card>
<Card title="Strategy Generation" icon="lightbulb">
Generate mitigation strategies based on event impact.
</Card>
<Card title="Risk Management" icon="shield-check">
Proactively manage and mitigate supply chain risks.
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Prompt Chaining" icon="link" href="/features/promptchaining">
Learn about sequential prompt execution
</Card>
<Card title="Evaluator Optimizer" icon="magnifying-glass-chart" href="/features/evaluator-optimiser">
Explore optimization techniques
</Card>
</CardGroup>
+277
View File
@@ -0,0 +1,277 @@
---
title: "Vulnerability Detection"
description: "Learn how to create AI agents for vulnerability detection and analysis."
icon: "shield-check"
---
```mermaid
flowchart LR
In[In] --> Scanner[Pattern Scanner]
Scanner --> Vector[Vector Analyzer]
Vector --> Simulator[Exploit Simulator]
Simulator --> Generator[Signature Generator]
Generator --> Validator[Finding Validator]
Validator --> Out[Out]
style In fill:#8B0000,color:#fff
style Scanner fill:#2E8B57,color:#fff
style Vector fill:#2E8B57,color:#fff
style Simulator fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Validator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
## What is Vulnerability Detection?
Vulnerability Detection is a systematic process of identifying, analyzing, and validating security vulnerabilities in code. It involves pattern scanning, attack vector analysis, exploitation simulation, signature generation, and finding validation to ensure robust security measures are in place.
## Features
<CardGroup cols={2}>
<Card title="Pattern Scanning" icon="magnifying-glass">
Detection of buffer overflows, SQL injections, and race conditions.
</Card>
<Card title="Attack Vector Analysis" icon="route">
Analysis of attack paths, complexity, and CVSS scores.
</Card>
<Card title="Exploit Simulation" icon="bug">
Simulation of exploitation attempts with success rate and detection time.
</Card>
<Card title="Signature Generation" icon="fingerprint">
Creation of vulnerability signatures with reliability metrics.
</Card>
<Card title="Finding Validation" icon="check-double">
Validation of findings with confidence and reproducibility scores.
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
from typing import Dict, List
import asyncio
def scan_code_patterns():
"""Simulates code pattern scanning"""
patterns = [
{
"type": "buffer_overflow",
"severity": "critical",
"location": "memory_management",
"frequency": 3
},
{
"type": "sql_injection",
"severity": "high",
"location": "database_interface",
"frequency": 2
},
{
"type": "race_condition",
"severity": "medium",
"location": "thread_handling",
"frequency": 1
}
]
return patterns[int(time.time()) % 3]
def analyze_attack_vectors(pattern: Dict):
"""Analyzes potential attack vectors"""
vectors = []
severity_scores = {"critical": 9.5, "high": 8.0, "medium": 6.5}
base_score = severity_scores[pattern["type"]]
vectors.append({
"type": pattern["type"],
"attack_path": f"exploit_{pattern['location']}",
"complexity": "high" if pattern["frequency"] < 2 else "medium",
"cvss_score": base_score + (time.time() % 1)
})
return vectors
def simulate_exploitation(vectors: List[Dict]):
"""Simulates exploitation attempts"""
results = []
for vector in vectors:
results.append({
"vector": vector["type"],
"success_rate": 0.7 + (time.time() % 3) / 10,
"detection_time": 100 + (int(time.time()) % 50),
"mitigation_possible": vector["complexity"] != "high"
})
return results
def generate_signatures(results: List[Dict]):
"""Generates vulnerability signatures"""
signatures = []
for result in results:
signatures.append({
"pattern": f"signature_{result['vector']}",
"reliability": result['success_rate'],
"false_positive_rate": 0.1 + (time.time() % 2) / 10,
"detection_speed": result['detection_time']
})
return signatures
def validate_findings(signatures: List[Dict]):
"""Validates vulnerability findings"""
validations = []
for sig in signatures:
validations.append({
"signature": sig["pattern"],
"confidence": sig["reliability"] * (1 - sig["false_positive_rate"]),
"reproducibility": 0.8 + (time.time() % 2) / 10,
"severity": "critical" if sig["reliability"] > 0.8 else "high"
})
return validations
# Create specialized agents
pattern_scanner = Agent(
name="Pattern Scanner",
role="Code Analysis",
goal="Scan for suspicious patterns",
instructions="Analyze code for potential vulnerabilities",
tools=[scan_code_patterns]
)
vector_analyzer = Agent(
name="Vector Analyzer",
role="Attack Vector Analysis",
goal="Analyze attack vectors",
instructions="Identify potential attack paths",
tools=[analyze_attack_vectors]
)
exploit_simulator = Agent(
name="Exploit Simulator",
role="Exploitation Testing",
goal="Simulate exploitation attempts",
instructions="Test potential vulnerabilities",
tools=[simulate_exploitation]
)
signature_generator = Agent(
name="Signature Generator",
role="Signature Creation",
goal="Generate vulnerability signatures",
instructions="Create detection signatures",
tools=[generate_signatures]
)
finding_validator = Agent(
name="Finding Validator",
role="Validation",
goal="Validate findings",
instructions="Verify vulnerability findings",
tools=[validate_findings]
)
# Create workflow tasks
scanning_task = Task(
name="scan_patterns",
description="Scan code patterns",
expected_output="Suspicious patterns",
agent=pattern_scanner,
is_start=True,
next_tasks=["analyze_vectors"]
)
vector_task = Task(
name="analyze_vectors",
description="Analyze attack vectors",
expected_output="Attack vectors",
agent=vector_analyzer,
next_tasks=["simulate_exploits"]
)
simulation_task = Task(
name="simulate_exploits",
description="Simulate exploits",
expected_output="Exploitation results",
agent=exploit_simulator,
next_tasks=["generate_signatures"]
)
signature_task = Task(
name="generate_signatures",
description="Generate signatures",
expected_output="Vulnerability signatures",
agent=signature_generator,
next_tasks=["validate_findings"]
)
validation_task = Task(
name="validate_findings",
description="Validate findings",
expected_output="Validation results",
agent=finding_validator,
task_type="decision",
condition={
"critical": ["scan_patterns"], # Continue scanning if critical
"high": ["analyze_vectors"], # Reanalyze if high
"medium": "" # End workflow if medium
}
)
# Create workflow
workflow = PraisonAIAgents(
agents=[pattern_scanner, vector_analyzer, exploit_simulator,
signature_generator, finding_validator],
tasks=[scanning_task, vector_task, simulation_task,
signature_task, validation_task],
process="workflow",
verbose=True
)
async def main():
print("\nStarting Vulnerability Detection Workflow...")
print("=" * 50)
# Run workflow
results = await workflow.astart()
# Print results
print("\nVulnerability Detection Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
print(f"\nTask: {task_id}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
## Next Steps
<CardGroup>
<Card title="Introduction" icon="book" href="/introduction">
Learn more about PraisonAI and its core concepts
</Card>
<Card title="Quick Start" icon="bolt" href="/quickstart">
Get started with the basics of PraisonAI
</Card>
</CardGroup>
+20
View File
@@ -4,6 +4,26 @@ description: "Async AI Agents allow you to run AI tasks asynchronously, improvin
icon: "clock"
---
```mermaid
flowchart LR
In[In] --> Agent1[AI Agent]
Agent1 --> Agent2[AI Agent]
Agent1 --> Agent3[AI Agent]
Agent1 --> Agent4[AI Agent]
Agent2 --> Out[Out]
Agent3 --> Out
Agent4 --> Out
style In fill:#8B0000,color:#fff
style Agent1 fill:#2E8B57,color:#fff
style Agent2 fill:#2E8B57,color:#fff
style Agent3 fill:#2E8B57,color:#fff
style Agent4 fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
Async AI Agents allow you to run AI tasks asynchronously, improving performance and efficiency in your applications.
## Quick Start
<Tabs>
+41
View File
@@ -4,6 +4,47 @@ description: "AutoAgents automatically creates and manages AI agents and tasks b
icon: "robot"
---
```mermaid
flowchart LR
In[In] --> Plan[Plan Tasks]
subgraph Creation[Automatic Agent Creation]
Plan --> Agent1[AI Agent 1]
Plan --> Agent2[AI Agent 2]
Plan --> Agent3[AI Agent 3]
end
subgraph Tools[Automatic Tool Assignment]
Agent1 --> Tool1[Tools 1]
Agent2 --> Tool2[Tools 2]
Agent3 --> Tool3[Tools 3]
end
Tools --> Execution
subgraph Execution[Execution]
Exec1[AI Agent 1] --> Exec2[AI Agent 2]
Exec2 --> Exec3[AI Agent 3]
end
Exec3 --> Out[Out]
style In fill:#8B0000,color:#fff
style Plan fill:#2E8B57,color:#fff
style Agent1 fill:#2E8B57,color:#fff
style Agent2 fill:#2E8B57,color:#fff
style Agent3 fill:#2E8B57,color:#fff
style Tool1 fill:#2E8B57,color:#fff
style Tool2 fill:#2E8B57,color:#fff
style Tool3 fill:#2E8B57,color:#fff
style Exec1 fill:#2E8B57,color:#fff
style Exec2 fill:#2E8B57,color:#fff
style Exec3 fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
AutoAgents automatically creates and manages AI agents and tasks based on high-level instructions.
## Quick Start
<Tabs>
+277
View File
@@ -0,0 +1,277 @@
---
title: "Agentic Autonomous Workflow"
sidebarTitle: "Autonomous Workflow"
description: "Learn how to create AI agents that can autonomously monitor, act, and adapt based on environment feedback."
icon: "robot"
---
```mermaid
flowchart LR
Human[Human] <--> LLM[LLM Call]
LLM -->|ACTION| Environment[Environment]
Environment -->|FEEDBACK| LLM
LLM --> Stop[Stop]
style Human fill:#8B0000,color:#fff
style LLM fill:#2E8B57,color:#fff
style Environment fill:#8B0000,color:#fff
style Stop fill:#333,color:#fff
```
An agent-based workflow where LLMs act autonomously within a loop, interacting with their environment and receiving feedback to refine their actions and decisions.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import time
def get_environment_state():
"""Simulates getting current environment state"""
current_time = int(time.time())
states = ["normal", "critical", "optimal"]
state = states[current_time % 3]
print(f"Environment state: {state}")
return state
def perform_action(state: str):
"""Simulates performing an action based on state"""
actions = {
"normal": "maintain",
"critical": "fix",
"optimal": "enhance"
}
action = actions.get(state, "observe")
print(f"Performing action: {action} for state: {state}")
return action
def get_feedback():
"""Simulates environment feedback"""
current_time = int(time.time())
feedback = "positive" if current_time % 2 == 0 else "negative"
print(f"Feedback received: {feedback}")
return feedback
# Create specialized agents
llm_caller = Agent(
name="Environment Monitor",
role="State analyzer",
goal="Monitor environment and analyze state",
instructions="Check environment state and provide analysis",
tools=[get_environment_state]
)
action_agent = Agent(
name="Action Executor",
role="Action performer",
goal="Execute appropriate actions based on state",
instructions="Determine and perform actions based on environment state",
tools=[perform_action]
)
feedback_agent = Agent(
name="Feedback Processor",
role="Feedback analyzer",
goal="Process environment feedback and adapt strategy",
instructions="Analyze feedback and provide adaptation recommendations",
tools=[get_feedback]
)
# Create tasks for autonomous workflow
monitor_task = Task(
name="monitor_environment",
description="Monitor and analyze environment state",
expected_output="Current environment state analysis",
agent=llm_caller,
is_start=True,
task_type="decision",
next_tasks=["execute_action"],
condition={
"normal": ["execute_action"],
"critical": ["execute_action"],
"optimal": "exit"
}
)
action_task = Task(
name="execute_action",
description="Execute appropriate action based on state",
expected_output="Action execution result",
agent=action_agent,
next_tasks=["process_feedback"]
)
feedback_task = Task(
name="process_feedback",
description="Process feedback and adapt strategy",
expected_output="Strategy adaptation based on feedback",
agent=feedback_agent,
next_tasks=["monitor_environment"], # Create feedback loop
context=[monitor_task, action_task] # Access to previous states and actions
)
# Create workflow manager
workflow = PraisonAIAgents(
agents=[llm_caller, action_agent, feedback_agent],
tasks=[monitor_task, action_task, feedback_task],
process="workflow",
verbose=True
)
def main():
print("\nStarting Autonomous Agent Workflow...")
print("=" * 50)
# Run autonomous workflow
results = workflow.start()
# Print results
print("\nAutonomous Agent Results:")
print("=" * 50)
for task_id, result in results["task_results"].items():
if result:
task_name = result.description
print(f"\nTask: {task_name}")
print(f"Result: {result.raw}")
print("-" * 50)
if __name__ == "__main__":
main()
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
- Basic understanding of Python
</Note>
## Understanding Autonomous Workflow
<Card title="What is Autonomous Workflow?" icon="question">
Autonomous Workflow enables:
- Continuous environment monitoring
- Automated decision-making and action execution
- Real-time feedback processing
- Self-adapting behavior based on outcomes
</Card>
## Features
<CardGroup cols={2}>
<Card title="Environment Monitoring" icon="eye">
Continuously monitor and analyze environment state.
</Card>
<Card title="Adaptive Actions" icon="gears">
Execute context-aware actions based on state analysis.
</Card>
<Card title="Feedback Processing" icon="rotate">
Process and learn from action outcomes.
</Card>
<Card title="Self-Optimization" icon="arrow-trend-up">
Improve performance through continuous learning.
</Card>
</CardGroup>
## Configuration Options
```python
# Create a monitor agent
monitor = Agent(
name="Environment Monitor",
role="State analyzer",
goal="Monitor and analyze state",
tools=[get_environment_state], # Environment monitoring tools
verbose=True # Enable detailed logging
)
# Create an action agent
action = Agent(
name="Action Executor",
role="Action performer",
goal="Execute appropriate actions",
tools=[perform_action] # Action execution tools
)
# Create monitoring task
monitor_task = Task(
name="monitor_environment",
description="Monitor environment state",
agent=monitor,
is_start=True,
task_type="decision",
condition={
"normal": ["execute_action"],
"critical": ["execute_action"],
"optimal": "exit"
}
)
# Create feedback loop task
feedback_task = Task(
name="process_feedback",
description="Process and adapt",
agent=feedback_agent,
next_tasks=["monitor_environment"], # Create feedback loop
context=[monitor_task, action_task] # Access history
)
```
## Troubleshooting
<CardGroup cols={2}>
<Card title="Monitoring Issues" icon="triangle-exclamation">
If monitoring fails:
- Check environment access
- Verify state detection
- Enable verbose mode for debugging
</Card>
<Card title="Adaptation Flow" icon="diagram-project">
If adaptation is incorrect:
- Review feedback processing
- Check action outcomes
- Verify learning loop
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="AutoAgents" icon="robot" href="./autoagents">
Learn about automatically created and managed AI agents
</Card>
<Card title="Mini Agents" icon="microchip" href="./mini">
Explore lightweight, focused AI agents
</Card>
</CardGroup>
<Note>
For optimal results, ensure your environment monitoring is reliable and your feedback processing logic is properly configured for effective adaptation.
</Note>
+14
View File
@@ -5,6 +5,20 @@ description: "Learn how to implement callbacks to monitor and log AI agent inter
icon: "bell"
---
```mermaid
flowchart LR
In[In] --> Agent[AI Agent]
Agent --> Out[Out]
Agent --> Callback[Callback]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Callback fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
Learn how to implement callbacks to monitor and log AI agent interactions, errors, and task completions.
## Quick Start
<Tabs>
+244
View File
@@ -0,0 +1,244 @@
---
title: "Chat with PDF Agents"
sidebarTitle: "Chat with PDF"
description: "Learn how to create AI agents that can intelligently chat with PDF documents using vector databases for efficient information retrieval."
icon: "file-pdf"
---
```mermaid
flowchart LR
PDF[PDF Document] --> PDFAgent[("PDF Chat Agent")]
VDB[(Vector DB)] --> PDFAgent
PDFAgent --> Chat[Chat Interface]
Chat --> |Query| VDB
Chat --> Out[Response]
style PDF fill:#8B0000,color:#fff
style PDFAgent fill:#2E8B57,color:#fff,shape:circle
style VDB fill:#4169E1,color:#fff,shape:cylinder
style Chat fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A PDF-centric workflow where Chat agents interact with vector databases to store and retrieve information from PDF documents, enabling natural conversations and intelligent question-answering capabilities.
## Quick Start
<Steps>
<Step title="Install Package">
Install PraisonAI Agents with PDF chat support:
```bash
pip install "praisonaiagents[knowledge]"
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key:
```bash
export OPENAI_API_KEY=xxxxx
```
</Step>
<Step title="Create Script">
Create a new file `chat_with_pdf.py`:
```python
from praisonaiagents import Agent
agent = Agent(
name="PDF Chat Agent",
instructions="You answer questions based on the provided PDF document.",
knowledge=["document.pdf"], # PDF Indexing
)
agent.start("What is the main topic of this PDF?") # Chat Query
```
</Step>
</Steps>
## PDF Processing and Chat Agents
<Note>
PDF processing involves indexing the document content for efficient retrieval during chat.
</Note>
```mermaid
flowchart LR
subgraph In[Input]
PDF[PDF Documents]
end
subgraph Router[Vector Store]
DB[(Vector DB)]
end
subgraph Out[Chat Agents]
A1[Chat Agent 1]
A2[Chat Agent 2]
A3[Chat Agent 3]
end
In --> Router
Router --> A1
Router --> A2
Router --> A3
style In fill:#8B0000,color:#fff
style Router fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
The simplest way to create a PDF chat agent is without any configuration:
```python
from praisonaiagents import Agent
agent = Agent(
name="PDF Chat Agent",
instructions="You answer questions based on the provided PDF document.",
knowledge=["document.pdf"] # PDF Indexing
)
agent.start("What are the key points in this document?") # Chat Query
```
### Advanced Configuration
For more control over the knowledge base, you can specify a configuration:
```python
from praisonaiagents import Agent
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison",
}
}
}
agent = Agent(
name="PDF Chat Agent",
instructions="You answer questions based on the provided PDF document.",
knowledge=["document.pdf"], # PDF Indexing
knowledge_config=config # Configuration
)
agent.start("What is the main topic of this PDF?") # Chat Query
```
### Multi-Agent Knowledge System
For more complex scenarios, you can create a knowledge-based system with multiple agents:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import logging
import os
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Define the configuration for the Knowledge instance
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison",
}
}
}
# Create an agent with knowledge capabilities
knowledge_agent = Agent(
name="KnowledgeAgent",
role="Information Specialist",
goal="Store and retrieve knowledge efficiently",
backstory="Expert in managing and utilizing stored knowledge",
knowledge=["sample.pdf"], # Indexing
knowledge_config=config, # Configuration
verbose=True
)
# Define a task for the agent
knowledge_task = Task(
name="knowledge_task",
description="Who is Mervin Praison?",
expected_output="Answer to the question",
agent=knowledge_agent # Agent
)
# Create and start the agents
agents = PraisonAIAgents(
agents=[knowledge_agent],
tasks=[knowledge_task],
process="sequential",
user_id="user1" # User ID
)
# Start execution
result = agents.start() # Retrieval
```
## Understanding PDF Chat Agents
<Card title="What are PDF Chat Agents?" icon="question">
PDF Chat agents enable:
- Natural conversation with PDF documents
- Intelligent information extraction
- Context-aware document understanding
- Quick answers to document-specific questions
</Card>
## Features
<CardGroup cols={2}>
<Card title="PDF Processing" icon="file-pdf">
Process and index PDF documents efficiently.
</Card>
<Card title="Natural Chat" icon="comments">
Have natural conversations about PDF content.
</Card>
<Card title="Smart Retrieval" icon="brain">
Intelligently retrieve relevant information from PDFs.
</Card>
<Card title="Context Awareness" icon="layer-group">
Maintain context throughout the conversation.
</Card>
</CardGroup>
## Troubleshooting
<CardGroup cols={2}>
<Card title="PDF Issues" icon="triangle-exclamation">
If PDF processing isn't working:
- Check PDF file format and encoding
- Verify document accessibility
- Enable verbose mode for debugging
</Card>
<Card title="Chat Issues" icon="gauge-high">
If chat responses aren't accurate:
- Check PDF indexing quality
- Verify question clarity
- Monitor context retention
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="AutoAgents" icon="robot" href="./autoagents">
Learn about automatically created and managed AI agents
</Card>
<Card title="Mini Agents" icon="microchip" href="./mini">
Explore lightweight, focused AI agents
</Card>
</CardGroup>
<Note>
For optimal chat experience, ensure your PDFs are properly formatted and text-searchable.
</Note>
+230
View File
@@ -0,0 +1,230 @@
---
title: "Agentic Evaluator Optimizer"
sidebarTitle: "Evaluator Optimizer"
description: "Learn how to create AI agents that can generate and optimize solutions through iterative feedback."
icon: "arrows-rotate"
---
```mermaid
flowchart LR
In[In] --> Generator[LLM Call Generator]
Generator -->|SOLUTION| Evaluator[LLM Call Evaluator] -->|ACCEPTED| Out[Out]
Evaluator -->|REJECTED + FEEDBACK| Generator
style In fill:#8B0000,color:#fff
style Generator fill:#2E8B57,color:#fff
style Evaluator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A feedback loop workflow where LLM-generated outputs are evaluated, refined, and optimized iteratively to improve accuracy and relevance.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create generator and evaluator agents
generator = Agent(
name="Generator",
role="Solution generator",
goal="Generate initial solutions and incorporate feedback",
instructions=(
"1. Look at the context from previous tasks.\n"
"2. If you see that you have already produced 2 points, then add another 2 new points "
" so that the total becomes 10.\n"
"3. Otherwise, just produce the first 2 points.\n"
"4. Return only the final list of points, with no extra explanation."
)
)
evaluator = Agent(
name="Evaluator",
role="Solution evaluator",
goal="Evaluate solutions and provide improvement feedback",
instructions=(
"1. Count how many lines in the response start with a number and a period (like '1. ' or '2. ').\n"
"2. If there are 10 or more, respond with 'done'.\n"
"3. Otherwise, respond with 'more'.\n"
"4. Return only the single word: 'done' or 'more'."
)
)
# Create tasks for the feedback loop
generate_task = Task(
name="generate",
description="Write 2 points about AI incuding if anything exiting from previous points",
expected_output="2 points",
agent=generator,
is_start=True,
task_type="decision",
next_tasks=["evaluate"]
)
evaluate_task = Task(
name="evaluate",
description="Check if there are 10 points about AI",
expected_output="more or done",
agent=evaluator,
next_tasks=["generate"],
context=[generate_task],
task_type="decision",
condition={
"more": ["generate"], # Continue to generate
"done": [""] # Exit when optimization complete
}
)
# Create workflow manager
workflow = PraisonAIAgents(
agents=[generator, evaluator],
tasks=[generate_task, evaluate_task],
process="workflow",
verbose=True
)
# Run optimization workflow
results = workflow.start()
# Print results
print("\nEvaluator-Optimizer Results:")
for task_id, result in results["task_results"].items():
if result:
print(f"Task {task_id}: {result.raw}")
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python app.py
```
</Step>
</Steps>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
- Basic understanding of Python
</Note>
## Understanding Evaluator-Optimizer
<Card title="What is Evaluator-Optimizer?" icon="question">
Evaluator-Optimizer pattern enables:
- Iterative solution generation and refinement
- Automated quality evaluation
- Feedback-driven optimization
- Continuous improvement loops
</Card>
## Features
<CardGroup cols={2}>
<Card title="Solution Generation" icon="wand-magic-sparkles">
Generate solutions based on requirements and feedback.
</Card>
<Card title="Quality Evaluation" icon="magnifying-glass-chart">
Automatically assess solution quality and completeness.
</Card>
<Card title="Feedback Loop" icon="rotate">
Implement iterative improvement through feedback cycles.
</Card>
<Card title="Process Control" icon="sliders">
Monitor and control the optimization process.
</Card>
</CardGroup>
## Configuration Options
```python
# Create a generator agent
generator = Agent(
name="Generator",
role="Solution generator",
goal="Generate and improve solutions",
instructions="Step-by-step instructions for generation",
verbose=True # Enable detailed logging
)
# Create an evaluator agent
evaluator = Agent(
name="Evaluator",
role="Solution evaluator",
goal="Evaluate and provide feedback",
instructions="Evaluation criteria and feedback format"
)
# Create tasks with feedback loop
generate_task = Task(
name="generate",
description="Generate solution",
agent=generator,
is_start=True,
task_type="decision",
next_tasks=["evaluate"]
)
evaluate_task = Task(
name="evaluate",
description="Evaluate solution",
agent=evaluator,
context=[generate_task],
task_type="decision",
condition={
"more": ["generate"], # Continue optimization
"done": [""] # Exit when complete
}
)
```
## Troubleshooting
<CardGroup cols={2}>
<Card title="Generation Issues" icon="triangle-exclamation">
If generation is not improving:
- Review generator instructions
- Check feedback integration
- Enable verbose mode for debugging
</Card>
<Card title="Evaluation Flow" icon="diagram-project">
If evaluation cycle is incorrect:
- Verify evaluation criteria
- Check condition mappings
- Review feedback loop connections
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="AutoAgents" icon="robot" href="./autoagents">
Learn about automatically created and managed AI agents
</Card>
<Card title="Mini Agents" icon="microchip" href="./mini">
Explore lightweight, focused AI agents
</Card>
</CardGroup>
<Note>
For optimal results, ensure your generator instructions and evaluation criteria are clear and well-defined to achieve the desired optimization outcomes.
</Note>
Loaded 100 of 475 files, more files were not shown because too many files have changed in this diff. Show more