Compare commits

...
167 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
Mervin Praison 1c1a1b719b Merge pull request #283 from MervinPraison/develop
Update PraisonAI to version 2.0.40 and enhance logging
2025-01-11 16:02:16 +00:00
MervinPraison a8e0914e05 Update PraisonAI to version 2.0.40 and enhance logging
- Updated the PraisonAI package version from 2.0.39 to 2.0.40 in Dockerfile, pyproject.toml, and related files.
- Added a new memory configuration option in agents.yaml to control memory usage.
- Improved logging throughout the codebase by changing info logs to debug logs for better traceability.
- Updated .gitignore to include new files for better project management.
- Adjusted dependencies in pyproject.toml and uv.lock for compatibility with the new version.
2025-01-11 16:01:54 +00:00
Mervin Praison ec6d883f4f Merge pull request #282 from MervinPraison/develop
adding langchain agent doc
2025-01-11 08:21:48 +00:00
MervinPraison d094cbfac5 adding langchain agent doc 2025-01-11 08:21:25 +00:00
Mervin Praison 14e3724aed Merge pull request #281 from MervinPraison/develop
Update praisonaiagents to version 0.0.31 and enhance agent functionality
2025-01-11 07:51:59 +00:00
MervinPraison 92436277d9 Update praisonaiagents to version 0.0.31 and enhance agent functionality
- Updated the version of the praisonaiagents package from 0.0.30 to 0.0.31 in pyproject.toml and related files.
- Added a new Fact Agent to store and retrieve facts, improving the overall functionality of the agent system.
- Enhanced the Research Agent with multiple tasks focused on AI topics, including healthcare and education.
- Updated display functions to include agent information in the output, improving clarity during interactions.
- Improved logging for agent processing and responses, aiding in debugging and tracking agent activities.
- Adjusted dependencies in pyproject.toml and uv.lock for compatibility with the new version.
2025-01-11 07:51:05 +00:00
Mervin Praison 3e0fd298e2 Merge pull request #280 from MervinPraison/develop
AI Agents with memory
2025-01-10 17:21:44 +00:00
MervinPraison fad0b41b52 Update PraisonAI to version 2.0.38 and enhance memory management
- Updated PraisonAI package version from 2.0.37 to 2.0.38 in Dockerfile, pyproject.toml, and related files.
- Refactored memory handling in memory_example.py to improve database path management and logging.
- Introduced new memory management features in the PraisonAIAgents class, allowing for better context retention across tasks.
- Enhanced logging throughout the codebase for improved debugging and tracking of memory operations.
- Added comprehensive documentation on memory capabilities, including short-term and long-term memory management.
- Updated dependencies in pyproject.toml and uv.lock for compatibility with the new version.
2025-01-10 17:20:54 +00:00
MervinPraison 6c3e5ee187 Agents(memory=True) working
Refactor memory management and enhance agent initialization

- Removed direct memory initialization from memory_example.py and integrated shared memory handling into PraisonAIAgents class.
- Updated PraisonAIAgents constructor to accept a memory flag, initializing shared memory if enabled.
- Assigned shared memory to tasks dynamically, improving data sharing between agents.
- Enhanced logging for memory initialization and task assignment to facilitate debugging.
2025-01-10 06:11:35 +00:00
MervinPraison f842ee7048 Update chainlit dependency to version 2.0.1 and improve tool registration in realtime.py
- Updated chainlit version from 1.3.2 to 2.0.1 in pyproject.toml and uv.lock.
- Enhanced tool registration logic in realtime.py to ensure only valid tools are added, with improved error handling and logging for invalid tool definitions.
- Refactored custom tools processing to support both formatted and unformatted tool definitions.
2025-01-10 06:01:47 +00:00
MervinPraison b0ff6f3f60 Update .gitignore and add new ignore files; enhance memory_example.py and memory.py functionality
- Updated .gitignore to include chroma_db/ directory.
- Added .praisoncontext and .praisonignore files for better project structure.
- Refactored memory_example.py to improve memory retrieval and logging.
- Enhanced memory.py to handle exceptions during ChromaDB collection initialization and updated embedding model to 'text-embedding-3-small'.
- Improved logging for embedding operations and ensured API key is set correctly.
2025-01-10 05:40:32 +00:00
MervinPraison 798f6dad14 Refactor memory handling and enhance task execution flow
- Improved memory initialization and management in memory_example.py and Task class.
- Integrated shared memory for tasks to facilitate data sharing between agents.
- Enhanced error handling and logging for memory operations in the Memory class.
- Updated task execution to include memory context and quality metrics.
- Added new task for querying both short-term and long-term memory.
- Improved overall structure and clarity of code with better logging practices.
2025-01-09 10:24:53 +00:00
MervinPraison 629bf0d669 Refactor memory management and enhance search functionality
- Removed unused imports and improved logging in memory_example.py.
- Updated Task description and expected output for clarity.
- Enhanced Memory class to support OpenAI embeddings for improved search capabilities.
- Added quality and relevance filtering in search_short_term and search_long_term methods.
- Implemented deletion of existing ChromaDB collection before creating a new one.
- Improved error handling and logging for database operations.
2025-01-09 06:44:25 +00:00
MervinPraison eaca447b82 Enhance code structure and documentation:
- Updated cursor rules for minimal code changes and user-friendly function naming.
- Integrated Memory module into the PraisonAIAgents initialization.
- Modified Agent class parameters for improved flexibility and default values.
- Enhanced Task class with memory and quality check features, including logging for quality metrics during execution.
2025-01-09 06:23:00 +00:00
Mervin Praison bef3693627 Merge pull request #278 from MervinPraison/develop
updating docs
2025-01-08 16:43:47 +00:00
MervinPraison aa62babed6 updating docs 2025-01-08 16:43:30 +00:00
Mervin Praison b73f181200 Merge pull request #277 from MervinPraison/develop
Updating Docs
2025-01-08 13:42:39 +00:00
MervinPraison 66d2998047 Updating Docs 2025-01-08 13:42:00 +00:00
Mervin Praison c5b6f8b91a Merge pull request #276 from MervinPraison/develop
adding autoagents
2025-01-08 06:47:17 +00:00
MervinPraison 823e46ca84 adding autoagents 2025-01-08 06:47:02 +00:00
499 changed files with 51747 additions and 5529 deletions

No files matched your search

+2 -1
View File
@@ -65,4 +65,5 @@ outputs
agents/praisonaiagents/build
agents/praisonaiagents/dist
agents/praisonaiagents/praisonaiagents.egg-info
.codegpt
.codegpt
.praison
+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.
+1
View File
@@ -1,6 +1,7 @@
framework: praisonai
process: sequential
topic: create movie script about cat in mars
memory: false
roles:
researcher:
backstory: Skilled in research, with a focus on gathering accurate and relevant
-6
View File
@@ -1,6 +0,0 @@
Make it minimal change as possible
Firstly try not to make any modification to the existing code as possible
Only if its highly required, without that if it can't be done, then modify the existing.
So by default try to add new code section and not modify the existing.
-4
View File
@@ -1,4 +0,0 @@
"""Agent module for AI agents"""
from .agent import Agent
__all__ = ['Agent']
-736
View File
@@ -1,736 +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: bool = True,
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: Optional[bool] = None,
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=False, # 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():
display_instruction(f"Agent {self.name} is processing prompt: {display_text}", console=self.console)
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.info(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
# 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
-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")
-74
View File
@@ -1,74 +0,0 @@
import logging
import asyncio
from typing import List, Optional, Dict, Any, Type, Callable, Union, Coroutine
from pydantic import BaseModel
from ..main import TaskOutput
from ..agent.agent import Agent
import uuid
class Task:
def __init__(
self,
description: str,
expected_output: str,
agent: Optional[Agent] = None,
name: Optional[str] = None,
tools: Optional[List[Any]] = None,
context: Optional[List["Task"]] = None,
async_execution: Optional[bool] = False,
config: Optional[Dict[str, Any]] = None,
output_file: Optional[str] = None,
output_json: Optional[Type[BaseModel]] = None,
output_pydantic: Optional[Type[BaseModel]] = None,
callback: Optional[Union[Callable[[TaskOutput], Any], Callable[[TaskOutput], Coroutine[Any, Any, Any]]]] = None,
status: str = "not started",
result: Optional[TaskOutput] = None,
create_directory: Optional[bool] = False,
id: Optional[int] = None,
images: Optional[List[str]] = None,
next_tasks: Optional[List[str]] = None,
task_type: str = "task",
condition: Optional[Dict[str, List[str]]] = None,
is_start: bool = False,
loop_state: Optional[Dict[str, Union[str, int]]] = None
):
self.id = str(uuid.uuid4()) if id is None else str(id)
self.name = name
self.description = description
self.expected_output = expected_output
self.agent = agent
self.tools = tools if tools else []
self.context = context if context else []
self.async_execution = async_execution
self.config = config if config else {}
self.output_file = output_file
self.output_json = output_json
self.output_pydantic = output_pydantic
self.callback = callback
self.status = status
self.result = result
self.create_directory = create_directory
self.images = images if images else []
self.next_tasks = next_tasks if next_tasks else []
self.task_type = task_type
self.condition = condition if condition else {}
self.is_start = is_start
self.loop_state = loop_state if loop_state else {}
if self.output_json and self.output_pydantic:
raise ValueError("Only one output type can be defined")
# Track previous tasks based on next_tasks relationships
self.previous_tasks = []
def __str__(self):
return f"Task(name='{self.name if self.name else 'None'}', description='{self.description}', agent='{self.agent.name if self.agent else 'None'}', status='{self.status}')"
async def execute_callback(self, task_output: TaskOutput) -> None:
"""Execute the callback function, handling both sync and async callbacks"""
if self.callback:
if asyncio.iscoroutinefunction(self.callback):
await self.callback(task_output)
else:
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, self.callback, task_output)
-16
View File
@@ -1,16 +0,0 @@
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "praisonaiagents"
version = "0.0.27"
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
authors = [
{ name="Mervin Praison" }
]
dependencies = [
"pydantic",
"rich",
"openai"
]
-321
View File
@@ -1,321 +0,0 @@
version = 1
requires-python = ">=3.11"
[[package]]
name = "annotated-types"
version = "0.7.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643 },
]
[[package]]
name = "anyio"
version = "4.7.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "idna" },
{ name = "sniffio" },
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/f6/40/318e58f669b1a9e00f5c4453910682e2d9dd594334539c7b7817dabb765f/anyio-4.7.0.tar.gz", hash = "sha256:2f834749c602966b7d456a7567cafcb309f96482b5081d14ac93ccd457f9dd48", size = 177076 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a0/7a/4daaf3b6c08ad7ceffea4634ec206faeff697526421c20f07628c7372156/anyio-4.7.0-py3-none-any.whl", hash = "sha256:ea60c3723ab42ba6fff7e8ccb0488c898ec538ff4df1f1d5e642c3601d07e352", size = 93052 },
]
[[package]]
name = "certifi"
version = "2024.12.14"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/0f/bd/1d41ee578ce09523c81a15426705dd20969f5abf006d1afe8aeff0dd776a/certifi-2024.12.14.tar.gz", hash = "sha256:b650d30f370c2b724812bee08008be0c4163b163ddaec3f2546c1caf65f191db", size = 166010 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/a5/32/8f6669fc4798494966bf446c8c4a162e0b5d893dff088afddf76414f70e1/certifi-2024.12.14-py3-none-any.whl", hash = "sha256:1275f7a45be9464efc1173084eaa30f866fe2e47d389406136d332ed4967ec56", size = 164927 },
]
[[package]]
name = "colorama"
version = "0.4.6"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 },
]
[[package]]
name = "distro"
version = "1.9.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/fc/f8/98eea607f65de6527f8a2e8885fc8015d3e6f5775df186e443e0964a11c3/distro-1.9.0.tar.gz", hash = "sha256:2fa77c6fd8940f116ee1d6b94a2f90b13b5ea8d019b98bc8bafdcabcdd9bdbed", size = 60722 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277 },
]
[[package]]
name = "h11"
version = "0.14.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f5/38/3af3d3633a34a3316095b39c8e8fb4853a28a536e55d347bd8d8e9a14b03/h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d", size = 100418 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/95/04/ff642e65ad6b90db43e668d70ffb6736436c7ce41fcc549f4e9472234127/h11-0.14.0-py3-none-any.whl", hash = "sha256:e3fe4ac4b851c468cc8363d500db52c2ead036020723024a109d37346efaa761", size = 58259 },
]
[[package]]
name = "httpcore"
version = "1.0.7"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "certifi" },
{ name = "h11" },
]
sdist = { url = "https://files.pythonhosted.org/packages/6a/41/d7d0a89eb493922c37d343b607bc1b5da7f5be7e383740b4753ad8943e90/httpcore-1.0.7.tar.gz", hash = "sha256:8551cb62a169ec7162ac7be8d4817d561f60e08eaa485234898414bb5a8a0b4c", size = 85196 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/87/f5/72347bc88306acb359581ac4d52f23c0ef445b57157adedb9aee0cd689d2/httpcore-1.0.7-py3-none-any.whl", hash = "sha256:a3fff8f43dc260d5bd363d9f9cf1830fa3a458b332856f34282de498ed420edd", size = 78551 },
]
[[package]]
name = "httpx"
version = "0.28.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
{ name = "certifi" },
{ name = "httpcore" },
{ name = "idna" },
]
sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517 },
]
[[package]]
name = "idna"
version = "3.10"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442 },
]
[[package]]
name = "jiter"
version = "0.8.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f8/70/90bc7bd3932e651486861df5c8ffea4ca7c77d28e8532ddefe2abc561a53/jiter-0.8.2.tar.gz", hash = "sha256:cd73d3e740666d0e639f678adb176fad25c1bcbdae88d8d7b857e1783bb4212d", size = 163007 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/b0/c1a7caa7f9dc5f1f6cfa08722867790fe2d3645d6e7170ca280e6e52d163/jiter-0.8.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:2dd61c5afc88a4fda7d8b2cf03ae5947c6ac7516d32b7a15bf4b49569a5c076b", size = 303666 },
{ url = "https://files.pythonhosted.org/packages/f5/97/0468bc9eeae43079aaa5feb9267964e496bf13133d469cfdc135498f8dd0/jiter-0.8.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a6c710d657c8d1d2adbbb5c0b0c6bfcec28fd35bd6b5f016395f9ac43e878a15", size = 311934 },
{ url = "https://files.pythonhosted.org/packages/e5/69/64058e18263d9a5f1e10f90c436853616d5f047d997c37c7b2df11b085ec/jiter-0.8.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a9584de0cd306072635fe4b89742bf26feae858a0683b399ad0c2509011b9dc0", size = 335506 },
{ url = "https://files.pythonhosted.org/packages/9d/14/b747f9a77b8c0542141d77ca1e2a7523e854754af2c339ac89a8b66527d6/jiter-0.8.2-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5a90a923338531b7970abb063cfc087eebae6ef8ec8139762007188f6bc69a9f", size = 355849 },
{ url = "https://files.pythonhosted.org/packages/53/e2/98a08161db7cc9d0e39bc385415890928ff09709034982f48eccfca40733/jiter-0.8.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d21974d246ed0181558087cd9f76e84e8321091ebfb3a93d4c341479a736f099", size = 381700 },
{ url = "https://files.pythonhosted.org/packages/7a/38/1674672954d35bce3b1c9af99d5849f9256ac8f5b672e020ac7821581206/jiter-0.8.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:32475a42b2ea7b344069dc1e81445cfc00b9d0e3ca837f0523072432332e9f74", size = 389710 },
{ url = "https://files.pythonhosted.org/packages/f8/9b/92f9da9a9e107d019bcf883cd9125fa1690079f323f5a9d5c6986eeec3c0/jiter-0.8.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8b9931fd36ee513c26b5bf08c940b0ac875de175341cbdd4fa3be109f0492586", size = 345553 },
{ url = "https://files.pythonhosted.org/packages/44/a6/6d030003394e9659cd0d7136bbeabd82e869849ceccddc34d40abbbbb269/jiter-0.8.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ce0820f4a3a59ddced7fce696d86a096d5cc48d32a4183483a17671a61edfddc", size = 376388 },
{ url = "https://files.pythonhosted.org/packages/ad/8d/87b09e648e4aca5f9af89e3ab3cfb93db2d1e633b2f2931ede8dabd9b19a/jiter-0.8.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:8ffc86ae5e3e6a93765d49d1ab47b6075a9c978a2b3b80f0f32628f39caa0c88", size = 511226 },
{ url = "https://files.pythonhosted.org/packages/77/95/8008ebe4cdc82eac1c97864a8042ca7e383ed67e0ec17bfd03797045c727/jiter-0.8.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:5127dc1abd809431172bc3fbe8168d6b90556a30bb10acd5ded41c3cfd6f43b6", size = 504134 },
{ url = "https://files.pythonhosted.org/packages/26/0d/3056a74de13e8b2562e4d526de6dac2f65d91ace63a8234deb9284a1d24d/jiter-0.8.2-cp311-cp311-win32.whl", hash = "sha256:66227a2c7b575720c1871c8800d3a0122bb8ee94edb43a5685aa9aceb2782d44", size = 203103 },
{ url = "https://files.pythonhosted.org/packages/4e/1e/7f96b798f356e531ffc0f53dd2f37185fac60fae4d6c612bbbd4639b90aa/jiter-0.8.2-cp311-cp311-win_amd64.whl", hash = "sha256:cde031d8413842a1e7501e9129b8e676e62a657f8ec8166e18a70d94d4682855", size = 206717 },
{ url = "https://files.pythonhosted.org/packages/a1/17/c8747af8ea4e045f57d6cfd6fc180752cab9bc3de0e8a0c9ca4e8af333b1/jiter-0.8.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:e6ec2be506e7d6f9527dae9ff4b7f54e68ea44a0ef6b098256ddf895218a2f8f", size = 302027 },
{ url = "https://files.pythonhosted.org/packages/3c/c1/6da849640cd35a41e91085723b76acc818d4b7d92b0b6e5111736ce1dd10/jiter-0.8.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:76e324da7b5da060287c54f2fabd3db5f76468006c811831f051942bf68c9d44", size = 310326 },
{ url = "https://files.pythonhosted.org/packages/06/99/a2bf660d8ccffee9ad7ed46b4f860d2108a148d0ea36043fd16f4dc37e94/jiter-0.8.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:180a8aea058f7535d1c84183c0362c710f4750bef66630c05f40c93c2b152a0f", size = 334242 },
{ url = "https://files.pythonhosted.org/packages/a7/5f/cea1c17864828731f11427b9d1ab7f24764dbd9aaf4648a7f851164d2718/jiter-0.8.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:025337859077b41548bdcbabe38698bcd93cfe10b06ff66617a48ff92c9aec60", size = 356654 },
{ url = "https://files.pythonhosted.org/packages/e9/13/62774b7e5e7f5d5043efe1d0f94ead66e6d0f894ae010adb56b3f788de71/jiter-0.8.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ecff0dc14f409599bbcafa7e470c00b80f17abc14d1405d38ab02e4b42e55b57", size = 379967 },
{ url = "https://files.pythonhosted.org/packages/ec/fb/096b34c553bb0bd3f2289d5013dcad6074948b8d55212aa13a10d44c5326/jiter-0.8.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ffd9fee7d0775ebaba131f7ca2e2d83839a62ad65e8e02fe2bd8fc975cedeb9e", size = 389252 },
{ url = "https://files.pythonhosted.org/packages/17/61/beea645c0bf398ced8b199e377b61eb999d8e46e053bb285c91c3d3eaab0/jiter-0.8.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:14601dcac4889e0a1c75ccf6a0e4baf70dbc75041e51bcf8d0e9274519df6887", size = 345490 },
{ url = "https://files.pythonhosted.org/packages/d5/df/834aa17ad5dcc3cf0118821da0a0cf1589ea7db9832589278553640366bc/jiter-0.8.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:92249669925bc1c54fcd2ec73f70f2c1d6a817928480ee1c65af5f6b81cdf12d", size = 376991 },
{ url = "https://files.pythonhosted.org/packages/67/80/87d140399d382fb4ea5b3d56e7ecaa4efdca17cd7411ff904c1517855314/jiter-0.8.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:e725edd0929fa79f8349ab4ec7f81c714df51dc4e991539a578e5018fa4a7152", size = 510822 },
{ url = "https://files.pythonhosted.org/packages/5c/37/3394bb47bac1ad2cb0465601f86828a0518d07828a650722e55268cdb7e6/jiter-0.8.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:bf55846c7b7a680eebaf9c3c48d630e1bf51bdf76c68a5f654b8524335b0ad29", size = 503730 },
{ url = "https://files.pythonhosted.org/packages/f9/e2/253fc1fa59103bb4e3aa0665d6ceb1818df1cd7bf3eb492c4dad229b1cd4/jiter-0.8.2-cp312-cp312-win32.whl", hash = "sha256:7efe4853ecd3d6110301665a5178b9856be7e2a9485f49d91aa4d737ad2ae49e", size = 203375 },
{ url = "https://files.pythonhosted.org/packages/41/69/6d4bbe66b3b3b4507e47aa1dd5d075919ad242b4b1115b3f80eecd443687/jiter-0.8.2-cp312-cp312-win_amd64.whl", hash = "sha256:83c0efd80b29695058d0fd2fa8a556490dbce9804eac3e281f373bbc99045f6c", size = 204740 },
{ url = "https://files.pythonhosted.org/packages/6c/b0/bfa1f6f2c956b948802ef5a021281978bf53b7a6ca54bb126fd88a5d014e/jiter-0.8.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:ca1f08b8e43dc3bd0594c992fb1fd2f7ce87f7bf0d44358198d6da8034afdf84", size = 301190 },
{ url = "https://files.pythonhosted.org/packages/a4/8f/396ddb4e292b5ea57e45ade5dc48229556b9044bad29a3b4b2dddeaedd52/jiter-0.8.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:5672a86d55416ccd214c778efccf3266b84f87b89063b582167d803246354be4", size = 309334 },
{ url = "https://files.pythonhosted.org/packages/7f/68/805978f2f446fa6362ba0cc2e4489b945695940656edd844e110a61c98f8/jiter-0.8.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:58dc9bc9767a1101f4e5e22db1b652161a225874d66f0e5cb8e2c7d1c438b587", size = 333918 },
{ url = "https://files.pythonhosted.org/packages/b3/99/0f71f7be667c33403fa9706e5b50583ae5106d96fab997fa7e2f38ee8347/jiter-0.8.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:37b2998606d6dadbb5ccda959a33d6a5e853252d921fec1792fc902351bb4e2c", size = 356057 },
{ url = "https://files.pythonhosted.org/packages/8d/50/a82796e421a22b699ee4d2ce527e5bcb29471a2351cbdc931819d941a167/jiter-0.8.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4ab9a87f3784eb0e098f84a32670cfe4a79cb6512fd8f42ae3d0709f06405d18", size = 379790 },
{ url = "https://files.pythonhosted.org/packages/3c/31/10fb012b00f6d83342ca9e2c9618869ab449f1aa78c8f1b2193a6b49647c/jiter-0.8.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:79aec8172b9e3c6d05fd4b219d5de1ac616bd8da934107325a6c0d0e866a21b6", size = 388285 },
{ url = "https://files.pythonhosted.org/packages/c8/81/f15ebf7de57be488aa22944bf4274962aca8092e4f7817f92ffa50d3ee46/jiter-0.8.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:711e408732d4e9a0208008e5892c2966b485c783cd2d9a681f3eb147cf36c7ef", size = 344764 },
{ url = "https://files.pythonhosted.org/packages/b3/e8/0cae550d72b48829ba653eb348cdc25f3f06f8a62363723702ec18e7be9c/jiter-0.8.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:653cf462db4e8c41995e33d865965e79641ef45369d8a11f54cd30888b7e6ff1", size = 376620 },
{ url = "https://files.pythonhosted.org/packages/b8/50/e5478ff9d82534a944c03b63bc217c5f37019d4a34d288db0f079b13c10b/jiter-0.8.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:9c63eaef32b7bebac8ebebf4dabebdbc6769a09c127294db6babee38e9f405b9", size = 510402 },
{ url = "https://files.pythonhosted.org/packages/8e/1e/3de48bbebbc8f7025bd454cedc8c62378c0e32dd483dece5f4a814a5cb55/jiter-0.8.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:eb21aaa9a200d0a80dacc7a81038d2e476ffe473ffdd9c91eb745d623561de05", size = 503018 },
{ url = "https://files.pythonhosted.org/packages/d5/cd/d5a5501d72a11fe3e5fd65c78c884e5164eefe80077680533919be22d3a3/jiter-0.8.2-cp313-cp313-win32.whl", hash = "sha256:789361ed945d8d42850f919342a8665d2dc79e7e44ca1c97cc786966a21f627a", size = 203190 },
{ url = "https://files.pythonhosted.org/packages/51/bf/e5ca301245ba951447e3ad677a02a64a8845b185de2603dabd83e1e4b9c6/jiter-0.8.2-cp313-cp313-win_amd64.whl", hash = "sha256:ab7f43235d71e03b941c1630f4b6e3055d46b6cb8728a17663eaac9d8e83a865", size = 203551 },
{ url = "https://files.pythonhosted.org/packages/2f/3c/71a491952c37b87d127790dd7a0b1ebea0514c6b6ad30085b16bbe00aee6/jiter-0.8.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:b426f72cd77da3fec300ed3bc990895e2dd6b49e3bfe6c438592a3ba660e41ca", size = 308347 },
{ url = "https://files.pythonhosted.org/packages/a0/4c/c02408042e6a7605ec063daed138e07b982fdb98467deaaf1c90950cf2c6/jiter-0.8.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b2dd880785088ff2ad21ffee205e58a8c1ddabc63612444ae41e5e4b321b39c0", size = 342875 },
{ url = "https://files.pythonhosted.org/packages/91/61/c80ef80ed8a0a21158e289ef70dac01e351d929a1c30cb0f49be60772547/jiter-0.8.2-cp313-cp313t-win_amd64.whl", hash = "sha256:3ac9f578c46f22405ff7f8b1f5848fb753cc4b8377fbec8470a7dc3997ca7566", size = 202374 },
]
[[package]]
name = "markdown-it-py"
version = "3.0.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "mdurl" },
]
sdist = { url = "https://files.pythonhosted.org/packages/38/71/3b932df36c1a044d397a1f92d1cf91ee0a503d91e470cbd670aa66b07ed0/markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb", size = 74596 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", size = 87528 },
]
[[package]]
name = "mdurl"
version = "0.1.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979 },
]
[[package]]
name = "openai"
version = "1.58.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
{ name = "distro" },
{ name = "httpx" },
{ name = "jiter" },
{ name = "pydantic" },
{ name = "sniffio" },
{ name = "tqdm" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/27/3c/b1ecce430ed56fa3ac1b0676966d3250aab9c70a408232b71e419ea62148/openai-1.58.1.tar.gz", hash = "sha256:f5a035fd01e141fc743f4b0e02c41ca49be8fab0866d3b67f5f29b4f4d3c0973", size = 343411 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/8e/5a/d22cd07f1a99b9e8b3c92ee0c1959188db4318828a3d88c9daac120bdd69/openai-1.58.1-py3-none-any.whl", hash = "sha256:e2910b1170a6b7f88ef491ac3a42c387f08bd3db533411f7ee391d166571d63c", size = 454279 },
]
[[package]]
name = "praisonaiagents"
version = "0.0.27"
source = { editable = "." }
dependencies = [
{ name = "openai" },
{ name = "pydantic" },
{ name = "rich" },
]
[package.metadata]
requires-dist = [
{ name = "openai" },
{ name = "pydantic" },
{ name = "rich" },
]
[[package]]
name = "pydantic"
version = "2.10.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "annotated-types" },
{ name = "pydantic-core" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/70/7e/fb60e6fee04d0ef8f15e4e01ff187a196fa976eb0f0ab524af4599e5754c/pydantic-2.10.4.tar.gz", hash = "sha256:82f12e9723da6de4fe2ba888b5971157b3be7ad914267dea8f05f82b28254f06", size = 762094 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f3/26/3e1bbe954fde7ee22a6e7d31582c642aad9e84ffe4b5fb61e63b87cd326f/pydantic-2.10.4-py3-none-any.whl", hash = "sha256:597e135ea68be3a37552fb524bc7d0d66dcf93d395acd93a00682f1efcb8ee3d", size = 431765 },
]
[[package]]
name = "pydantic-core"
version = "2.27.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/fc/01/f3e5ac5e7c25833db5eb555f7b7ab24cd6f8c322d3a3ad2d67a952dc0abc/pydantic_core-2.27.2.tar.gz", hash = "sha256:eb026e5a4c1fee05726072337ff51d1efb6f59090b7da90d30ea58625b1ffb39", size = 413443 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c2/89/f3450af9d09d44eea1f2c369f49e8f181d742f28220f88cc4dfaae91ea6e/pydantic_core-2.27.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:8e10c99ef58cfdf2a66fc15d66b16c4a04f62bca39db589ae8cba08bc55331bc", size = 1893421 },
{ url = "https://files.pythonhosted.org/packages/9e/e3/71fe85af2021f3f386da42d291412e5baf6ce7716bd7101ea49c810eda90/pydantic_core-2.27.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:26f32e0adf166a84d0cb63be85c562ca8a6fa8de28e5f0d92250c6b7e9e2aff7", size = 1814998 },
{ url = "https://files.pythonhosted.org/packages/a6/3c/724039e0d848fd69dbf5806894e26479577316c6f0f112bacaf67aa889ac/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8c19d1ea0673cd13cc2f872f6c9ab42acc4e4f492a7ca9d3795ce2b112dd7e15", size = 1826167 },
{ url = "https://files.pythonhosted.org/packages/2b/5b/1b29e8c1fb5f3199a9a57c1452004ff39f494bbe9bdbe9a81e18172e40d3/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:5e68c4446fe0810e959cdff46ab0a41ce2f2c86d227d96dc3847af0ba7def306", size = 1865071 },
{ url = "https://files.pythonhosted.org/packages/89/6c/3985203863d76bb7d7266e36970d7e3b6385148c18a68cc8915fd8c84d57/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d9640b0059ff4f14d1f37321b94061c6db164fbe49b334b31643e0528d100d99", size = 2036244 },
{ url = "https://files.pythonhosted.org/packages/0e/41/f15316858a246b5d723f7d7f599f79e37493b2e84bfc789e58d88c209f8a/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:40d02e7d45c9f8af700f3452f329ead92da4c5f4317ca9b896de7ce7199ea459", size = 2737470 },
{ url = "https://files.pythonhosted.org/packages/a8/7c/b860618c25678bbd6d1d99dbdfdf0510ccb50790099b963ff78a124b754f/pydantic_core-2.27.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1c1fd185014191700554795c99b347d64f2bb637966c4cfc16998a0ca700d048", size = 1992291 },
{ url = "https://files.pythonhosted.org/packages/bf/73/42c3742a391eccbeab39f15213ecda3104ae8682ba3c0c28069fbcb8c10d/pydantic_core-2.27.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d81d2068e1c1228a565af076598f9e7451712700b673de8f502f0334f281387d", size = 1994613 },
{ url = "https://files.pythonhosted.org/packages/94/7a/941e89096d1175d56f59340f3a8ebaf20762fef222c298ea96d36a6328c5/pydantic_core-2.27.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:1a4207639fb02ec2dbb76227d7c751a20b1a6b4bc52850568e52260cae64ca3b", size = 2002355 },
{ url = "https://files.pythonhosted.org/packages/6e/95/2359937a73d49e336a5a19848713555605d4d8d6940c3ec6c6c0ca4dcf25/pydantic_core-2.27.2-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:3de3ce3c9ddc8bbd88f6e0e304dea0e66d843ec9de1b0042b0911c1663ffd474", size = 2126661 },
{ url = "https://files.pythonhosted.org/packages/2b/4c/ca02b7bdb6012a1adef21a50625b14f43ed4d11f1fc237f9d7490aa5078c/pydantic_core-2.27.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:30c5f68ded0c36466acede341551106821043e9afaad516adfb6e8fa80a4e6a6", size = 2153261 },
{ url = "https://files.pythonhosted.org/packages/72/9d/a241db83f973049a1092a079272ffe2e3e82e98561ef6214ab53fe53b1c7/pydantic_core-2.27.2-cp311-cp311-win32.whl", hash = "sha256:c70c26d2c99f78b125a3459f8afe1aed4d9687c24fd677c6a4436bc042e50d6c", size = 1812361 },
{ url = "https://files.pythonhosted.org/packages/e8/ef/013f07248041b74abd48a385e2110aa3a9bbfef0fbd97d4e6d07d2f5b89a/pydantic_core-2.27.2-cp311-cp311-win_amd64.whl", hash = "sha256:08e125dbdc505fa69ca7d9c499639ab6407cfa909214d500897d02afb816e7cc", size = 1982484 },
{ url = "https://files.pythonhosted.org/packages/10/1c/16b3a3e3398fd29dca77cea0a1d998d6bde3902fa2706985191e2313cc76/pydantic_core-2.27.2-cp311-cp311-win_arm64.whl", hash = "sha256:26f0d68d4b235a2bae0c3fc585c585b4ecc51382db0e3ba402a22cbc440915e4", size = 1867102 },
{ url = "https://files.pythonhosted.org/packages/d6/74/51c8a5482ca447871c93e142d9d4a92ead74de6c8dc5e66733e22c9bba89/pydantic_core-2.27.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:9e0c8cfefa0ef83b4da9588448b6d8d2a2bf1a53c3f1ae5fca39eb3061e2f0b0", size = 1893127 },
{ url = "https://files.pythonhosted.org/packages/d3/f3/c97e80721735868313c58b89d2de85fa80fe8dfeeed84dc51598b92a135e/pydantic_core-2.27.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:83097677b8e3bd7eaa6775720ec8e0405f1575015a463285a92bfdfe254529ef", size = 1811340 },
{ url = "https://files.pythonhosted.org/packages/9e/91/840ec1375e686dbae1bd80a9e46c26a1e0083e1186abc610efa3d9a36180/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:172fce187655fece0c90d90a678424b013f8fbb0ca8b036ac266749c09438cb7", size = 1822900 },
{ url = "https://files.pythonhosted.org/packages/f6/31/4240bc96025035500c18adc149aa6ffdf1a0062a4b525c932065ceb4d868/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:519f29f5213271eeeeb3093f662ba2fd512b91c5f188f3bb7b27bc5973816934", size = 1869177 },
{ url = "https://files.pythonhosted.org/packages/fa/20/02fbaadb7808be578317015c462655c317a77a7c8f0ef274bc016a784c54/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:05e3a55d124407fffba0dd6b0c0cd056d10e983ceb4e5dbd10dda135c31071d6", size = 2038046 },
{ url = "https://files.pythonhosted.org/packages/06/86/7f306b904e6c9eccf0668248b3f272090e49c275bc488a7b88b0823444a4/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9c3ed807c7b91de05e63930188f19e921d1fe90de6b4f5cd43ee7fcc3525cb8c", size = 2685386 },
{ url = "https://files.pythonhosted.org/packages/8d/f0/49129b27c43396581a635d8710dae54a791b17dfc50c70164866bbf865e3/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6fb4aadc0b9a0c063206846d603b92030eb6f03069151a625667f982887153e2", size = 1997060 },
{ url = "https://files.pythonhosted.org/packages/0d/0f/943b4af7cd416c477fd40b187036c4f89b416a33d3cc0ab7b82708a667aa/pydantic_core-2.27.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:28ccb213807e037460326424ceb8b5245acb88f32f3d2777427476e1b32c48c4", size = 2004870 },
{ url = "https://files.pythonhosted.org/packages/35/40/aea70b5b1a63911c53a4c8117c0a828d6790483f858041f47bab0b779f44/pydantic_core-2.27.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:de3cd1899e2c279b140adde9357c4495ed9d47131b4a4eaff9052f23398076b3", size = 1999822 },
{ url = "https://files.pythonhosted.org/packages/f2/b3/807b94fd337d58effc5498fd1a7a4d9d59af4133e83e32ae39a96fddec9d/pydantic_core-2.27.2-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:220f892729375e2d736b97d0e51466252ad84c51857d4d15f5e9692f9ef12be4", size = 2130364 },
{ url = "https://files.pythonhosted.org/packages/fc/df/791c827cd4ee6efd59248dca9369fb35e80a9484462c33c6649a8d02b565/pydantic_core-2.27.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:a0fcd29cd6b4e74fe8ddd2c90330fd8edf2e30cb52acda47f06dd615ae72da57", size = 2158303 },
{ url = "https://files.pythonhosted.org/packages/9b/67/4e197c300976af185b7cef4c02203e175fb127e414125916bf1128b639a9/pydantic_core-2.27.2-cp312-cp312-win32.whl", hash = "sha256:1e2cb691ed9834cd6a8be61228471d0a503731abfb42f82458ff27be7b2186fc", size = 1834064 },
{ url = "https://files.pythonhosted.org/packages/1f/ea/cd7209a889163b8dcca139fe32b9687dd05249161a3edda62860430457a5/pydantic_core-2.27.2-cp312-cp312-win_amd64.whl", hash = "sha256:cc3f1a99a4f4f9dd1de4fe0312c114e740b5ddead65bb4102884b384c15d8bc9", size = 1989046 },
{ url = "https://files.pythonhosted.org/packages/bc/49/c54baab2f4658c26ac633d798dab66b4c3a9bbf47cff5284e9c182f4137a/pydantic_core-2.27.2-cp312-cp312-win_arm64.whl", hash = "sha256:3911ac9284cd8a1792d3cb26a2da18f3ca26c6908cc434a18f730dc0db7bfa3b", size = 1885092 },
{ url = "https://files.pythonhosted.org/packages/41/b1/9bc383f48f8002f99104e3acff6cba1231b29ef76cfa45d1506a5cad1f84/pydantic_core-2.27.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:7d14bd329640e63852364c306f4d23eb744e0f8193148d4044dd3dacdaacbd8b", size = 1892709 },
{ url = "https://files.pythonhosted.org/packages/10/6c/e62b8657b834f3eb2961b49ec8e301eb99946245e70bf42c8817350cbefc/pydantic_core-2.27.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:82f91663004eb8ed30ff478d77c4d1179b3563df6cdb15c0817cd1cdaf34d154", size = 1811273 },
{ url = "https://files.pythonhosted.org/packages/ba/15/52cfe49c8c986e081b863b102d6b859d9defc63446b642ccbbb3742bf371/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71b24c7d61131bb83df10cc7e687433609963a944ccf45190cfc21e0887b08c9", size = 1823027 },
{ url = "https://files.pythonhosted.org/packages/b1/1c/b6f402cfc18ec0024120602bdbcebc7bdd5b856528c013bd4d13865ca473/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fa8e459d4954f608fa26116118bb67f56b93b209c39b008277ace29937453dc9", size = 1868888 },
{ url = "https://files.pythonhosted.org/packages/bd/7b/8cb75b66ac37bc2975a3b7de99f3c6f355fcc4d89820b61dffa8f1e81677/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ce8918cbebc8da707ba805b7fd0b382816858728ae7fe19a942080c24e5b7cd1", size = 2037738 },
{ url = "https://files.pythonhosted.org/packages/c8/f1/786d8fe78970a06f61df22cba58e365ce304bf9b9f46cc71c8c424e0c334/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:eda3f5c2a021bbc5d976107bb302e0131351c2ba54343f8a496dc8783d3d3a6a", size = 2685138 },
{ url = "https://files.pythonhosted.org/packages/a6/74/d12b2cd841d8724dc8ffb13fc5cef86566a53ed358103150209ecd5d1999/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bd8086fa684c4775c27f03f062cbb9eaa6e17f064307e86b21b9e0abc9c0f02e", size = 1997025 },
{ url = "https://files.pythonhosted.org/packages/a0/6e/940bcd631bc4d9a06c9539b51f070b66e8f370ed0933f392db6ff350d873/pydantic_core-2.27.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8d9b3388db186ba0c099a6d20f0604a44eabdeef1777ddd94786cdae158729e4", size = 2004633 },
{ url = "https://files.pythonhosted.org/packages/50/cc/a46b34f1708d82498c227d5d80ce615b2dd502ddcfd8376fc14a36655af1/pydantic_core-2.27.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:7a66efda2387de898c8f38c0cf7f14fca0b51a8ef0b24bfea5849f1b3c95af27", size = 1999404 },
{ url = "https://files.pythonhosted.org/packages/ca/2d/c365cfa930ed23bc58c41463bae347d1005537dc8db79e998af8ba28d35e/pydantic_core-2.27.2-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:18a101c168e4e092ab40dbc2503bdc0f62010e95d292b27827871dc85450d7ee", size = 2130130 },
{ url = "https://files.pythonhosted.org/packages/f4/d7/eb64d015c350b7cdb371145b54d96c919d4db516817f31cd1c650cae3b21/pydantic_core-2.27.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:ba5dd002f88b78a4215ed2f8ddbdf85e8513382820ba15ad5ad8955ce0ca19a1", size = 2157946 },
{ url = "https://files.pythonhosted.org/packages/a4/99/bddde3ddde76c03b65dfd5a66ab436c4e58ffc42927d4ff1198ffbf96f5f/pydantic_core-2.27.2-cp313-cp313-win32.whl", hash = "sha256:1ebaf1d0481914d004a573394f4be3a7616334be70261007e47c2a6fe7e50130", size = 1834387 },
{ url = "https://files.pythonhosted.org/packages/71/47/82b5e846e01b26ac6f1893d3c5f9f3a2eb6ba79be26eef0b759b4fe72946/pydantic_core-2.27.2-cp313-cp313-win_amd64.whl", hash = "sha256:953101387ecf2f5652883208769a79e48db18c6df442568a0b5ccd8c2723abee", size = 1990453 },
{ url = "https://files.pythonhosted.org/packages/51/b2/b2b50d5ecf21acf870190ae5d093602d95f66c9c31f9d5de6062eb329ad1/pydantic_core-2.27.2-cp313-cp313-win_arm64.whl", hash = "sha256:ac4dbfd1691affb8f48c2c13241a2e3b60ff23247cbcf981759c768b6633cf8b", size = 1885186 },
]
[[package]]
name = "pygments"
version = "2.18.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/8e/62/8336eff65bcbc8e4cb5d05b55faf041285951b6e80f33e2bff2024788f31/pygments-2.18.0.tar.gz", hash = "sha256:786ff802f32e91311bff3889f6e9a86e81505fe99f2735bb6d60ae0c5004f199", size = 4891905 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f7/3f/01c8b82017c199075f8f788d0d906b9ffbbc5a47dc9918a945e13d5a2bda/pygments-2.18.0-py3-none-any.whl", hash = "sha256:b8e6aca0523f3ab76fee51799c488e38782ac06eafcf95e7ba832985c8e7b13a", size = 1205513 },
]
[[package]]
name = "rich"
version = "13.9.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "markdown-it-py" },
{ name = "pygments" },
]
sdist = { url = "https://files.pythonhosted.org/packages/ab/3a/0316b28d0761c6734d6bc14e770d85506c986c85ffb239e688eeaab2c2bc/rich-13.9.4.tar.gz", hash = "sha256:439594978a49a09530cff7ebc4b5c7103ef57baf48d5ea3184f21d9a2befa098", size = 223149 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/19/71/39c7c0d87f8d4e6c020a393182060eaefeeae6c01dab6a84ec346f2567df/rich-13.9.4-py3-none-any.whl", hash = "sha256:6049d5e6ec054bf2779ab3358186963bac2ea89175919d699e378b99738c2a90", size = 242424 },
]
[[package]]
name = "sniffio"
version = "1.3.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235 },
]
[[package]]
name = "tqdm"
version = "4.67.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "colorama", marker = "sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a8/4b/29b4ef32e036bb34e4ab51796dd745cdba7ed47ad142a9f4a1eb8e0c744d/tqdm-4.67.1.tar.gz", hash = "sha256:f8aef9c52c08c13a65f30ea34f4e5aac3fd1a34959879d7e59e63027286627f2", size = 169737 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d0/30/dc54f88dd4a2b5dc8a0279bdd7270e735851848b762aeb1c1184ed1f6b14/tqdm-4.67.1-py3-none-any.whl", hash = "sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2", size = 78540 },
]
[[package]]
name = "typing-extensions"
version = "4.12.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/df/db/f35a00659bc03fec321ba8bce9420de607a1d37f8342eee1863174c69557/typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8", size = 85321 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/26/9f/ad63fc0248c5379346306f8668cda6e2e2e9c95e01216d2b8ffd9ff037d0/typing_extensions-4.12.2-py3-none-any.whl", hash = "sha256:04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d", size = 37438 },
]
+1 -1
View File
@@ -1,6 +1,6 @@
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.36 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.36 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;)
@@ -0,0 +1,187 @@
---
title: "AutoAgents Module"
description: "Documentation for the praisonaiagents.agents.autoagents module"
icon: "robot"
---
# Module praisonaiagents.agents.autoagents
The AutoAgents module provides automatic creation and management of AI agents and tasks based on high-level instructions.
## Classes
### AutoAgents
The main class for automatically creating and managing AI agents and tasks.
#### Parameters
- `instructions: str` - High-level task description for the agents
- `tools: Optional[List[Any]] = None` - List of tools available to the agents
- `verbose: bool = False` - Enable detailed logging
- `process: str = "sequential"` - Process type (sequential or hierarchical)
- `manager_llm: Optional[str] = None` - Language model for manager agent
- `max_retries: int = 5` - Maximum retry attempts
- `completion_checker: Optional[Any] = None` - Custom completion checker
- `allow_code_execution: bool = False` - Allow code execution
- `memory: bool = True` - Enable agent memory
- `markdown: bool = True` - Enable markdown formatting
- `self_reflect: bool = False` - Enable agent self-reflection
- `max_reflect: int = 3` - Maximum reflection iterations
- `min_reflect: int = 1` - Minimum reflection iterations
- `llm: Optional[str] = None` - Language model for agents
- `function_calling_llm: Optional[str] = None` - Language model for tool calling
- `respect_context_window: bool = True` - Respect model context window
- `code_execution_mode: str = "safe"` - Code execution mode (safe/unsafe)
- `embedder_config: Optional[Dict[str, Any]] = None` - Embedder configuration
- `knowledge_sources: Optional[List[Any]] = None` - Knowledge sources
- `use_system_prompt: bool = True` - Use system prompts
- `cache: bool = True` - Enable caching
- `allow_delegation: bool = False` - Allow task delegation
- `step_callback: Optional[Any] = None` - Callback for each step
- `system_template: Optional[str] = None` - Custom system template
- `prompt_template: Optional[str] = None` - Custom prompt template
- `response_template: Optional[str] = None` - Custom response template
- `max_rpm: Optional[int] = None` - Maximum requests per minute
- `max_execution_time: Optional[int] = None` - Maximum execution time
- `max_iter: int = 20` - Maximum iterations
- `reflect_llm: Optional[str] = None` - Language model for reflection
- `max_agents: int = 3` - Maximum number of agents to create
#### Methods
##### start()
Start the agents synchronously.
```python
def start(self):
"""
Creates tasks based on the instructions, then starts execution.
Returns the task status and results dictionary.
"""
return super().start()
```
##### astart()
Start the agents asynchronously.
```python
async def astart(self):
"""
Async version of start() method.
Creates tasks based on the instructions, then starts execution.
Returns the task status and results dictionary.
"""
return await super().astart()
```
#### Internal Methods
##### _generate_config()
Generate the configuration for agents and tasks.
```python
def _generate_config(self) -> AutoAgentsConfig:
"""
Generate the configuration for agents and tasks based on instructions.
Returns AutoAgentsConfig object containing agent and task configurations.
"""
```
##### _create_agents_and_tasks()
Create agents and tasks from configuration.
```python
def _create_agents_and_tasks(self, config: AutoAgentsConfig) -> tuple[List[Agent], List[Task]]:
"""
Create agents and tasks based on the generated configuration.
Returns tuple of (agents, tasks).
"""
```
##### _assign_tools_to_agent()
Assign appropriate tools to an agent.
```python
def _assign_tools_to_agent(self, agent_config: AgentConfig) -> List[Any]:
"""
Assign tools to an agent based on its role and tasks.
Returns list of assigned tools.
"""
```
## Pydantic Models
### TaskConfig
Configuration for a task.
#### Attributes
- `name: str` - Task name
- `description: str` - Task description
- `expected_output: str` - Expected output description
- `tools: List[str]` - Required tools for the task
### AgentConfig
Configuration for an agent.
#### Attributes
- `name: str` - Agent name
- `role: str` - Agent role
- `goal: str` - Agent goal
- `backstory: str` - Agent backstory
- `tools: List[str]` - Required tools
- `tasks: List[TaskConfig]` - Tasks assigned to the agent
### AutoAgentsConfig
Overall configuration for AutoAgents.
#### Attributes
- `main_instruction: str` - Main instruction for the agents
- `process_type: str` - Process type (sequential/hierarchical)
- `agents: List[AgentConfig]` - List of agent configurations
## Example Usage
### Basic Usage
```python
from praisonaiagents import AutoAgents
from praisonaiagents.tools import SerperDevTool
agents = AutoAgents(
instructions="Research recent AI developments",
tools=[SerperDevTool()],
verbose=True
)
result = agents.start()
```
### Async Usage
```python
async def main():
agents = AutoAgents(
instructions="Research recent AI developments",
tools=[SerperDevTool()],
process="hierarchical"
)
result = await agents.astart()
import asyncio
asyncio.run(main())
```
### Advanced Configuration
```python
agents = AutoAgents(
instructions="Complex research task",
tools=[SerperDevTool()],
max_agents=5,
process="hierarchical",
manager_llm="gpt-4o",
memory=True,
allow_delegation=True,
max_execution_time=600,
self_reflect=True
)
```
<Note>
For optimal results, provide clear instructions and appropriate tools for your use case.
</Note>
-69
View File
@@ -1,69 +0,0 @@
---
title: Installation
description: Set up PraisonAI in your development environment
icon: download
---
<Note>
**Requirements**
- Python 3.10 or higher
- pip package manager
- Virtual environment (recommended)
</Note>
# Installing PraisonAI
Follow these steps to set up PraisonAI in your development environment.
<Steps>
<Step title="Create Virtual Environment (Optional)">
First, create and activate a virtual environment:
<CodeGroup>
```bash Mac/Linux
python -m venv praisonai-env
source praisonai-env/bin/activate
```
```bash Windows
python -m venv praisonai-env
.\praisonai-env\Scripts\activate
```
</CodeGroup>
</Step>
<Step title="Install PraisonAI">
Install the core package and tools:
```bash Terminal
pip install praisonaiagents
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
You can also use other LLM providers like Anthropic, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
</Steps>
## Next Steps
<CardGroup cols={2}>
<Card
title="Quick Start Guide"
icon="bolt"
href="/code/quickstart"
>
Build your first AI agent
</Card>
<Card
title="API Reference"
icon="code"
href="/api/praisonaiagents/index"
>
Explore the API documentation
</Card>
</CardGroup>
-188
View File
@@ -1,188 +0,0 @@
---
title: "Introduction"
description: "Welcome to PraisonAI - The Next Generation AI Agent Framework"
icon: "book-open"
---
<Note>
PraisonAI is a powerful framework for building and deploying AI agents that can understand, reason, and execute complex tasks autonomously.
</Note>
# What is PraisonAI?
```mermaid
graph LR
%% Define the main flow
Start([▶ Start]) --> Agent1
Agent1 --> Process[⚙ Process]
Process --> Agent2
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[" "]
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[" "]
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
```
## Core Components
<CardGroup cols={2}>
<Card title="Agents" icon="user-robot">
Autonomous AI entities that can understand context and execute tasks
</Card>
<Card title="Tasks" icon="list-check">
Units of work that agents can execute independently or collaboratively
</Card>
<Card title="Process" icon="diagram-project">
Workflow management for coordinating agent activities
</Card>
<Card title="Tools" icon="toolbox">
Extensible capabilities that agents can leverage
</Card>
</CardGroup>
## Key Features
<Steps>
<Step title="Autonomous Agents">
Create intelligent agents that can:
- Understand natural language instructions
- Make decisions based on context
- Execute complex tasks autonomously
</Step>
<Step title="Flexible Architecture">
Build with:
- Modular components
- Extensible tools
- Customizable workflows
</Step>
<Step title="Advanced Capabilities">
Leverage:
- Multi-agent collaboration
- Memory and context management
- Tool integration
</Step>
</Steps>
## Use Cases
<CardGroup cols={2}>
<Card title="Customer Service" icon="headset">
Build intelligent support agents that can handle customer inquiries and resolve issues autonomously.
</Card>
<Card title="Data Analysis" icon="chart-line">
Create agents that can process, analyze, and derive insights from complex datasets.
</Card>
<Card title="Content Creation" icon="pen-nib">
Deploy agents that can generate, edit, and optimize content across various formats.
</Card>
<Card title="Process Automation" icon="gears">
Automate complex workflows with intelligent agents that can coordinate and execute tasks.
</Card>
</CardGroup>
## Getting Started
<Warning>
Before proceeding, ensure you have Python 3.9+ installed on your system.
</Warning>
### Quick Setup
<CodeGroup>
```bash pip
pip install praisonai
```
</CodeGroup>
### Basic Example
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# 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"
)
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
# Run the agents
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
verbose=False
)
result = agents.start()
```
## Next Steps
<CardGroup cols={2}>
<Card
title="Installation"
icon="download"
href="/code/installation"
>
Complete installation guide and setup instructions
</Card>
<Card
title="Quick Start"
icon="play"
href="/code/quickstart"
>
Build your first AI agent in minutes
</Card>
</CardGroup>
<Tip>
Join our community on [Discord](https://www.youtube.com/redirect?event=channel_description&redir_token=QUFFLUhqbUpiZE00YlF1MjB1LVNIeTFxTnV6MWRRc18wZ3xBQ3Jtc0ttQVZ0aFJ4RXRDanlBQU1Vd3lHU3BBcml3bzhoek1pTmlkZkFkWjlNVDBpRkxZd1dTOWhPc20xbHJOb1NibmNYeTEydklJT0pZOVJFQW93MmJOQXU0WkJNVzNsd29SZ3FBNFVwMTFGNThNSHBWVUhjSQ&q=https%3A%2F%2Fdiscord.gg%2FnNZu5gGT59) to connect with other developers and get help!
</Tip>
-195
View File
@@ -1,195 +0,0 @@
---
title: Quick Start
description: Build your first AI agent with PraisonAI
icon: bolt
---
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
You can also use other LLM providers like Anthropic, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Create Agent">
Create `app.py`:
## Code Example
<CodeGroup>
```python Basic
from praisonaiagents import Agent, Task, PraisonAIAgents
# 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"
)
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
# Run the agents
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
verbose=False
)
result = agents.start()
```
```python Advanced
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()
```
</CodeGroup>
</Step>
<Step title="Run the Program">
Execute your script:
```bash Terminal
python app.py
```
You should see:
- Agent initialization
- Agents progress
- Final results
- Generated report
</Step>
</Steps>
## Advanced Usage
### Creating Custom Tool
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from duckduckgo_search import DDGS
from typing import List, Dict
# 1. Tool
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search
"""
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
# 2. Agent
data_agent = Agent(
name="DataCollector",
role="Search Specialist",
goal="Perform internet searches to collect relevant information.",
backstory="Expert in finding and organising internet data.",
tools=[internet_search_tool],
self_reflect=False
)
# 3. Tasks
collect_task = Task(
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
expected_output="List of search results with titles, URLs, and snippets.",
agent=data_agent,
name="collect_data",
)
# 4. Start Agents
agents = PraisonAIAgents(
agents=[data_agent],
tasks=[collect_task],
process="sequential"
)
agents.start()
```
## Next Steps
<CardGroup cols={2}>
<Card
title="Core Concepts"
icon="book"
href="/concepts/agents"
>
Learn about agents, tasks, and processes
</Card>
<Card
title="API Reference"
icon="code"
href="/api/praisonaiagents/index"
>
Explore detailed API documentation
</Card>
</CardGroup>
+186 -53
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
@@ -105,43 +91,190 @@ graph LR
```
</CodeGroup>
## Agent Types
<Steps>
<Step title="Basic Agent">
- Single-purpose focus
- Direct user interaction
- Limited tool set
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents
```
</Step>
<Step title="Specialized Agent">
- Domain expertise
- Advanced capabilities
- Custom tools
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Collaborative Agent">
- Team interaction
- Task delegation
- Shared context
<Step title="Create Agent">
Create `app.py`:
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent
agent = Agent(instructions="Your are a helpful AI assistant")
agent.start("Write a movie script about a robot in Mars")
```
```python Multi Agents
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()
```
</CodeGroup>
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
python app.py
```
You should see:
- Agent initialization
- Agents progress
- Final results
- Generated report
</Step>
</Steps>
## Agent Types
<CardGroup cols={3}>
<Card title="Basic Agent" icon="user" iconType="solid">
<AccordionGroup>
<Accordion title="Overview">
Perfect for straightforward tasks and direct interactions
</Accordion>
<Accordion title="Features">
- Single-purpose focus
- Direct user interaction
- Limited tool set
- Ideal for simple tasks
</Accordion>
</AccordionGroup>
</Card>
<Card title="Specialized Agent" icon="user-gear" iconType="solid">
<AccordionGroup>
<Accordion title="Overview">
Experts in specific domains with advanced capabilities
</Accordion>
<Accordion title="Features">
- Domain expertise
- Advanced capabilities
- Custom tools
- Deep knowledge base
</Accordion>
</AccordionGroup>
</Card>
<Card title="Collaborative Agent" icon="users" iconType="solid">
<AccordionGroup>
<Accordion title="Overview">
Designed for team-based operations and complex workflows
</Accordion>
<Accordion title="Features">
- Team interaction
- Task delegation
- Shared context
- Coordinated actions
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
## Best Practices
<Warning>
Always implement proper error handling and resource management in your agent configurations.
</Warning>
<Note>
Always implement proper error handling and resource management in your agent configurations.
</Note>
### Agent Design
1. Clear role definition
2. Specific, measurable goals
3. Relevant tool selection
4. Appropriate memory configuration
<CardGroup cols={2}>
<Card title="Agent Design" icon="compass-drafting" iconType="solid">
<Steps>
<Step title="Role Definition">
Define clear, specific roles for each agent
</Step>
<Step title="Goal Setting">
Set specific, measurable goals
</Step>
<Step title="Tool Selection">
Choose relevant tools for the task
</Step>
<Step title="Memory Setup">
Configure appropriate memory settings
</Step>
</Steps>
</Card>
### Agent Interaction
1. Clear communication protocols
2. Defined delegation rules
3. Error handling mechanisms
4. Resource management
<Card title="Agent Interaction" icon="network-wired" iconType="solid">
<Steps>
<Step title="Communication">
Establish clear communication protocols
</Step>
<Step title="Delegation">
Define explicit delegation rules
</Step>
<Step title="Error Handling">
Implement robust error handling
</Step>
<Step title="Resource Management">
Set up efficient resource allocation
</Step>
</Steps>
</Card>
</CardGroup>
## Async Capabilities
<CardGroup cols={1}>
<Card title="Key Features" icon="bolt" iconType="solid">
<Tabs>
<Tab title="Async Support">
```python
async def main():
agent = Agent(name="AsyncAgent")
result = await agent.aprocess_task()
```
- Full async/await support
- Non-blocking operations
- Enhanced performance
</Tab>
<Tab title="Parallel Execution">
```python
async def parallel_tasks():
tasks = [agent1.task(), agent2.task()]
results = await asyncio.gather(*tasks)
```
- Parallel task execution
- Efficient resource usage
- Improved throughput
</Tab>
<Tab title="Integration">
```python
@agent.async_tool
async def custom_tool():
async with aiohttp.ClientSession() as session:
# Async operations
pass
```
- Async tool integration
- Callback support
- Mixed sync/async operations
</Tab>
</Tabs>
</Card>
</CardGroup>
## Advanced Features
+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
+472
View File
@@ -0,0 +1,472 @@
---
title: "AI Agents with Memory"
sidebarTitle: "Memory"
description: "Learn how to create AI agents with memory capabilities for maintaining context and information across tasks."
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>
<Tab title="Code">
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install "praisonaiagents[memory]" duckduckgo_search
```
duckduckgo_search is a tool that allows agents to search the web.
It is required for the multiple agents example shown below.
</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:
<CodeGroup>
```python Single Agent
from praisonaiagents.agents.agents import Agent, Task, PraisonAIAgents
# Create blog writer agent
blog_agent = Agent(
role="Blog Writer",
goal="Write a blog post about AI",
backstory="Expert at writing blog posts",
llm="gpt-4o-mini"
)
# Create blog writing task
blog_task = Task(
description="Write a blog post about AI trends",
expected_output="Well-written blog post about AI trends",
agent=blog_agent
)
# Create and start the agents with memory enabled
agents = PraisonAIAgents(
agents=[blog_agent],
tasks=[blog_task],
memory=True
)
# Start execution
result = agents.start()
print(result)
```
```python Multiple Agents
from praisonaiagents.agents.agents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import duckduckgo
# Create research agent with memory
research_agent = Agent(
role="Research Analyst",
goal="Research and document key information about topics",
backstory="Expert at analyzing and storing information in memory",
llm="gpt-4o-mini",
tools=[duckduckgo]
)
# Create blog writer agent
blog_agent = Agent(
role="Blog Writer",
goal="Write a blog post about the research",
backstory="Expert at writing blog posts",
llm="gpt-4o-mini"
)
# Create research task
research_task = Task(
description="Research and document key information about AI trends",
expected_output="Detailed research findings about AI trends",
agent=research_agent
)
# Create blog writing task
blog_task = Task(
description="Write a blog post about the research findings",
expected_output="Well-written blog post based on research",
agent=blog_agent
)
# Create and start the agents with advanced memory configuration
agents = PraisonAIAgents(
agents=[research_agent, blog_agent],
tasks=[research_task, blog_task],
memory=True
)
# Start execution
result = agents.start()
print(result)
```
</CodeGroup>
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python app.py
```
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install Package">
Install the PraisonAI package:
```bash
pip install praisonai
```
</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 `agents.yaml` with the basic setup:
```yaml
framework: praisonai
process: sequential
memory: true
roles:
researcher:
backstory: Expert at analyzing and storing information in memory.
goal: Research and document key information about topics
role: Research Analyst
llm: gpt-4o-mini
tools:
- duckduckgo
tasks:
research_task:
description: Research and document key information about topics.
expected_output: Detailed research findings.
writer:
backstory: Expert at writing blog posts.
goal: Write a blog post about the research
role: Blog Writer
llm: gpt-4o-mini
tasks:
blog_task:
description: Write a blog post about the research.
expected_output: Well-written blog post based on research.
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
praisonai agents.yaml
```
</Step>
</Steps>
</Tab>
</Tabs>
<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 Memory
<Card title="What is Agent Memory?" icon="question">
Memory in AI agents enables them to:
- Maintain context across multiple tasks
- Remember previous interactions and findings
- Build upon past knowledge
- Share information between agents
- Create more coherent and contextual responses
</Card>
## Features
<CardGroup cols={2}>
<Card title="Context Retention" icon="brain">
Maintain information across multiple interactions.
</Card>
<Card title="Information Sharing" icon="share-nodes">
Share knowledge between multiple agents.
</Card>
<Card title="Long-term Storage" icon="database">
Store and retrieve information over extended periods.
</Card>
<Card title="Memory Types" icon="layer-group">
Support for different memory types (short-term, long-term).
</Card>
</CardGroup>
## Multi-Agent Memory
<Tabs>
<Tab title="Code">
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import duckduckgo
# Create first agent for research
researcher = Agent(
role="Research Analyst",
goal="Research and analyze market trends",
backstory="Expert in market research and data analysis",
tools=[duckduckgo],
verbose=True
)
# Create second agent for report writing
writer = Agent(
role="Report Writer",
goal="Create comprehensive market reports",
backstory="Expert in technical writing and report creation",
verbose=True
)
# Create research task
research_task = Task(
description="Research current market trends",
expected_output="Detailed market analysis",
agent=researcher
)
# Create writing task
report_task = Task(
description="Create a market report based on research",
expected_output="Comprehensive market report",
agent=writer
)
# Create and start the agents with memory
agents = PraisonAIAgents(
agents=[researcher, writer],
tasks=[research_task, report_task],
memory=True,
process="sequential"
)
# Start execution
result = agents.start()
```
</Tab>
<Tab title="No Code">
```yaml
framework: praisonai
process: sequential
memory: true
roles:
researcher:
backstory: Expert in market research and data analysis.
goal: Research and analyze market trends
role: Research Analyst
tools:
- duckduckgo
tasks:
research_task:
description: Research current market trends.
expected_output: Detailed market analysis.
writer:
backstory: Expert in technical writing and report creation.
goal: Create comprehensive market reports
role: Report Writer
tasks:
report_task:
description: Create a market report based on research.
expected_output: Comprehensive market report.
```
</Tab>
</Tabs>
### Configuration Options
```python
# Create an agent with memory configuration
agent = Agent(
role="Research Analyst",
goal="Research and retain information",
backstory="Expert in research and analysis",
tools=[duckduckgo],
verbose=True, # Enable detailed logging
llm="gpt-4o" # Language model to use
)
# Create agents with memory options
agents = PraisonAIAgents(
agents=[agent],
tasks=[task],
memory=True, # Enable memory
memory_config={
"provider": "rag", # Use RAG for semantic search
"use_embedding": True, # Enable embeddings for better search
"short_db": ".praison/short_term.db", # Path for short-term memory
"long_db": ".praison/long_term.db", # Path for long-term memory
"rag_db_path": ".praison/chroma_db" # Path for vector database
}
)
```
## Troubleshooting
<CardGroup cols={2}>
<Card title="Memory Issues" icon="triangle-exclamation">
If memory isn't working as expected:
- Check memory configuration
- Enable verbose mode for debugging
- Verify memory provider settings
</Card>
<Card title="Context Flow" icon="code">
If context isn't being maintained:
- Review task dependencies
- Check memory configuration
- Verify agent communication
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="AutoAgents" icon="robot" href="../features/autoagents">
Learn about automatically created and managed AI agents
</Card>
<Card title="Mini Agents" icon="microchip" href="../features/mini">
Explore lightweight, focused AI agents
</Card>
</CardGroup>
<Note>
For optimal results, configure memory settings based on your specific use case requirements and expected interaction patterns.
</Note>
### Memory Configuration Options
The memory system in PraisonAI supports various configuration options to customize how agents store and retrieve information:
```python
memory_config = {
# Memory Provider
"provider": "rag", # Options: "rag", "mem0", "none"
"use_embedding": True, # Enable semantic search with embeddings
# Storage Paths
"short_db": ".praison/short_term.db", # Short-term memory SQLite DB
"long_db": ".praison/long_term.db", # Long-term memory SQLite DB
"rag_db_path": ".praison/chroma_db", # Vector database path
# Memory Settings
"ttl": 3600, # Time to live for memory items (in seconds)
# Optional Mem0 Config (if using mem0 provider)
"config": {
"api_key": "...", # Mem0 API key
"org_id": "...", # Organization ID
"project_id": "..." # Project ID
}
}
# Create agents with memory configuration
agents = PraisonAIAgents(
agents=[agent],
tasks=[task],
memory=True,
memory_config=memory_config
)
```
### Memory Types
PraisonAI's memory system includes several types of memory:
<CardGroup cols={2}>
<Card title="Short-term Memory" icon="bolt">
- Temporary storage for current context
- Automatically cleared between sessions
- Fast access for immediate task context
</Card>
<Card title="Long-term Memory" icon="database">
- Persistent storage for important information
- Semantic search capabilities with RAG
- Quality-based storage decisions
</Card>
</CardGroup>
### Memory Quality Control
PraisonAI includes built-in quality control for memory storage:
```python
# Example of storing with quality metrics
agents.memory.store_long_term(
text="Important information to remember",
metadata={
"task_id": "task_123",
"agent": "research_agent"
},
completeness=0.9, # How complete is the information
relevance=0.85, # How relevant to the task
clarity=0.95, # How clear and well-structured
accuracy=0.9, # How accurate is the information
weights={ # Custom weights for quality score
"completeness": 0.3,
"relevance": 0.3,
"clarity": 0.2,
"accuracy": 0.2
}
)
# Search with quality filter
results = agents.memory.search_long_term(
query="search query",
min_quality=0.8, # Only return high-quality matches
limit=5 # Maximum number of results
)
+403 -170
View File
@@ -10,96 +10,287 @@ Process types in PraisonAI define how tasks are executed and how agents collabor
## Process Types Overview
Three types of processes are implemented in PraisonAI:
<CardGroup cols={3}>
<Card
title="Sequential Process"
icon="arrow-right"
href="/sequential-process"
>
Linear task execution in a predefined order
</Card>
<Card
title="Hierarchical Process"
icon="sitemap"
href="/hierarchical-process"
>
Manager-coordinated task execution with dynamic assignment
</Card>
<Card
title="Workflow Process"
icon="diagram-project"
href="/workflow-process"
>
Complex task flows with conditional execution and state management
</Card>
</CardGroup>
<Frame>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
<div className="flex items-center mb-4">
<div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
<svg className="w-6 h-6 text-blue-600 dark:text-blue-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16m-7 6h7" />
</svg>
</div>
<h3 className="ml-3 text-lg font-semibold">Sequential Process</h3>
</div>
<p>Linear task execution in a predefined order</p>
</div>
## Sequential Process
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
<div className="flex items-center mb-4">
<div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
<svg className="w-6 h-6 text-green-600 dark:text-green-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
</svg>
</div>
<h3 className="ml-3 text-lg font-semibold">Hierarchical Process</h3>
</div>
<p>Manager-coordinated task execution with dynamic assignment</p>
</div>
```mermaid
graph LR
Input[Input] --> A1
subgraph Agents
direction LR
A1[Agent 1] --> A2[Agent 2] --> A3[Agent 3]
end
A3 --> Output[Output]
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
<div className="flex items-center mb-4">
<div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
<svg className="w-6 h-6 text-purple-600 dark:text-purple-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
</div>
<h3 className="ml-3 text-lg font-semibold">Workflow Process</h3>
</div>
<p>Complex task flows with conditional execution and state management</p>
</div>
</div>
</Frame>
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
```
### Sequential Process
The simplest form of task execution where tasks are performed one after another.
<Frame>
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
#### Characteristics
- Linear execution flow
- Predictable order
- Simple dependency management
- Direct task progression
<Card>
### Characteristics
- Linear execution flow
- Predictable order
- Simple dependency management
- Direct task progression
#### Usage
```python
agents = PraisonAIAgents(
agents=[agent1, agent2],
tasks=[task1, task2, task3],
process="sequential"
)
```
</div>
</Frame>
### Usage
```python
agents = PraisonAIAgents(
agents=[agent1, agent2],
tasks=[task1, task2, task3],
process="sequential"
)
```
</Card>
## 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
```
### Hierarchical Process
Uses a manager agent to coordinate task execution and agent assignments.
<Frame>
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
#### Characteristics
- Manager-driven coordination
- Dynamic task assignment
- Flexible execution order
- Intelligent resource allocation
<Card>
### Characteristics
- Manager-driven coordination
- Dynamic task assignment
- Flexible execution order
- Intelligent resource allocation
#### Configuration
```python
agents = PraisonAIAgents(
agents=[manager_agent, worker_agent1, worker_agent2],
tasks=[task1, task2],
process="hierarchical",
manager_llm="gpt-4o"
)
```
</div>
</Frame>
### Configuration
```python
agents = PraisonAIAgents(
agents=[manager_agent, worker_agent1, worker_agent2],
tasks=[task1, task2],
process="hierarchical",
manager_llm="gpt-4o"
)
```
</Card>
## 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
```
### Workflow Process
Advanced process type supporting complex task relationships and conditional execution.
<Card>
### Features
- Task dependencies
- Conditional branching
- Loop handling
- Context sharing
- State management
### Implementation
```python
task_workflow = {
"start_task": {
"next": ["decision_task"],
"type": "task"
},
"decision_task": {
"type": "decision",
"conditions": {
"success": ["process_task"],
"failure": ["error_task"]
}
}
}
```
</Card>
## Getting Started
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Create Agent">
Create `app.py`:
<CodeGroup>
```python Single Agent Sequential Process
from praisonaiagents import Agent, Task, PraisonAIAgents
# 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"
)
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
# Run the agents
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
verbose=False,
process="sequential"
)
result = agents.start()
```
```python Multiple Agents Hierarchical Process
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()
```
</CodeGroup>
</Step>
</Steps>
<br /><br />
<div className="relative w-full aspect-video">
<iframe
className="absolute top-0 left-0 w-full h-full"
@@ -111,110 +302,152 @@ Advanced process type supporting complex task relationships and conditional exec
</div>
<br />
<Frame>
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
#### Features
- Task dependencies
- Conditional branching
- Loop handling
- Context sharing
- State management
#### Implementation
```python
task_workflow = {
"start_task": {
"next": ["decision_task"],
"type": "task"
},
"decision_task": {
"type": "decision",
"conditions": {
"success": ["process_task"],
"failure": ["error_task"]
}
}
}
```
</div>
</Frame>
## Advanced Features
### State Management
- Task state tracking
- Context preservation
- Data flow control
<CardGroup cols={2}>
<Card title="State Management" icon="database" iconType="solid">
<AccordionGroup>
<Accordion title="Task State Tracking">
Monitor and manage the progress of each task in real-time
</Accordion>
<Accordion title="Context Preservation">
Maintain important information across different stages of execution
</Accordion>
<Accordion title="Data Flow Control">
Manage how data moves between tasks and agents efficiently
</Accordion>
</AccordionGroup>
</Card>
### Error Handling
- Graceful failure recovery
- Alternative path execution
- Error reporting
<Card title="Error Handling" icon="shield-check" iconType="solid">
<AccordionGroup>
<Accordion title="Graceful Recovery">
Automatically handle failures and continue execution
</Accordion>
<Accordion title="Alternative Paths">
Switch to backup plans when primary execution fails
</Accordion>
<Accordion title="Error Reporting">
Detailed error logs and diagnostic information
</Accordion>
</AccordionGroup>
</Card>
### Monitoring
- Progress tracking
- Performance metrics
- Resource utilization
<Card title="Monitoring" icon="chart-line" iconType="solid">
<AccordionGroup>
<Accordion title="Progress Tracking">
Real-time visibility into task completion status
</Accordion>
<Accordion title="Performance Metrics">
Measure execution time and resource efficiency
</Accordion>
<Accordion title="Resource Usage">
Monitor system resource utilization
</Accordion>
</AccordionGroup>
</Card>
### Integration
- External system coordination
- API synchronization
- Event handling
<Card title="Integration" icon="plug" iconType="solid">
<AccordionGroup>
<Accordion title="External Systems">
Connect with other services and platforms
</Accordion>
<Accordion title="API Sync">
Maintain data consistency across systems
</Accordion>
<Accordion title="Event Handling">
React to system and external events
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
## Async Process Execution
All process types (sequential, workflow, hierarchical) support async execution through async generators. This enables efficient handling of async tasks and parallel processing.
## Async Processing
### Async Process Methods
- `asequential`: Async version of sequential process
- `aworkflow`: Async version of workflow process
- `ahierarchical`: Async version of hierarchical process
<Note>
All process types support asynchronous execution through async generators, enabling efficient parallel processing and non-blocking operations.
</Note>
### Example Usage:
### Core Async Methods
```python
import asyncio
from praisonaiagents import Agent, Task, PraisonAIAgents
<CardGroup cols={3}>
<Card title="asequential" icon="arrow-right">
Async version of sequential process for non-blocking linear execution
</Card>
<Card title="aworkflow" icon="diagram-project">
Async workflow process for complex parallel task execution
</Card>
<Card title="ahierarchical" icon="sitemap">
Async hierarchical process for distributed task management
</Card>
</CardGroup>
async def main():
# Create agents and tasks
agents = [async_agent1, async_agent2]
tasks = [async_task1, async_task2]
### Process-Specific Features
# Initialize PraisonAIAgents with async workflow
agents = PraisonAIAgents(
agents=agents,
tasks=tasks,
process="workflow" # or "sequential" or "hierarchical"
)
<Tabs>
<Tab title="Sequential Process">
<Card>
- Tasks execute in order but don't block
- Maintains sequence while allowing async operations
- Perfect for I/O-heavy tasks
```python
async def main():
agents = PraisonAIAgents(
process="sequential",
async_mode=True
)
await agents.astart()
```
</Card>
</Tab>
<Tab title="Workflow Process">
<Card>
- Parallel execution of independent tasks
- Async branching and merging
- Dynamic task scheduling based on conditions
```python
async def main():
agents = PraisonAIAgents(
process="workflow",
async_mode=True,
parallel_tasks=True
)
await agents.astart()
```
</Card>
</Tab>
<Tab title="Hierarchical Process">
<Card>
- Async manager delegation
- Parallel subtask execution
- Dynamic worker assignment
```python
async def main():
agents = PraisonAIAgents(
process="hierarchical",
async_mode=True,
dynamic_assignment=True
)
await agents.astart()
```
</Card>
</Tab>
</Tabs>
# Start async execution
result = await agents.astart()
print(result)
### Key Benefits
# Run the async workflow
asyncio.run(main())
```
### Async Process Features:
- Parallel task execution in workflow
- Async task delegation in hierarchical process
- Non-blocking task execution
- Efficient resource utilization
- Mixed sync/async task support
### Process-Specific Async Behavior:
1. **Sequential Process**:
- Tasks are executed in order
- Async tasks don't block other tasks
- Maintains sequential order while allowing async execution
2. **Workflow Process**:
- Parallel execution of independent tasks
- Async branching and merging
- Dynamic task scheduling
3. **Hierarchical Process**:
- Async manager delegation
- Parallel subtask execution
- Dynamic task assignment
<CardGroup cols={2}>
<Card title="Performance" icon="bolt">
- Efficient resource utilization
- Reduced waiting time
- Better throughput
</Card>
<Card title="Flexibility" icon="puzzle-piece">
- Mix sync and async tasks
- Adaptable execution patterns
- Easy scaling
</Card>
</CardGroup>
+391 -178
View File
@@ -4,117 +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.
<Frame>
<div className="p-6 bg-white dark:bg-gray-800 rounded-lg">
<div className="grid grid-cols-1 gap-6">
{/* Task Flow Steps */}
<div className="flex justify-between items-center">
{/* Task Definition */}
<div className="flex-1 p-4 border-2 border-blue-500 rounded-lg text-center">
<div className="flex items-center justify-center mb-2">
<div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-full">
<svg className="w-6 h-6 text-blue-600 dark:text-blue-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
</div>
</div>
<h4 className="font-semibold">Task Definition</h4>
<p className="text-sm mt-1">Description & Requirements</p>
</div>
```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]
{/* Arrow 1 */}
<div className="flex-none px-4">
<svg className="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
</svg>
</div>
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
{/* Agent Assignment */}
<div className="flex-1 p-4 border-2 border-green-500 rounded-lg text-center">
<div className="flex items-center justify-center mb-2">
<div className="p-2 bg-green-100 dark:bg-green-900 rounded-full">
<svg className="w-6 h-6 text-green-600 dark:text-green-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
</div>
</div>
<h4 className="font-semibold">Agent Assignment</h4>
<p className="text-sm mt-1">Matching & Delegation</p>
</div>
{/* Arrow 2 */}
<div className="flex-none px-4">
<svg className="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
</svg>
</div>
{/* Execution */}
<div className="flex-1 p-4 border-2 border-purple-500 rounded-lg text-center">
<div className="flex items-center justify-center mb-2">
<div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-full">
<svg className="w-6 h-6 text-purple-600 dark:text-purple-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
</div>
</div>
<h4 className="font-semibold">Execution</h4>
<p className="text-sm mt-1">Processing & Tools</p>
</div>
{/* Arrow 3 */}
<div className="flex-none px-4">
<svg className="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
</svg>
</div>
{/* Output */}
<div className="flex-1 p-4 border-2 border-yellow-500 rounded-lg text-center">
<div className="flex items-center justify-center mb-2">
<div className="p-2 bg-yellow-100 dark:bg-yellow-900 rounded-full">
<svg className="w-6 h-6 text-yellow-600 dark:text-yellow-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</div>
</div>
<h4 className="font-semibold">Output</h4>
<p className="text-sm mt-1">Results & Validation</p>
</div>
</div>
{/* Task States */}
<div className="grid grid-cols-4 gap-4 mt-4">
<div className="p-3 border border-gray-200 rounded-lg bg-blue-50 dark:bg-blue-900">
<div className="flex items-center justify-center">
<span className="font-semibold">Pending</span>
</div>
</div>
<div className="p-3 border border-gray-200 rounded-lg bg-yellow-50 dark:bg-yellow-900">
<div className="flex items-center justify-center">
<span className="font-semibold">In Progress</span>
</div>
</div>
<div className="p-3 border border-gray-200 rounded-lg bg-green-50 dark:bg-green-900">
<div className="flex items-center justify-center">
<span className="font-semibold">Completed</span>
</div>
</div>
<div className="p-3 border border-gray-200 rounded-lg bg-red-50 dark:bg-red-900">
<div className="flex items-center justify-center">
<span className="font-semibold">Failed</span>
</div>
</div>
</div>
</div>
</div>
</Frame>
class Input,Output input
class Role,Goal,Story,Expected process
class Task transparent
```
## Core Components
@@ -155,6 +74,79 @@ icon: "list-check"
```
</CodeGroup>
# Understanding Tasks
<br />
```mermaid
graph LR
%% Task Flow Steps
Start([▶ Start]) --> TaskDef
TaskDef --> AgentAssign
AgentAssign --> Exec
Exec --> Output([✓ Output])
%% Define subgraphs for each step
subgraph TaskDef[" "]
TD_Icon[📋 Task Definition]
TD_Desc[Description & Requirements]
TD_Icon --- TD_Desc
style TD_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
style TD_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
end
subgraph AgentAssign[" "]
AA_Icon[🤖 Agent Assignment]
AA_Desc[Matching & Delegation]
AA_Icon --- AA_Desc
style AA_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
style AA_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
end
subgraph Exec[" "]
E_Icon[⚙️ Execution]
E_Desc[Processing & Tools]
E_Icon --- E_Desc
style E_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
style E_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
end
%% Styling for main elements
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
%% Style for containers
style TaskDef fill:#1B1F3B,stroke:#7C90A0,color:#fff
style AgentAssign fill:#1B1F3B,stroke:#7C90A0,color:#fff
style Exec fill:#1B1F3B,stroke:#7C90A0,color:#fff
%% Global styles
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
linkStyle default stroke:#7C90A0,stroke-width:2px
```
<br /><br />
```mermaid
graph LR
%% Task States
Pending([📥 Pending]) --> InProgress([⚡ In Progress])
InProgress --> Completed([✅ Completed])
InProgress --> Failed([❌ Failed])
%% Styling
style Pending fill:#2D3047,stroke:#7C90A0,color:#fff
style InProgress fill:#5C80BC,stroke:#7C90A0,color:#fff
style Completed fill:#2D3047,stroke:#7C90A0,color:#fff
style Failed fill:#2D3047,stroke:#7C90A0,color:#fff
%% Global styles
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
linkStyle default stroke:#7C90A0,stroke-width:2px
```
## Task Types
<Steps>
@@ -223,17 +215,300 @@ task_b = Task(
</Card>
</CardGroup>
## Getting Started
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Create Agent">
Create `app.py`:
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent, Task, PraisonAIAgents
# 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"
)
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
# Run the agents
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
verbose=False
)
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()
```
</CodeGroup>
</Step>
</Steps>
## Best Practices
<Tip>
Design tasks to be atomic and focused. Each task should have a single, clear responsibility.
</Tip>
<Note>
Design tasks to be atomic and focused. Each task should have a single, clear responsibility.
</Note>
1. Clear task descriptions
2. Well-defined success criteria
3. Appropriate tool selection
4. Error handling consideration
5. Resource management
<CardGroup cols={2}>
<Card title="Task Design Principles" icon="compass-drafting" iconType="solid">
<AccordionGroup>
<Accordion title="Clear Task Descriptions">
Write precise, unambiguous task descriptions that clearly state the task's purpose and requirements.
```python
task = Task(
description=(
"Analyze Q4 2024 sales data "
"and generate growth metrics"
),
expected_output="Sales growth report"
)
```
</Accordion>
<Accordion title="Success Criteria">
Define measurable success criteria to ensure task completion can be properly evaluated.
```python
task = Task(
success_criteria={
"format": "markdown",
"metrics": [
"growth_rate",
"revenue_change"
],
"min_confidence": 0.95
}
)
```
</Accordion>
<Accordion title="Task Dependencies">
Specify any dependencies or prerequisites for the task.
```python
task = Task(
description="Generate final report",
dependencies=[
data_collection_task,
analysis_task
],
wait_for_dependencies=True
)
```
</Accordion>
</AccordionGroup>
</Card>
<Card title="Resource Management" icon="server" iconType="solid">
<AccordionGroup>
<Accordion title="Tool Selection">
Choose appropriate tools that match your task's requirements.
```python
task = Task(
tools=[
DataAnalyzer(),
ReportGenerator(),
MetricsCalculator()
],
tool_config={
"timeout": 30,
"retry": True
}
)
```
</Accordion>
<Accordion title="Error Handling">
Implement comprehensive error management strategies.
```python
task = Task(
error_strategy="retry",
max_retries=3,
fallback_handler=handler,
error_callbacks=[
log_error,
notify_admin
]
)
```
</Accordion>
<Accordion title="Resource Limits">
Set appropriate resource constraints for optimal performance.
```python
task = Task(
memory_limit="2GB",
timeout=300,
max_concurrent=5,
cpu_priority="high",
auto_scale=True
)
```
</Accordion>
<Accordion title="Performance Monitoring">
Configure monitoring and logging for task execution.
```python
task = Task(
monitoring={
"metrics": ["duration", "memory", "cpu"],
"log_level": "INFO",
"trace_enabled": True,
"alert_threshold": 0.85
}
)
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
## Async Task Execution
<CardGroup cols={1}>
<Card title="Async Task Features" icon="bolt" iconType="solid">
<Tabs>
<Tab title="Basic Configuration">
```python
async_task = Task(
description="Perform async operation",
expected_output="Async result",
agent=async_agent,
async_execution=True, # Enable async execution
callback=async_callback # Optional async callback
)
```
- Enable async execution with `async_execution=True`
- Perfect for I/O-heavy operations
- Supports parallel task execution
</Tab>
<Tab title="Async Callbacks">
```python
async def async_callback(output: TaskOutput):
await asyncio.sleep(1) # Simulate async operation
print(f"Processed output: {output.raw}")
task = Task(
description="Task with async callback",
expected_output="Result",
agent=agent,
async_execution=True,
callback=async_callback
)
```
- Support for async callbacks
- Process results asynchronously
- Handle task completion events
</Tab>
<Tab title="Mixed Execution">
```python
# Create mixed task types
sync_task = Task(
description="Synchronous operation",
async_execution=False
)
async_task = Task(
description="Asynchronous operation",
async_execution=True
)
# Run with mixed execution
agents = PraisonAIAgents(
agents=[sync_agent, async_agent],
tasks=[sync_task, async_task]
)
result = await agents.astart()
```
- Mix sync and async tasks
- Flexible execution patterns
- Optimal resource utilization
</Tab>
</Tabs>
</Card>
</CardGroup>
<Tip>
**Pro Tip**: Use async execution for tasks that involve I/O operations (like API calls or file operations) to improve overall performance. Keep CPU-intensive tasks synchronous.
</Tip>
## Next Steps
@@ -252,66 +527,4 @@ task_b = Task(
>
Explore the complete Task API documentation
</Card>
</CardGroup>
## Async Task Execution
Tasks can be executed asynchronously by setting `async_execution=True`. This is particularly useful for tasks that involve I/O operations or when you want to run multiple tasks in parallel.
### Async Task Configuration
```python
async_task = Task(
description="Perform async operation",
expected_output="Async result",
agent=async_agent,
async_execution=True, # Enable async execution
callback=async_callback # Optional async callback
)
```
### Async Callbacks
Tasks support both synchronous and asynchronous callbacks:
```python
async def async_callback(output: TaskOutput):
await asyncio.sleep(1) # Simulate async operation
print(f"Processed output: {output.raw}")
# Task with async callback
task = Task(
description="Task with async callback",
expected_output="Result",
agent=agent,
async_execution=True,
callback=async_callback
)
```
### Mixing Sync and Async Tasks
You can mix synchronous and asynchronous tasks in the same workflow:
```python
# Sync task
sync_task = Task(
description="Synchronous operation",
expected_output="Sync result",
agent=sync_agent,
async_execution=False
)
# Async task
async_task = Task(
description="Asynchronous operation",
expected_output="Async result",
agent=async_agent,
async_execution=True
)
# Create agents with mixed tasks
agents = PraisonAIAgents(
agents=[sync_agent, async_agent],
tasks=[sync_task, async_task]
)
# Run asynchronously
result = await agents.astart()
```
</CardGroup>
+538 -226
View File
@@ -1,54 +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]
## Tools Overview
T3 --> A1
T1 --> A2
T2 --> A3
<Frame>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
<div className="flex items-center mb-4">
<div className="p-2 bg-blue-100 dark:bg-blue-900 rounded-lg">
<svg className="w-6 h-6 text-blue-600 dark:text-blue-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
<h3 className="ml-3 text-lg font-semibold">Search Tools</h3>
</div>
<p>Tools for searching and retrieving information from various sources</p>
</div>
style Tools fill:#189AB4,color:#fff
style Agents fill:#8B0000,color:#fff
style Input fill:#8B0000,color:#fff
style Output fill:#8B0000,color:#fff
```
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
<div className="flex items-center mb-4">
<div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
<svg className="w-6 h-6 text-green-600 dark:text-green-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2" />
</svg>
</div>
<h3 className="ml-3 text-lg font-semibold">File Tools</h3>
</div>
<p>Tools for reading, writing, and manipulating files</p>
</div>
| 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 |
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
<div className="flex items-center mb-4">
<div className="p-2 bg-purple-100 dark:bg-purple-900 rounded-lg">
<svg className="w-6 h-6 text-purple-600 dark:text-purple-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3" />
</svg>
</div>
<h3 className="ml-3 text-lg font-semibold">API Tools</h3>
</div>
<p>Tools for interacting with external APIs and services</p>
</div>
</div>
</Frame>
## 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>
@@ -99,237 +94,554 @@ Assign the tool to an agent
</Card>
## Implementing Tools Full Code Example
<Tabs>
Tools are implemented as Python functions with type hints and docstrings. Here's a complete example:
<Tab title="Code">
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents duckduckgo-search
```
</Step>
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from duckduckgo_search import DDGS
from typing import List, Dict
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
# 1. Tool Implementation
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search using DuckDuckGo
<Step title="Create Agent with Tool">
Create `app.py`
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from duckduckgo_search import DDGS
from typing import List, Dict
# 1. Tool Implementation
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search using DuckDuckGo
Args:
query (str): The search query string
Args:
query (str): The search query string
Returns:
List[Dict]: List of search results containing title, URL, and snippet
"""
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
Returns:
List[Dict]: List of search results containing title, URL, and snippet
"""
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
# 2. Assign the tool to an agent
data_agent = Agent(
name="DataCollector",
role="Search Specialist",
goal="Perform internet searches to collect relevant information.",
backstory="Expert in finding and organising internet data.",
tools=[internet_search_tool],
self_reflect=False
)
# 2. Assign the tool to an agent
data_agent = Agent(
name="DataCollector",
role="Search Specialist",
goal="Perform internet searches to collect relevant information.",
backstory="Expert in finding and organising internet data.",
tools=[internet_search_tool],
self_reflect=False
)
# 3. Task Definition
collect_task = Task(
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
expected_output="List of search results with titles, URLs, and snippets.",
agent=data_agent,
name="collect_data",
)
# 3. Task Definition
collect_task = Task(
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
expected_output="List of search results with titles, URLs, and snippets.",
agent=data_agent,
name="collect_data",
)
# 4. Start Agents
agents = PraisonAIAgents(
agents=[data_agent],
tasks=[collect_task],
process="sequential"
)
# 4. Start Agents
agents = PraisonAIAgents(
agents=[data_agent],
tasks=[collect_task],
process="sequential"
)
agents.start()
```
agents.start()
```
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
python app.py
```
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install PraisonAI">
Install the core package and duckduckgo_search package:
```bash Terminal
pip install praisonai duckduckgo_search
```
</Step>
<Step title="Create Custom Tool">
<Info>
To add additional tools/features you need some coding which can be generated using ChatGPT or any LLM
</Info>
Create a new file `tools.py` with the following content:
```python
from duckduckgo_search import DDGS
from typing import List, Dict
# 1. Tool
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search
"""
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
```
</Step>
<Step title="Create Agent">
Create a new file `agents.yaml` with the following content:
```yaml
framework: praisonai
topic: create movie script about cat in mars
roles:
scriptwriter:
backstory: Expert in dialogue and script structure, translating concepts into
scripts.
goal: Write a movie script about a cat in Mars
role: Scriptwriter
tools:
- internet_search_tool # <-- Tool assigned to Agent here
tasks:
scriptwriting_task:
description: Turn the story concept into a production-ready movie script,
including dialogue and scene details.
expected_output: Final movie script with dialogue and scene details.
```
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
praisonai agents.yaml
```
</Step>
</Steps>
</Tab>
</Tabs>
## In-build Tools in PraisonAI
<CardGroup cols={2}>
<Card title="Search Tools" icon="magnifying-glass" href="/tools/search">
Tools for searching and retrieving information from various sources
</Card>
<Card title="Python Tools" icon="python" href="/tools/python_tools">
Essential Python utilities for data manipulation and scripting
</Card>
<Card title="Spider Tools" icon="spider" href="/tools/spider_tools">
Web crawling and scraping capabilities for data extraction
</Card>
<Card title="Arxiv Tools" icon="book" href="/tools/arxiv_tools">
Access and search academic papers from arXiv repository
</Card>
<Card title="Newspaper Tools" icon="newspaper" href="/tools/newspaper_tools">
Extract and parse content from news articles and websites
</Card>
<Card title="DuckDB Tools" icon="database" href="/tools/duckdb_tools">
Fast analytical SQL database operations and queries
</Card>
<Card title="DuckDuckGo Tools" icon="duck" href="/tools/duckduckgo_tools">
Web search functionality using DuckDuckGo's API
</Card>
<Card title="Calculator Tools" icon="calculator" href="/tools/calculator_tools">
Perform mathematical calculations and conversions
</Card>
<Card title="YAML Tools" icon="file-code" href="/tools/yaml_tools">
Parse and manipulate YAML format data
</Card>
<Card title="JSON Tools" icon="brackets-curly" href="/tools/json_tools">
Handle JSON data structures and operations
</Card>
<Card title="Pandas Tools" icon="table" href="/tools/pandas_tools">
Data analysis and manipulation using Pandas
</Card>
<Card title="YFinance Tools" icon="chart-line" href="/tools/yfinance_tools">
Fetch financial market data from Yahoo Finance
</Card>
<Card title="Shell Tools" icon="terminal" href="/tools/shell_tools">
Execute shell commands and system operations
</Card>
<Card title="Wikipedia Tools" icon="book-open" href="/tools/wikipedia_tools">
Access and search Wikipedia articles and data
</Card>
<Card title="XML Tools" icon="code" href="/tools/xml_tools">
Process and manipulate XML format data
</Card>
<Card title="File Tools" icon="file" href="/tools/file_tools">
File system operations and management utilities
</Card>
<Card title="Excel Tools" icon="file-excel" href="/tools/excel_tools">
Work with Excel spreadsheets and workbooks
</Card>
<Card title="CSV Tools" icon="file-csv" href="/tools/csv_tools">
Handle CSV file operations and transformations
</Card>
</CardGroup>
## Tools Overview
<CardGroup cols={3}>
<Card
title="Search Tools"
icon="magnifying-glass"
iconType="solid"
>
Tools for searching and retrieving information from various sources
</Card>
<Card
title="File Tools"
icon="file"
iconType="solid"
>
Tools for reading, writing, and manipulating files
</Card>
<Card
title="API Tools"
icon="code"
iconType="solid"
>
Tools for interacting with external APIs and services
</Card>
</CardGroup>
## Advanced Tool Features
### Tool Configuration
<Frame>
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
```python
def configured_tool(
query: str,
max_results: int = 5,
timeout: int = 10
) -> List[Dict]:
"""
Example of a configurable tool
```python
def configured_tool(
query: str,
max_results: int = 5,
timeout: int = 10
) -> List[Dict]:
"""
Example of a configurable tool
Args:
query (str): Search query
max_results (int): Maximum number of results
timeout (int): Request timeout in seconds
Args:
query (str): Search query
max_results (int): Maximum number of results
timeout (int): Request timeout in seconds
Returns:
List[Dict]: Search results
"""
# Tool implementation
pass
```
</div>
Returns:
List[Dict]: Search results
"""
# Tool implementation
pass
```
</Frame>
### Tool Chaining
<Frame>
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
```python
def chain_tools(input_data: str) -> Dict:
"""
Example of chaining multiple tools
```python
def chain_tools(input_data: str) -> Dict:
"""
Example of chaining multiple tools
Args:
input_data (str): Input data
Args:
input_data (str): Input data
Returns:
Dict: Processed results
"""
# 1. Search for data
search_results = internet_search_tool(input_data)
# 2. Process results
processed_data = process_tool(search_results)
# 3. Format output
return format_tool(processed_data)
```
</div>
Returns:
Dict: Processed results
"""
# 1. Search for data
search_results = internet_search_tool(input_data)
# 2. Process results
processed_data = process_tool(search_results)
# 3. Format output
return format_tool(processed_data)
```
</Frame>
### Tool Categories
1. **Data Collection Tools**
- Web scraping
- API integration
- Database queries
2. **Processing Tools**
- Data transformation
- Text analysis
- Image processing
3. **Output Tools**
- File generation
- Report creation
- Data visualization
<CardGroup cols={3}>
<Card title="Data Collection Tools">
- Web scraping
- API integration
- Database queries
</Card>
<Card title="Processing Tools">
- Data transformation
- Text analysis
- Image processing
</Card>
<Card title="Output Tools">
- File generation
- Report creation
- Data visualization
</Card>
</CardGroup>
## Tool Integration
### Adding Tools to Agents
<Frame>
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
```python
# Multiple tools
agent = Agent(
name="MultiTool Agent",
tools=[
internet_search_tool,
file_processing_tool,
api_integration_tool
]
)
```
</div>
```python
# Multiple tools
agent = Agent(
name="MultiTool Agent",
tools=[
internet_search_tool,
file_processing_tool,
api_integration_tool
]
)
```
</Frame>
### Tool Dependencies
<Frame>
<div className="p-4 bg-white dark:bg-gray-800 rounded-lg">
```python
# Tool with dependencies
def advanced_tool(data: Dict) -> Dict:
"""
Tool that depends on external libraries
```python
# Tool with dependencies
def advanced_tool(data: Dict) -> Dict:
"""
Tool that depends on external libraries
Args:
data (Dict): Input data
Args:
data (Dict): Input data
Returns:
Dict: Processed data
"""
try:
import required_library
# Tool implementation
return processed_result
except ImportError:
raise Exception("Required library not installed")
```
</div>
Returns:
Dict: Processed data
"""
try:
import required_library
# Tool implementation
return processed_result
except ImportError:
raise Exception("Required library not installed")
```
</Frame>
## Tool Guidelines
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
<h3 className="text-lg font-semibold mb-3">Best Practices</h3>
1. **Type Hints**
- Use Python type hints
- Define clear input/output types
- Document complex types
2. **Documentation**
- Write clear docstrings
- Explain parameters
- Provide usage examples
<CardGroup cols={2}>
<Card title="Best Practices">
1. **Type Hints**
- Use Python type hints
- Define clear input/output types
- Document complex types
3. **Error Handling**
- Handle exceptions gracefully
- Return meaningful errors
- Validate inputs
</div>
2. **Documentation**
- Write clear docstrings
- Explain parameters
- Provide usage examples
<div className="p-4 border rounded-lg bg-white dark:bg-gray-800">
<h3 className="text-lg font-semibold mb-3">Tool Types</h3>
1. **Search Tools**
- Web search
- Database queries
- Document search
3. **Error Handling**
- Handle exceptions gracefully
- Return meaningful errors
- Validate inputs
</Card>
2. **File Tools**
- Read/write operations
- File conversion
- Data extraction
<Card title="Tool Types">
1. **Search Tools**
- Web search
- Database queries
- Document search
3. **API Tools**
- REST API calls
- GraphQL queries
- Service integration
</div>
</div>
2. **File Tools**
- Read/write operations
- File conversion
- Data extraction
3. **API Tools**
- REST API calls
- GraphQL queries
- Service integration
</Card>
</CardGroup>
## Best Practices Summary
1. **Design Principles**
- Single responsibility
- Clear interfaces
- Proper documentation
- Error handling
<Note>
Following these best practices will help you create robust, efficient, and secure tools in PraisonAI.
</Note>
2. **Performance**
- Efficient processing
- Resource management
- Caching when appropriate
- Asynchronous operations
<CardGroup cols={1}>
<Card title="Design Principles" icon="compass-drafting" iconType="solid">
<AccordionGroup>
<Accordion title="Single Responsibility">
Each tool should have one clear purpose and do it well. Avoid creating tools that try to do too many things.
```python
# Good Example
def process_image(image: np.array) -> np.array:
return processed_image
3. **Security**
- Input validation
- Rate limiting
- API key management
- Error masking
# Avoid
def process_and_save_and_upload(image):
# Too many responsibilities
pass
```
</Accordion>
<Accordion title="Clear Interfaces">
Define explicit input/output types and maintain consistent parameter naming.
```python
def search_tool(
query: str,
max_results: int = 10
) -> List[Dict[str, Any]]:
"""
Search for information with clear parameters
"""
pass
```
</Accordion>
<Accordion title="Documentation">
Always include detailed docstrings and type hints.
```python
def analyze_text(
text: str,
language: str = "en"
) -> Dict[str, float]:
"""
Analyze text sentiment and emotions.
Args:
text: Input text to analyze
language: ISO language code
Returns:
Dict with sentiment scores
"""
pass
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
<br />
<CardGroup cols={1}>
<Card title="Performance Optimization" icon="bolt" iconType="solid">
<AccordionGroup>
<Accordion title="Efficient Processing">
Optimize resource usage and processing time.
```python
# Use generators for large datasets
def process_large_data():
for chunk in data_generator():
yield process_chunk(chunk)
```
</Accordion>
<Accordion title="Resource Management">
Properly handle resource allocation and cleanup.
```python
async with aiohttp.ClientSession() as session:
# Resource automatically managed
await process_data(session)
```
</Accordion>
<Accordion title="Caching">
Implement caching for frequently accessed data.
```python
@cache.memoize(timeout=300)
def expensive_operation(data: str) -> Dict:
return process_expensive(data)
```
</Accordion>
<Accordion title="Async Operations">
Use async/await for I/O-bound operations.
```python
async def fetch_data(urls: List[str]):
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
return await asyncio.gather(*tasks)
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
<br />
<CardGroup cols={1}>
<Card title="Security Best Practices" icon="shield-check" iconType="solid">
<AccordionGroup>
<Accordion title="Input Validation">
Always validate and sanitize inputs to prevent security vulnerabilities.
```python
def process_user_input(data: str) -> str:
if not isinstance(data, str):
raise ValueError("Input must be string")
return sanitize_input(data.strip())
```
</Accordion>
<Accordion title="Rate Limiting">
Implement rate limiting for API calls to prevent abuse.
```python
@rate_limit(calls=100, period=60)
async def api_call():
return await make_request()
```
</Accordion>
<Accordion title="API Key Management">
Securely handle API keys and credentials using environment variables.
```python
# Use environment variables
api_key = os.getenv('API_KEY')
if not api_key:
raise ConfigError("API key not found")
```
</Accordion>
<Accordion title="Error Masking">
Hide sensitive information in error messages to prevent information leakage.
```python
try:
result = process_sensitive_data()
except Exception as e:
# Log detailed error internally
logger.error(f"Detailed error: {str(e)}")
# Return sanitized error to user
raise PublicError("Processing failed")
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
<br />
<Tip>
**Pro Tip**: Start with these practices from the beginning of your project. It's easier to maintain good practices than to retrofit them later.
</Tip>
+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>
Loaded 100 of 499 files, more files were not shown because too many files have changed in this diff. Show more