Compare commits

...
78 Commits
Author SHA1 Message Date
Mervin Praison 0985e12ad4 Merge pull request #366 from MervinPraison/develop
Bump version to 2.0.65 and update deployment configurations
2025-02-04 08:05:06 +00:00
MervinPraison 0fbb7972e1 Bump version to 2.0.65 and update deployment configurations
- Updated version across multiple files (praisonai.rb, pyproject.toml, uv.lock, Dockerfile, deploy.py, docs)
- Enhanced Conda environment setup script with Ollama installation check
- Minor improvements to deployment and setup scripts
2025-02-04 08:04:44 +00:00
Mervin Praison 5744ae853e Merge pull request #365 from MervinPraison/develop
Develop
2025-02-04 07:36:59 +00:00
MervinPraison bd6e3da4ff Bump version to 2.0.64 and update dependencies
- Updated version across multiple files (praisonai.rb, pyproject.toml, uv.lock, Dockerfile, deploy.py, docs)
- Added TRAIN_AVAILABLE flag in cli.py for optional training feature
- Updated Conda environment setup script with latest dependencies
- Minor improvements to training and deployment configurations
2025-02-04 07:36:43 +00:00
MervinPraison f2f51d9e8b Refactor train.py with Enhanced Dataset Processing and Tokenization
- Completely rewrote training script with robust dataset handling
- Added support for ShareGPT and Alpaca-style datasets
- Implemented advanced formatting and tokenization functions
- Enhanced debug logging and error handling
- Simplified model preparation and training workflow
- Updated chat template and tokenization strategies
- Improved inference and model saving methods
2025-02-03 19:38:57 +00:00
Mervin Praison 4a1098603d Merge pull request #364 from MervinPraison/develop
cli docs
2025-02-03 07:41:14 +00:00
MervinPraison 5468e35bc1 cli docs 2025-02-03 07:40:46 +00:00
Mervin Praison b468267a87 Merge pull request #362 from MervinPraison/develop
Develop
2025-02-02 06:45:30 +00:00
MervinPraison 48141bbd9e update readme 2025-02-02 06:45:12 +00:00
MervinPraison b3cdf53d07 adding demo 2025-02-02 06:43:16 +00:00
Mervin Praison aa594ddc32 Merge pull request #361 from MervinPraison/develop
update read me 2
2025-02-02 06:30:57 +00:00
MervinPraison 5f330e8fb2 update read me 2 2025-02-02 06:30:37 +00:00
Mervin Praison ff94e128de Merge pull request #360 from MervinPraison/develop
update read me
2025-02-02 06:28:35 +00:00
MervinPraison 854a016fc5 update read me 2025-02-02 06:28:08 +00:00
Mervin Praison 12e8ed7b77 Merge pull request #359 from MervinPraison/develop
Update CLI Documentation with Latest LLM Model Option
2025-02-01 21:51:34 +00:00
MervinPraison 13c5f5537e Update CLI Documentation with Latest LLM Model Option
- Updated CLI documentation to reflect the latest LLM model option
- Changed example command to use `gpt-4o-mini` instead of `gpt-4-mini`
- Minor documentation refinement for CLI feature
2025-02-01 21:51:20 +00:00
Mervin Praison e7c1614ac8 Merge pull request #358 from MervinPraison/develop
Add CLI Documentation and Enhance CLI Functionality
2025-02-01 00:20:09 +00:00
MervinPraison 7cc6db2a34 Add CLI Documentation and Enhance CLI Functionality
- Added comprehensive CLI documentation in docs/features/cli.mdx
- Enhanced CLI functionality with new command-line options
- Implemented `--llm` flag to specify LLM models for direct prompts
- Updated CLI parsing to support flexible LLM model selection
- Improved direct prompt handling across different AI frameworks
- Bumped package version to 2.0.63
2025-02-01 00:19:44 +00:00
Mervin Praison b869bbc346 Merge pull request #357 from MervinPraison/develop
Enhance CLI with Direct Prompt Handling and Framework Flexibility
2025-02-01 00:01:27 +00:00
MervinPraison 5492be4412 Enhance CLI with Direct Prompt Handling and Framework Flexibility
- Added direct prompt handling in CLI for immediate task execution
- Implemented fallback mechanism to support multiple AI agent frameworks (PraisonAI, CrewAI, AutoGen)
- Updated CLI parsing to handle various input scenarios
- Simplified agent initialization for direct prompts
- Improved error messaging for framework installation
- Bumped package version to 2.0.62
2025-02-01 00:01:12 +00:00
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
309 changed files with 11211 additions and 3333 deletions

No files matched your search

+8 -1885
View File
File diff suppressed because it is too large. Load diff
+29 -6
View File
@@ -54,7 +54,7 @@ PraisonAI is a production-ready Multi-AI Agents framework with self-reflection,
- 📄 YAML Configuration
- 💯 100+ LLM Support
## Using Code
## Using Python Code
Light weight package dedicated for coding:
```bash
@@ -71,7 +71,7 @@ Create app.py file and add the code below:
```python
from praisonaiagents import Agent
agent = Agent(instructions="Your are a helpful AI assistant")
agent.chat("Write a movie script about a robot in Mars")
agent.start("Write a movie script about a robot in Mars")
```
Run:
@@ -105,6 +105,21 @@ 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');
```
![PraisonAI CLI Demo](docs/demo/praisonai-cli-demo.gif)
## AI Agents Flow
```mermaid
@@ -472,6 +487,8 @@ export OPENAI_BASE_URL=https://api.groq.com/openai/v1
### Simple Playbook Example
Create `agents.yaml` file and add the code below:
```yaml
framework: praisonai
topic: Artificial Intelligence
@@ -544,14 +561,19 @@ uv pip install -r pyproject.toml --extra "crewai,autogen"
[![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) |
@@ -564,4 +586,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) |
-8
View File
@@ -1,8 +0,0 @@
1. Make minimal code changes as possible
2. if you are creating function, make sure to name it in more easy, user friendly , optimised manner.
3. Never copy the exact code if presented with a code from other location or file or codebase, just make it optimised
4. Always Follow the principle LESS IS MORE
5. Make it minimal change as possible
6. Firstly try not to make any modification to the existing code as possible
7. Only modify the existing code if its highly required, without that if it cant be done, then add new code section.
8. If you are adding new code, make sure to add it in a way that it can be easily integrated with the existing codebase.
-4
View File
@@ -1,4 +0,0 @@
"""Agent module for AI agents"""
from .agent import Agent
__all__ = ['Agent']
-650
View File
@@ -1,650 +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
import csv
import os
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, max_iter: int = 10):
self.tasks = tasks
self.agents = agents
self.manager_llm = manager_llm
self.verbose = verbose
self.max_iter = max_iter
async def aworkflow(self) -> AsyncGenerator[str, None]:
"""Async version of workflow method"""
current_iter = 0 # Track how many times we've looped
# 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:
current_iter += 1
if current_iter > self.max_iter:
logging.info(f"Max iteration limit {self.max_iter} reached, ending workflow.")
break
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}"
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)
# Reset completed task to "not started" so it can run again
if self.tasks[task_id].status == "completed":
logging.debug(f"Task {task_id} was completed, resetting to 'not started' for next iteration.")
self.tasks[task_id].status = "not started"
# 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 and current_task.result:
if current_task.task_type in ["decision", "loop"]:
# MINIMAL CHANGE: use pydantic decision if present
decision_str = current_task.result.raw.lower()
if current_task.result.pydantic and hasattr(current_task.result.pydantic, "decision"):
decision_str = current_task.result.pydantic.decision.lower()
# Check conditions
for condition, tasks in current_task.condition.items():
if condition.lower() == decision_str:
# Handle both list and direct string values
task_value = tasks[0] if isinstance(tasks, list) else tasks
if not task_value or task_value == "exit":
logging.info("Workflow exit condition met, ending workflow")
current_task = None
break
next_task_name = task_value
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 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"""
current_iter = 0 # Track how many times we've looped
# 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")
# If loop type and no input_file, default to tasks.csv
if start_task and start_task.task_type == "loop" and not start_task.input_file:
start_task.input_file = "tasks.csv"
# --- If loop + input_file, read file & create tasks
if start_task and start_task.task_type == "loop" and getattr(start_task, "input_file", None):
try:
file_ext = os.path.splitext(start_task.input_file)[1].lower()
new_tasks = []
if file_ext == ".csv":
# existing CSV reading logic
with open(start_task.input_file, "r", encoding="utf-8") as f:
# Try as simple CSV first
reader = csv.reader(f)
previous_task = None
for i, row in enumerate(reader):
if row: # Skip empty rows
task_desc = row[0] # Take first column
row_task = Task(
description=task_desc, # Keep full row as description
agent=start_task.agent,
name=task_desc, # Use first column as name
is_start=(i == 0),
task_type="task",
condition={
"complete": ["next"],
"retry": ["current"]
}
)
self.tasks[row_task.id] = row_task
new_tasks.append(row_task)
if previous_task:
previous_task.next_tasks = [row_task.name]
previous_task.condition["complete"] = [row_task.name]
previous_task = row_task
else:
# If not CSV, read lines
with open(start_task.input_file, "r", encoding="utf-8") as f:
lines = f.read().splitlines()
previous_task = None
for i, line in enumerate(lines):
row_task = Task(
description=line.strip(),
agent=start_task.agent,
name=line.strip(),
is_start=(i == 0),
task_type="task",
condition={
"complete": ["next"],
"retry": ["current"]
}
)
self.tasks[row_task.id] = row_task
new_tasks.append(row_task)
if previous_task:
previous_task.next_tasks = [row_task.name]
previous_task.condition["complete"] = [row_task.name]
previous_task = row_task
if new_tasks:
start_task = new_tasks[0]
logging.info(f"Created {len(new_tasks)} tasks from: {start_task.input_file}")
except Exception as e:
logging.error(f"Failed to read file tasks: {e}")
# end of the new block
current_task = start_task
visited_tasks = set()
loop_data = {} # Store loop-specific data
while current_task:
current_iter += 1
if current_iter > self.max_iter:
logging.info(f"Max iteration limit {self.max_iter} reached, ending workflow.")
break
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}"
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)
# Reset completed task to "not started" so it can run again: Only for workflow because some tasks may be revisited
if self.tasks[task_id].status == "completed":
logging.debug(f"Task {task_id} was completed, resetting to 'not started' for next iteration.")
self.tasks[task_id].status = "not started"
# 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 and current_task.result:
if current_task.task_type in ["decision", "loop"]:
# MINIMAL CHANGE: use pydantic decision if present
decision_str = current_task.result.raw.lower()
if current_task.result.pydantic and hasattr(current_task.result.pydantic, "decision"):
decision_str = current_task.result.pydantic.decision.lower()
# Check conditions
for condition, tasks in current_task.condition.items():
if condition.lower() == decision_str:
# Handle both list and direct string values
task_value = tasks[0] if isinstance(tasks, list) else tasks
if not task_value or task_value == "exit":
logging.info("Workflow exit condition met, ending workflow")
current_task = None
break
next_task_name = task_value
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 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")
+1 -1
View File
@@ -1,6 +1,6 @@
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.57 gunicorn markdown
RUN pip install flask praisonai==2.0.65 gunicorn markdown
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
+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.57 gunicorn markdown\n&#34;)
file.write(&#34;RUN pip install flask praisonai==2.0.65 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;)
+12 -76
View File
@@ -112,86 +112,22 @@ graph LR
<Step title="Create Agent">
Create `app.py`:
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent, Task, PraisonAIAgents
```python Single Agent
from praisonaiagents import Agent
# Create an agent
researcher = Agent(
name="Researcher",
role="Senior Research Analyst",
goal="Uncover cutting-edge developments in AI",
backstory="You are an expert at a technology research group",
verbose=True,
llm="gpt-4o"
)
agent = Agent(instructions="Your are a helpful AI assistant")
agent.start("Write a movie script about a robot in Mars")
```
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
```python Multi Agents
from praisonaiagents import Agent, PraisonAIAgents
# Run the agents
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
verbose=False
)
research_agent = Agent(instructions="Research about AI")
summarise_agent = Agent(instructions="Summarise research agent's findings")
result = agents.start()
```
```python Multiple Agents
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create multiple agents
researcher = Agent(
name="Researcher",
role="Senior Research Analyst",
goal="Uncover cutting-edge developments in AI",
backstory="You are an expert at a technology research group",
verbose=True,
llm="gpt-4o",
markdown=True
)
writer = Agent(
name="Writer",
role="Tech Content Strategist",
goal="Craft compelling content on tech advancements",
backstory="You are a content strategist",
llm="gpt-4o",
markdown=True
)
# Define multiple tasks
task1 = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
task2 = Task(
name="writing_task",
description="Create a blog post about AI advancements",
expected_output="A blog post",
agent=writer
)
# Run with hierarchical process
agents = PraisonAIAgents(
agents=[researcher, writer],
tasks=[task1, task2],
verbose=False,
process="hierarchical",
manager_llm="gpt-4o"
)
result = agents.start()
```
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
agents.start()
```
</CodeGroup>
</Step>
Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

+117
View File
@@ -0,0 +1,117 @@
---
title: "Command Line Interface"
sidebarTitle: "CLI"
description: "Use PraisonAI directly from your terminal with simple commands"
icon: "terminal"
---
```mermaid
flowchart LR
Start((🚀)) --> CLI[CLI Command]
CLI --> Agent[AI Agent]
Agent --> Config[Config/YAML]
Config --> Out((🏁))
style Start fill:#8B0000,color:#fff,stroke:#8B0000
style CLI fill:#2E8B57,color:#fff
style Agent fill:#2E8B57,color:#fff
style Config fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff,stroke:#8B0000
```
PraisonAI CLI provides a simple way to interact with AI agents directly from your terminal. You can run quick commands, specify LLM options, or use YAML configuration files for more complex scenarios.
<Frame>
<img src="../demo/praisonai-cli-demo.gif" alt="PraisonAI CLI Demo" />
</Frame>
## Quick Start
<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:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
</Steps>
## Usage Examples
<AccordionGroup>
<Accordion title="Simple Command" icon="terminal" defaultOpen>
Run a simple command directly:
```bash
praisonai "write a movie script in 3 lines"
```
</Accordion>
<Accordion title="With LLM Option" icon="wand-magic-sparkles" defaultOpen>
Specify a different LLM model:
```bash
praisonai "write a movie script in 3 lines" --llm gpt-4o-mini
```
</Accordion>
<Accordion title="Using YAML Config" icon="file-code" defaultOpen>
Run agents defined in a YAML file:
```bash
praisonai agents.yaml
```
</Accordion>
</AccordionGroup>
## Configuration
<Tabs>
<Tab title="Create Config">
Initialize a new agents.yaml file for your project:
```bash
praisonai --init "Create a movie script about AI"
```
This will create an `agents.yaml` file with predefined configuration for your task.
</Tab>
<Tab title="Auto Mode">
Let PraisonAI automatically create and configure agents:
```bash
praisonai --auto "Create a movie script about AI"
```
This mode will analyze your task and set up appropriate agents automatically.
</Tab>
</Tabs>
## Features
<CardGroup cols={2}>
<Card title="Simple Commands" icon="terminal">
Run AI tasks directly from your terminal with simple commands.
</Card>
<Card title="LLM Options" icon="wand-magic-sparkles">
Choose from different LLM models for your specific needs.
</Card>
<Card title="YAML Support" icon="file-code">
Use YAML files for complex agent configurations and workflows.
</Card>
<Card title="Auto Configuration" icon="robot">
Automatic agent setup based on task requirements.
</Card>
</CardGroup>
## Next Steps
<CardGroup>
<Card title="YAML Configuration" icon="file-code" href="/config">
Learn more about YAML configuration options
</Card>
<Card title="API Reference" icon="code" href="/api-reference">
View the complete API documentation
</Card>
</CardGroup>
+298
View File
@@ -0,0 +1,298 @@
---
title: "Generate Synthetic Reasoning Data Agents"
sidebarTitle: "Generate Reasoning Data"
description: "Learn how to generate chain-of-thought reasoning data using PraisonAI Agents."
icon: "brain"
---
```mermaid
flowchart TD
Start[Start] --> Generator[Question Answer Generator Agent]
Generator --> Evaluator[Evaluator Agent]
Evaluator --> COT[Reasoning Steps / COT Generator Agent]
COT --> COT
COT --> Upload[HuggingFace Uploader Agent]
Upload --> End[End]
style Start fill:#8B0000,color:#fff
style Generator fill:#2E8B57,color:#fff
style Evaluator fill:#2E8B57,color:#fff
style COT fill:#2E8B57,color:#fff
style Upload fill:#2E8B57,color:#fff
style End fill:#8B0000,color:#fff
```
## What is Chain-of-Thought Generation?
Chain-of-Thought (CoT) Generation is a process where AI agents create detailed, step-by-step reasoning paths for solving problems. This involves generating questions, evaluating them, producing detailed solution steps, and making the data available for training and analysis.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install "praisonaiagents[llm]" datasets huggingface-hub pandas
```
</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
export HF_TOKEN=your_huggingface_token_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import cot_save, cot_upload_to_huggingface
from pydantic import BaseModel
import os
# Define Pydantic model for structured output
class DecisionModel(BaseModel):
response: str
decision: str
def write_csv(file_path, data):
"""Write data to CSV file."""
if not os.path.exists(file_path):
with open(file_path, 'w') as file:
file.write(data + '\n')
else:
with open(file_path, 'a') as file:
file.write(data + '\n')
return f"Data appended to {file_path}"
def count_questions(file_path):
"""Count lines in file."""
with open(file_path, 'r') as file:
return sum(1 for _ in file)
# Create specialized agents
qa_generator = Agent(
name="Generator",
role="Question Creator",
goal="Create challenging math and logic questions",
backstory="Expert in educational content creation",
llm="gpt-4o-mini",
tools=[write_csv, count_questions]
)
total_questions_evaluator = Agent(
name="TotalQuestionsEvaluator",
role="Total Questions Evaluator",
goal="Evaluate the total number of questions in qa_pairs.csv file",
backstory="Expert in evaluating the total number of questions in a file",
llm="gpt-4o-mini",
tools=[count_questions],
verbose=False
)
cot_generator = Agent(
name="COTGenerator",
role="Chain of Thought Specialist",
goal="Generate and manage chain of thought solutions for Q&A pairs",
backstory="Expert in breaking down problems and generating detailed solution steps",
tools=[cot_save],
llm="gpt-4o-mini",
verbose=False
)
upload_to_huggingface = Agent(
name="UploadToHuggingface",
role="Upload to Huggingface",
goal="Upload the generated chain of thought solutions to a Huggingface dataset",
backstory="Expert in saving data to Huggingface",
tools=[cot_upload_to_huggingface],
llm="gpt-4o-mini",
verbose=False
)
# Define tasks with workflow
generate_task = Task(
description="""Generate question and answer in csv format without headers: question, answer and append to qa_pairs.csv file
generate 10 unique questions and answers and don't repeat on the same question and answer. Reponse with 'done' when done
with append mode as 'a'
Example question and answer:
question, answer
What is the sum of numbers from 1 to 10?, 55
Number of r's in the word strawberry, 3
""",
expected_output="append to qa_pairs.csv file with questions and answers and move to next task",
agent=qa_generator,
name="generate_task",
is_start=True,
next_tasks=["evaluate_total_questions"],
task_type="decision",
condition={
"more": "generate_task",
"done": "evaluate_total_questions"
}
)
evaluate_total_questions_task = Task(
description="Evaluate the total number of questions in qa_pairs.csv file is 1",
expected_output="Total number of questions in qa_pairs.csv file",
agent=total_questions_evaluator,
task_type="decision",
name="evaluate_total_questions",
condition={
"more": "generate_task",
"done": "generate_cot"
}
)
generate_cot_task = Task(
name="generate_cot",
description="""Generate chain of thought solutions for each question in the input file.
Save to cot_solutions.csv file
Don't generate chain of thought solutions again after receiving the response from Tool Call
After calling the tool, respond with a JSON object:
{
"response": "done",
"decision": "done"
}
""",
expected_output="done",
agent=cot_generator,
input_file="qa_pairs.csv",
task_type="loop",
next_tasks=["upload_to_huggingface"],
condition={
"done": ["upload_to_huggingface"],
"exit": [],
},
output_pydantic=DecisionModel # Use Pydantic model for output validation
)
upload_to_huggingface_task = Task(
name="upload_to_huggingface",
description="""Upload to Huggingface:
1. Save to cot_solutions.csv
2. Upload to mervinpraison/cot-dataset""",
expected_output="Dataset published successfully",
agent=upload_to_huggingface,
tools=[cot_upload_to_huggingface]
)
# Initialize workflow
agents = PraisonAIAgents(
agents=[qa_generator, total_questions_evaluator, cot_generator, upload_to_huggingface],
tasks=[generate_task, evaluate_total_questions_task, generate_cot_task, upload_to_huggingface_task],
process="workflow",
max_iter=30,
verbose=False
)
agents.start()
```
</Step>
<Step title="Run the application">
Execute the Python script to start generating chain-of-thought data:
```bash
python app.py
```
</Step>
</Steps>
## Features
<CardGroup cols={2}>
<Card title="Question Generation" icon="question">
Create challenging math and logic questions with answers.
</Card>
<Card title="Question Evaluation" icon="check-double">
Evaluate and validate generated questions for quality.
</Card>
<Card title="CoT Solutions" icon="diagram-project">
Generate detailed chain-of-thought solutions for each question.
</Card>
<Card title="Data Management" icon="database">
Save and manage generated data in structured formats.
</Card>
<Card title="HuggingFace Integration" icon="cloud-arrow-up">
Upload datasets directly to HuggingFace for sharing.
</Card>
</CardGroup>
## Understanding the Workflow
<AccordionGroup>
<Accordion title="Key Components">
<CardGroup cols={2}>
<Card title="Question Generator" icon="robot">
Creates unique math and logic questions with answers. Uses `write_csv` and `count_questions` tools.
</Card>
<Card title="Questions Evaluator" icon="magnifying-glass-chart">
Validates the total number of generated questions. Uses `count_questions` tool.
</Card>
<Card title="CoT Generator" icon="diagram-project">
Produces detailed step-by-step solutions. Uses `cot_save` tool for solution management.
</Card>
<Card title="HuggingFace Uploader" icon="cloud-arrow-up">
Publishes datasets to HuggingFace. Uses `cot_upload_to_huggingface` tool.
</Card>
</CardGroup>
</Accordion>
<Accordion title="Task Types and Flow Control">
<Tabs>
<Tab title="Decision Tasks">
Used in question generation and evaluation phases.
```python Decision Task Example
generate_task = Task(
task_type="decision",
condition={
"more": "generate_task",
"done": "evaluate_total_questions"
}
)
```
<Note>
Conditions determine whether to continue generating or move forward. The task can loop back to itself or proceed to the next task.
</Note>
</Tab>
<Tab title="Loop Tasks">
Used in Chain-of-Thought generation phase.
```python Loop Task Example
generate_cot_task = Task(
task_type="loop",
input_file="qa_pairs.csv",
output_pydantic=DecisionModel
)
```
<Warning>
Always use Pydantic models for output validation in loop tasks to ensure data consistency.
</Warning>
</Tab>
</Tabs>
<Info>
Each task type serves a specific purpose in the workflow:
- **Decision Tasks**: Control flow and branching logic
- **Loop Tasks**: Process data iteratively with validation
</Info>
</Accordion>
</AccordionGroup>
## 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>
+126
View File
@@ -0,0 +1,126 @@
---
title: "Image Generation AI Agents"
sidebarTitle: "Image Generation"
description: "Generate high-quality images using PraisonAI Image Agents with both synchronous and asynchronous capabilities."
icon: "image"
---
```mermaid
flowchart LR
In[Start] --> Process[Image Description]
Process --> Agent[Image Agent]
Agent --> Out[Image URL]
style In fill:#8B0000,color:#fff
style Process fill:#2E8B57,color:#fff
style Agent fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
Image Generation in PraisonAI allows you to create high-quality images using natural language descriptions. The Image Agent supports both synchronous and asynchronous operations, making it flexible for various use cases.
## Quick Start
<Tabs>
<Tab title="Code">
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package with LLM support:
```bash
pip install "praisonaiagents[llm]"
```
</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 Agent">
Create a new file `image_gen.py` with the basic setup:
```python
from praisonaiagents.agent.image_agent import ImageAgent
# Create an image agent
agent = ImageAgent(
llm="dall-e-3",
verbose=True
)
# Generate an image
result = agent.chat("A cute baby sea otter playing with a laptop")
print("Image generation result:", result)
```
</Step>
</Steps>
</Tab>
<Tab title="Async">
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package with LLM support:
```bash
pip install "praisonaiagents[llm]"
```
</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 Async Agent">
Create a new file `image_gen_async.py` with the async setup:
```python
import asyncio
from praisonaiagents import ImageAgent
async def main():
agent = ImageAgent(
name="ImageCreator",
llm="dall-e-3",
style="natural"
)
result = await agent.achat("A cute baby sea otter playing with a laptop")
print(f"Image generation result: {result}")
if __name__ == "__main__":
asyncio.run(main())
```
</Step>
</Steps>
</Tab>
</Tabs>
## Features
<CardGroup cols={2}>
<Card title="DALL-E Integration" icon="image">
Seamless integration with DALL-E for high-quality image generation.
</Card>
<Card title="Async Support" icon="bolt">
Asynchronous operations for better performance in concurrent environments.
</Card>
<Card title="Natural Style" icon="paintbrush">
Generate images with natural, realistic styling options.
</Card>
<Card title="Verbose Mode" icon="message">
Detailed output logging for better debugging and monitoring.
</Card>
</CardGroup>
## Next Steps
<CardGroup>
<Card title="Agents Overview" icon="robot" href="/agents">
Learn more about PraisonAI Agents and their capabilities
</Card>
<Card title="API Reference" icon="code" href="/api-reference">
View the complete API documentation
</Card>
</CardGroup>
+137
View File
@@ -0,0 +1,137 @@
---
title: "Reasoning Extract Agents"
description: "Learn how to create AI agents that can perform step-by-step reasoning and extract information"
icon: "brain-circuit"
---
```mermaid
flowchart LR
In[Input] --> RA[("Reasoning Agent")]
RA --> Steps[Reasoning Steps]
Steps --> SA[("Small Agent")]
SA --> Out[Output]
style In fill:#8B0000,color:#fff
style RA fill:#2E8B57,color:#fff,shape:circle
style Steps fill:#4169E1,color:#fff
style SA fill:#2E8B57,color:#fff,shape:circle
style Out fill:#8B0000,color:#fff
```
A workflow where a reasoning agent breaks down complex problems into steps, followed by a smaller agent that processes these steps to provide concise answers.
## Prerequisites
<Steps>
<Step title="Install Package">
Install required packages:
```bash
pip install "praisonaiagents[llm]"
```
<Note>
praisonaiagents[llm] includes all necessary dependencies for reasoning agents
</Note>
</Step>
<Step title="Set API Key">
Configure your API key:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create File">
Create a new file called `app.py` and add the following code:
</Step>
<Step title="Run Application">
Execute the script:
```bash
python app.py
```
</Step>
</Steps>
## Code
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
reasoning_agent = Agent(
role="Helpful Assistant",
reasoning_steps=True,
llm="deepseek/deepseek-reasoner"
)
small_agent = Agent(
role="Helpful Assistant",
llm="gpt-3.5-turbo"
)
reasoning_task = Task(
description="How many r's in the word 'Strawberry'?",
agent=reasoning_agent
)
small_task = Task(
description="With the provided reasoning tell me how many r's in the word 'Strawberry'?",
agent=small_agent
)
agents = PraisonAIAgents(
agents=[reasoning_agent, small_agent],
tasks=[reasoning_task, small_task]
)
agents.start()
```
## Features
<CardGroup cols={2}>
<Card title="Step-by-Step Reasoning" icon="list-check">
Break down complex problems into logical steps.
</Card>
<Card title="Multi-Agent Collaboration" icon="users">
Combine reasoning and processing agents.
</Card>
<Card title="Flexible Models" icon="arrows-split-up-and-left">
Use different models for reasoning and processing.
</Card>
<Card title="Task Chaining" icon="link">
Connect reasoning output to processing tasks.
</Card>
</CardGroup>
## Understanding Reasoning Agents
<Card title="What are Reasoning Agents?" icon="question">
Reasoning agents enable:
- Detailed step-by-step analysis
- Logical problem decomposition
- Clear reasoning paths
- Enhanced decision making
</Card>
## Troubleshooting
<CardGroup cols={2}>
<Card title="Reasoning Issues" icon="triangle-exclamation">
If reasoning steps aren't clear:
- Check reasoning_steps parameter
- Verify model compatibility
- Review task descriptions
</Card>
<Card title="Agent Communication" icon="messages">
If agents aren't coordinating:
- Ensure task order is correct
- Check task dependencies
- Verify agent configurations
</Card>
</CardGroup>
<Note>
The reasoning agent uses a specialized model (deepseek-reasoner) optimized for step-by-step analysis, while the small agent can use a more general-purpose model for processing the reasoning output.
</Note>
+442 -98
View File
@@ -1,7 +1,7 @@
---
title: "Praison AI"
sidebarTitle: "Home"
description: "Comprehensive guide to PraisonAI - an AI Agents Framework with Self Reflection, combining PraisonAI Agents, AutoGen, and CrewAI for building multi-agent LLM systems"
description: "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."
icon: "house"
openGraph:
url: "/"
@@ -66,24 +66,53 @@ seo:
Internet search using Crawl4AI and Tavily
</Card>
</CardGroup>
<br />
<div className="relative w-full aspect-video overflow-hidden rounded-lg shadow-lg mb-8">
<iframe
className="absolute top-0 left-0 w-full h-full border-0"
src="https://www.youtube.com/embed/Fn1lQjC0GO0"
title="YouTube video player"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
style={{
maxWidth: '100vw',
margin: '0 auto'
}}
></iframe>
</div>
## Installation Options
## Install
<Tabs>
<Tab title="Code">
<Steps>
<Step title="Install Package">
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Create File">
Create `app.py` file
## Code Example
<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="Run Script">
```bash
python app.py
```
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Tip>
PraisonAI combines PraisonAI Agents, AutoGen, and CrewAI into a low-code solution for building and managing multi-agent LLM systems, focusing on simplicity, customization, and efficient human-agent collaboration.
@@ -109,11 +138,11 @@ seo:
</Step>
</Steps>
</Tab>
<Tab title="Code">
<Tab title="JavaScript">
<Steps>
<Step title="Install Package">
```bash
pip install praisonaiagents
npm install praisonai
```
</Step>
<Step title="Set API Key">
@@ -122,102 +151,390 @@ seo:
```
</Step>
<Step title="Create File">
Create `app.py` file
Create `app.js` file
## Code Example
<CodeGroup>
```python Basic
from praisonaiagents import Agent, Task, PraisonAIAgents
```javascript Single Agent
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');
```
# 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"
)
```javascript Multi Agents
const { Agent, PraisonAIAgents } = require('praisonai');
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
const researchAgent = new Agent({ instructions: 'Research about AI' });
const summariseAgent = new Agent({ instructions: 'Summarise research agent\'s findings' });
# 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()
```
const agents = new PraisonAIAgents({ agents: [researchAgent, summariseAgent] });
agents.start();
```
</CodeGroup>
</Step>
<Step title="Run Script">
```bash
python app.py
node app.js
```
</Step>
</Steps>
</Tab>
</Tabs>
## 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
```
<br />
<div className="relative w-full aspect-video overflow-hidden rounded-lg shadow-lg mb-8">
<iframe
className="absolute top-0 left-0 w-full h-full border-0"
src="https://www.youtube.com/embed/Fn1lQjC0GO0"
title="YouTube video player"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
style={{
maxWidth: '100vw',
margin: '0 auto'
}}
></iframe>
</div>
## Integration Options
<AccordionGroup>
@@ -338,4 +655,31 @@ seo:
<div className="hover:opacity-80 transition-opacity">
<img src="https://img.shields.io/github/forks/MervinPraison/PraisonAI?style=social" alt="GitHub Forks" />
</div>
</div>
</div>
## 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) |
| Firecrawl Integration | [![Firecrawl](https://img.youtube.com/vi/UoqUDcLcOYo/0.jpg)](https://www.youtube.com/watch?v=UoqUDcLcOYo) |
| User Interface | [![UI](https://img.youtube.com/vi/tg-ZjNl3OCg/0.jpg)](https://www.youtube.com/watch?v=tg-ZjNl3OCg) |
| Crawl4AI Integration | [![Crawl4AI](https://img.youtube.com/vi/KAvuVUh0XU8/0.jpg)](https://www.youtube.com/watch?v=KAvuVUh0XU8) |
| Chat Interface | [![Chat](https://img.youtube.com/vi/sw3uDqn2h1Y/0.jpg)](https://www.youtube.com/watch?v=sw3uDqn2h1Y) |
| Code Interface | [![Code](https://img.youtube.com/vi/_5jQayO-MQY/0.jpg)](https://www.youtube.com/watch?v=_5jQayO-MQY) |
| Mem0 Integration | [![Mem0](https://img.youtube.com/vi/KIGSgRxf1cY/0.jpg)](https://www.youtube.com/watch?v=KIGSgRxf1cY) |
| 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) |
+19
View File
@@ -11,6 +11,9 @@ pip install praisonaiagents
```bash No Code
pip install praisonai
```
```bash JavaScript
npm install praisonai
```
</RequestExample>
<Note>
@@ -90,6 +93,22 @@ Follow these steps to set up PraisonAI in your development environment.
</Step>
</Steps>
</Tab>
<Tab title="JavaScript">
<Steps>
<Step title="Install PraisonAI">
Install the PraisonAI package:
```bash
npm 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_openai_key
```
</Step>
</Steps>
</Tab>
</Tabs>
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
+141 -121
View File
@@ -89,143 +89,163 @@ graph LR
## Getting Started is Easy
<Tabs>
<Tab title="Code">
<Steps>
<Steps>
<Step title="Install Package">
Install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
```bash
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="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 Agents">
Create `app.py`:
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent, PraisonAIAgents
<Step title="Create Agent">
Create `app.py`:
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create a simple agent
summarise_agent = Agent(instructions="Summarise Photosynthesis")
# 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"
)
# Run the agent
agents = PraisonAIAgents(agents=[summarise_agent])
agents.start()
```
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
```python Multiple Agents
from praisonaiagents import Agent, PraisonAIAgents
# Run the agents
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
verbose=False
)
# Create agents with specific roles
diet_agent = Agent(
instructions="Give me 5 healthy food recipes",
)
result = agents.start()
```
blog_agent = Agent(
instructions="Write a blog post about the food recipes",
)
```python Multiple Agents
from praisonaiagents import Agent, Task, PraisonAIAgents
# Run multiple agents
agents = PraisonAIAgents(agents=[diet_agent, blog_agent])
agents.start()
```
</CodeGroup>
</Step>
# 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
)
<Step title="Run Agents">
Execute your script:
```bash
python app.py
```
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="Start Agents">
Execute your script:
```bash Terminal
python app.py
```
</Step>
</Steps>
</Tab>
You'll see:
- Agent initialization
- Task execution progress
- Final results
<Tip>
You have successfully CreatedAI Agents and made them work for you!
</Tip>
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install Package">
Install the No Code PraisonAI Package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Install PraisonAI">
Install the PraisonAI package:
```bash
pip install praisonai
```
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=your_openai_key
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```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 Config">
Create `agents.yaml`:
<Step title="Start AutoAgents">
Run your AutoAgents:
```bash
praisonai --auto "Create a movie script about a robot in Mars"
```
</Step>
<CodeGroup>
```yaml Single Agent
roles:
summarise_agent:
instructions: Summarise Photosynthesis
```
```yaml Multiple Agents
roles:
diet_agent:
instructions: Give me 5 healthy food recipes
blog_agent:
instructions: Write a blog post about the food recipes
```
</CodeGroup>
<Note>
You can automatically create `agents.yaml` using:
```bash
praisonai --init "your task description"
```
</Note>
</Step>
<Step title="Run Agents">
Execute your config:
```bash
praisonai agents.yaml
```
</Step>
</Steps>
</Tab>
<Tab title="JavaScript">
<Steps>
<Step title="Install Package">
```bash
npm install praisonai
```
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Create File">
Create `app.js` file
## Code Example
<CodeGroup>
```javascript Single Agent
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');
```
```javascript Multi Agents
const { Agent, PraisonAIAgents } = require('praisonai');
const researchAgent = new Agent({ instructions: 'Research about AI' });
const summariseAgent = new Agent({ instructions: 'Summarise research agent\'s findings' });
const agents = new PraisonAIAgents({ agents: [researchAgent, summariseAgent] });
agents.start();
```
</CodeGroup>
</Step>
<Step title="Run Script">
```bash
node app.js
```
</Step>
</Steps>
</Tab>
</Tabs>
+38
View File
@@ -0,0 +1,38 @@
---
title: "Development Setup"
sidebarTitle: "Development"
description: "Set up your development environment for PraisonAI JavaScript framework"
icon: "code"
---
## Development Setup
<Steps>
<Step title="Clone Repository">
```bash
git clone https://github.com/MervinPraison/PraisonAI.git
cd src/praisonai-ts
```
</Step>
<Step title="Install Dependencies">
```bash
npm install
```
</Step>
<Step title="Build Package">
```bash
npm run build
```
</Step>
</Steps>
## Package Structure
```
src/
├── agent/ # Agent-related interfaces and implementations
├── task/ # Task management and execution
├── utils/ # Utility functions and helpers
└── types/ # TypeScript type definitions
+214
View File
@@ -0,0 +1,214 @@
---
title: "JavaScript AI Agents Framework"
sidebarTitle: "JavaScript Agents"
description: "A production-ready Multi AI Agents framework for JavaScript"
icon: "js"
---
PraisonAI is a production-ready Multi AI Agents framework for JavaScript, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. It provides a low-code solution to streamline the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
```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
```
<Tabs>
<Tab title="JavaScript">
<Steps>
<Step title="Install Package">
<CodeGroup>
```bash npm
npm install praisonai
```
```bash yarn
yarn add praisonai
```
</CodeGroup>
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Create File">
Create `app.js` file
## Code Example
<CodeGroup>
```javascript Single Agent
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');
```
```javascript Multi Agents
const { Agent, PraisonAIAgents } = require('praisonai');
const researchAgent = new Agent({ instructions: 'Research about AI' });
const summariseAgent = new Agent({ instructions: 'Summarise research agent\'s findings' });
const agents = new PraisonAIAgents({ agents: [researchAgent, summariseAgent] });
agents.start();
```
</CodeGroup>
</Step>
<Step title="Run Script">
```bash
node app.js
```
</Step>
</Steps>
</Tab>
</Tabs>
## Usage Examples
<AccordionGroup>
<Accordion title="Single Agent Example" icon="user" defaultOpen>
Create and run a single agent to perform a specific task:
```javascript
const { Agent } = require('praisonai');
// Create a simple science explainer agent
const agent = new Agent({
instructions: "You are a science expert who explains complex phenomena in simple terms.",
name: "ScienceExplainer",
verbose: true
});
// Ask a question
agent.start("Why is the sky blue?")
.then(response => {
console.log('\nExplanation:');
console.log(response);
})
.catch(error => console.error('Error:', error));
```
</Accordion>
<Accordion title="Multi-Agent Example" icon="users" defaultOpen>
Create and run multiple agents working together:
```javascript
const { PraisonAIAgents, Agent } = require('praisonai');
// Create a story agent and a summary agent
const storyAgent = new Agent({
instructions: "You are a creative storyteller. Create engaging stories.",
name: "Storyteller"
});
const summaryAgent = new Agent({
instructions: "You summarize stories into brief, engaging summaries.",
name: "Summarizer"
});
// Create multi-agent system
const agents = new PraisonAIAgents({
agents: [storyAgent, summaryAgent],
tasks: [
"Create a short story about a magical forest",
"Summarize the story in 2 sentences"
]
});
// Run the agents
agents.start()
.then(responses => {
console.log('\nStory:');
console.log(responses[0]);
console.log('\nSummary:');
console.log(responses[1]);
})
.catch(error => console.error('Error:', error));
```
</Accordion>
<Accordion title="Task-Based Agent Example" icon="list-check" defaultOpen>
Create agents with specific tasks and dependencies:
```javascript
const { Agent, Task } = require('praisonai');
// Create a task-based agent
const agent = new Agent({
name: "TaskMaster",
role: "Assistant",
goal: "Complete tasks efficiently",
backstory: "You are an AI assistant that helps complete tasks step by step."
});
// Create a task with dependencies
const mainTask = new Task({
name: "Write Blog Post",
description: "Write a blog post about artificial intelligence",
expected_output: "A complete blog post",
dependencies: []
});
// Execute the task
agent.execute(mainTask)
.then(response => {
console.log('\nBlog Post:');
console.log(response);
})
.catch(error => console.error('Error:', error));
```
</Accordion>
</AccordionGroup>
## Running the Examples
<Steps>
<Step title="Set Environment Variables">
```bash
export OPENAI_API_KEY='your-api-key'
```
</Step>
<Step title="Create Example File">
Create a new JavaScript file (e.g., `app.js`) with any of the above examples.
</Step>
<Step title="Run the Example">
```bash
node app.js
```
</Step>
</Steps>
+251
View File
@@ -0,0 +1,251 @@
---
title: "Node.js AI Agents Framework"
sidebarTitle: "Node.js Agents"
description: "A production-ready Multi AI Agents framework for Node.js"
icon: "node-js"
---
PraisonAI is a production-ready Multi AI Agents framework for Node.js, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. It provides a low-code solution to streamline the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
```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
```
<Tabs>
<Tab title="Node.js">
<Steps>
<Step title="Install Package">
<CodeGroup>
```bash npm
npm install praisonai
```
```bash yarn
yarn add praisonai
```
</CodeGroup>
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Create File">
Create `app.js` file
## Code Example
<CodeGroup>
```javascript Single Agent
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');
```
```javascript Multi Agents
const { Agent, PraisonAIAgents } = require('praisonai');
const researchAgent = new Agent({ instructions: 'Research about AI' });
const summariseAgent = new Agent({ instructions: 'Summarise research agent\'s findings' });
const agents = new PraisonAIAgents({ agents: [researchAgent, summariseAgent] });
agents.start();
```
</CodeGroup>
</Step>
<Step title="Run Script">
```bash
node app.js
```
</Step>
</Steps>
</Tab>
</Tabs>
## Usage Examples
<AccordionGroup>
<Accordion title="Single Agent Example" icon="user" defaultOpen>
Create and run a single agent to perform a specific task:
```typescript
import { Agent } from 'praisonai';
// Single agent example - Science Explainer
const agent = new Agent({
instructions: `You are a science expert who explains complex phenomena in simple terms.
Provide clear, accurate, and easy-to-understand explanations.`,
name: "ScienceExplainer",
verbose: true
});
agent.start("Why is the sky blue?")
.then(response => {
console.log('\nExplanation:');
console.log(response);
})
.catch(error => {
console.error('Error:', error);
});
```
</Accordion>
<Accordion title="Multi-Agent Example" icon="users" defaultOpen>
Create and run multiple agents working together:
```typescript
import { Agent, PraisonAIAgents } from 'praisonai';
// Create story agent
const storyAgent = new Agent({
instructions: "You are a storyteller. Write a very short story (2-3 sentences) about a given topic.",
name: "StoryAgent",
verbose: true
});
// Create summary agent
const summaryAgent = new Agent({
instructions: "You are an editor. Create a one-sentence summary of the given story.",
name: "SummaryAgent",
verbose: true
});
// Create and start agents
const agents = new PraisonAIAgents({
agents: [storyAgent, summaryAgent],
tasks: [
"Write a short story about a cat",
"{previous_result}" // This will be replaced with the story
],
verbose: true
});
agents.start()
.then(results => {
console.log('\nStory:', results[0]);
console.log('\nSummary:', results[1]);
})
.catch(error => console.error('Error:', error));
```
</Accordion>
<Accordion title="Task-Based Agent Example" icon="list-check" defaultOpen>
Create agents with specific tasks and dependencies:
```typescript
import { Agent, PraisonAIAgents } from 'praisonai';
// Create recipe agent
const recipeAgent = new Agent({
instructions: `You are a professional chef and nutritionist. Create 5 healthy food recipes that are both nutritious and delicious.
Each recipe should include:
1. Recipe name
2. List of ingredients with quantities
3. Step-by-step cooking instructions
4. Nutritional information
5. Health benefits
Format your response in markdown.`,
name: "RecipeAgent",
verbose: true
});
// Create blog agent
const blogAgent = new Agent({
instructions: `You are a food and health blogger. Write an engaging blog post about the provided recipes.
The blog post should:
1. Have an engaging title
2. Include an introduction about healthy eating
3. Discuss each recipe and its unique health benefits
4. Include tips for meal planning and preparation
5. End with a conclusion encouraging healthy eating habits
Here are the recipes to write about:
{previous_result}
Format your response in markdown.`,
name: "BlogAgent",
verbose: true
});
// Create PraisonAIAgents instance with tasks
const agents = new PraisonAIAgents({
agents: [recipeAgent, blogAgent],
tasks: [
"Create 5 healthy and delicious recipes",
"Write a blog post about the recipes"
],
verbose: true
});
// Start the agents
agents.start()
.then(results => {
console.log('\nFinal Results:');
console.log('\nRecipe Task Results:');
console.log(results[0]);
console.log('\nBlog Task Results:');
console.log(results[1]);
})
.catch(error => {
console.error('Error:', error);
});
```
</Accordion>
</AccordionGroup>
## Running the Examples
<Steps>
<Step title="Set Environment Variables">
```bash
export OPENAI_API_KEY='your-api-key'
```
</Step>
<Step title="Create Example File">
Create a new TypeScript file (e.g., `app.ts`) with any of the above examples.
</Step>
<Step title="Run the Example">
```bash
npx ts-node app.ts
```
</Step>
</Steps>
+198
View File
@@ -0,0 +1,198 @@
---
title: "TypeScript Async AI Agents"
sidebarTitle: "TypeScript Async"
description: "A production-ready Multi AI Agents framework for TypeScript Async"
icon: "rotate"
---
PraisonAI is a production-ready Multi AI Agents framework for TypeScript Async, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. It provides a low-code solution to streamline the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
## Installation
<CodeGroup>
```bash npm
npm install praisonai
```
```bash yarn
yarn add praisonai
```
</CodeGroup>
## Usage Examples
<AccordionGroup>
<Accordion title="Single Agent Example" icon="user" defaultOpen>
Create and run a single agent to perform a specific task:
```typescript
import { Agent, PraisonAIAgents } from 'praisonai';
async function main() {
// Create a simple agent (no task specified)
const agent = new Agent({
name: "BiologyExpert",
instructions: "Explain the process of photosynthesis in detail.",
verbose: true
});
// Run the agent
const praisonAI = new PraisonAIAgents({
agents: [agent],
tasks: ["Explain the process of photosynthesis in detail."],
verbose: true
});
try {
console.log('Starting single agent example...');
const results = await praisonAI.start();
console.log('\nFinal Results:', results);
} catch (error) {
console.error('Error:', error);
}
}
main();
```
</Accordion>
<Accordion title="Multi-Agent Example" icon="users" defaultOpen>
Create and run multiple agents working together:
```typescript
import { Agent, PraisonAIAgents } from 'praisonai';
async function main() {
// Create multiple agents with different roles
const researchAgent = new Agent({
name: "ResearchAgent",
instructions: "Research and provide detailed information about renewable energy sources.",
verbose: true
});
const summaryAgent = new Agent({
name: "SummaryAgent",
instructions: "Create a concise summary of the research findings about renewable energy sources. Use {previous_result} as input.",
verbose: true
});
const recommendationAgent = new Agent({
name: "RecommendationAgent",
instructions: "Based on the summary in {previous_result}, provide specific recommendations for implementing renewable energy solutions.",
verbose: true
});
// Run the agents in sequence
const praisonAI = new PraisonAIAgents({
agents: [researchAgent, summaryAgent, recommendationAgent],
tasks: [
"Research and analyze current renewable energy technologies and their implementation.",
"Summarize the key findings from the research.",
"Provide actionable recommendations based on the summary."
],
verbose: true
});
try {
console.log('Starting multi-agent example...');
const results = await praisonAI.start();
console.log('\nFinal Results:', results);
} catch (error) {
console.error('Error:', error);
}
}
main();
```
</Accordion>
<Accordion title="Task-Based Agent Example" icon="list-check" defaultOpen>
Create agents with specific tasks and dependencies:
```typescript
import { Agent, Task, PraisonAIAgents } from 'praisonai';
async function main() {
// Create agents first
const dietAgent = new Agent({
name: "DietAgent",
role: "Nutrition Expert",
goal: "Create healthy and delicious recipes",
backstory: "You are a certified nutritionist with years of experience in creating balanced meal plans.",
verbose: true,
instructions: `You are a professional chef and nutritionist. Create 5 healthy food recipes that are both nutritious and delicious.
Each recipe should include:
1. Recipe name
2. List of ingredients with quantities
3. Step-by-step cooking instructions
4. Nutritional information
5. Health benefits
Format your response in markdown.`
});
const blogAgent = new Agent({
name: "BlogAgent",
role: "Food Blogger",
goal: "Write engaging blog posts about food and recipes",
backstory: "You are a successful food blogger known for your ability to make recipes sound delicious and approachable.",
verbose: true,
instructions: `You are a food and health blogger. Write an engaging blog post about the provided recipes.
The blog post should:
1. Have an engaging title
2. Include an introduction about healthy eating`
});
// Create tasks
const createRecipesTask = new Task({
name: "Create Recipes",
description: "Create 5 healthy and delicious recipes",
agent: dietAgent
});
const writeBlogTask = new Task({
name: "Write Blog",
description: "Write a blog post about the recipes",
agent: blogAgent,
dependencies: [createRecipesTask] // This task depends on the recipes being created first
});
// Run the tasks
const praisonAI = new PraisonAIAgents({
tasks: [createRecipesTask, writeBlogTask],
verbose: true
});
try {
console.log('Starting task-based example...');
const results = await praisonAI.start();
console.log('\nFinal Results:', results);
} catch (error) {
console.error('Error:', error);
}
}
main();
```
</Accordion>
</AccordionGroup>
## Running the Examples
<Steps>
<Step title="Set Environment Variables">
```bash
export OPENAI_API_KEY='your-api-key'
```
</Step>
<Step title="Create Example File">
Create a new TypeScript file (e.g., `app.ts`) with any of the above examples.
</Step>
<Step title="Run the Example">
```bash
npx ts-node app.ts
```
</Step>
</Steps>
+266
View File
@@ -0,0 +1,266 @@
---
title: "TypeScript AI Agents Framework"
sidebarTitle: "TypeScript Agents"
description: "A production-ready Multi AI Agents framework for TypeScript"
icon: "scroll"
---
PraisonAI is a production-ready Multi AI Agents framework for TypeScript, designed to create AI Agents to automate and solve problems ranging from simple tasks to complex challenges. It provides a low-code solution to streamline the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
```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
```
<Tabs>
<Tab title="TypeScript">
<Steps>
<Step title="Install Package">
<CodeGroup>
```bash npm
npm install praisonai
```
```bash yarn
yarn add praisonai
```
</CodeGroup>
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Create File">
Create `app.ts` file
## Code Example
<CodeGroup>
```javascript Single Agent
import { Agent } from 'praisonai';
const agent = new Agent({
instructions: `You are a creative writer who writes short stories with emojis.`,
name: "StoryWriter"
});
agent.start("Write a story about a time traveler")
```
```javascript Multi Agents
import { Agent, PraisonAIAgents } from 'praisonai';
const storyAgent = new Agent({
instructions: "Generate a very short story (2-3 sentences) about artificial intelligence with emojis.",
name: "StoryAgent"
});
const summaryAgent = new Agent({
instructions: "Summarize the provided AI story in one sentence with emojis.",
name: "SummaryAgent"
});
const agents = new PraisonAIAgents({
agents: [storyAgent, summaryAgent]
});
agents.start()
```
</CodeGroup>
</Step>
<Step title="Run Script">
```bash
npx ts-node app.ts
```
</Step>
</Steps>
</Tab>
</Tabs>
## Usage Examples
<AccordionGroup>
<Accordion title="Single Agent Example" icon="user" defaultOpen>
Create and run a single agent to perform a specific task:
```typescript
import { Agent } from 'praisonai';
// Single agent example - Science Explainer
const agent = new Agent({
instructions: `You are a science expert who explains complex phenomena in simple terms.
Provide clear, accurate, and easy-to-understand explanations.`,
name: "ScienceExplainer",
verbose: true
});
agent.start("Why is the sky blue?")
.then(response => {
console.log('\nExplanation:');
console.log(response);
})
.catch(error => {
console.error('Error:', error);
});
```
</Accordion>
<Accordion title="Multi-Agent Example" icon="users" defaultOpen>
Create and run multiple agents working together:
```typescript
import { Agent, PraisonAIAgents } from 'praisonai';
// Create story agent
const storyAgent = new Agent({
instructions: "You are a storyteller. Write a very short story (2-3 sentences) about a given topic.",
name: "StoryAgent",
verbose: true
});
// Create summary agent
const summaryAgent = new Agent({
instructions: "You are an editor. Create a one-sentence summary of the given story.",
name: "SummaryAgent",
verbose: true
});
// Create and start agents
const agents = new PraisonAIAgents({
agents: [storyAgent, summaryAgent],
tasks: [
"Write a short story about a cat",
"{previous_result}" // This will be replaced with the story
],
verbose: true
});
agents.start()
.then(results => {
console.log('\nStory:', results[0]);
console.log('\nSummary:', results[1]);
})
.catch(error => console.error('Error:', error));
```
</Accordion>
<Accordion title="Task-Based Agent Example" icon="list-check" defaultOpen>
Create agents with specific tasks and dependencies:
```typescript
import { Agent, PraisonAIAgents } from 'praisonai';
// Create recipe agent
const recipeAgent = new Agent({
instructions: `You are a professional chef and nutritionist. Create 5 healthy food recipes that are both nutritious and delicious.
Each recipe should include:
1. Recipe name
2. List of ingredients with quantities
3. Step-by-step cooking instructions
4. Nutritional information
5. Health benefits
Format your response in markdown.`,
name: "RecipeAgent",
verbose: true
});
// Create blog agent
const blogAgent = new Agent({
instructions: `You are a food and health blogger. Write an engaging blog post about the provided recipes.
The blog post should:
1. Have an engaging title
2. Include an introduction about healthy eating
3. Discuss each recipe and its unique health benefits
4. Include tips for meal planning and preparation
5. End with a conclusion encouraging healthy eating habits
Here are the recipes to write about:
{previous_result}
Format your response in markdown.`,
name: "BlogAgent",
verbose: true
});
// Create PraisonAIAgents instance with tasks
const agents = new PraisonAIAgents({
agents: [recipeAgent, blogAgent],
tasks: [
"Create 5 healthy and delicious recipes",
"Write a blog post about the recipes"
],
verbose: true
});
// Start the agents
agents.start()
.then(results => {
console.log('\nFinal Results:');
console.log('\nRecipe Task Results:');
console.log(results[0]);
console.log('\nBlog Task Results:');
console.log(results[1]);
})
.catch(error => {
console.error('Error:', error);
});
```
</Accordion>
</AccordionGroup>
## Running the Examples
<Steps>
<Step title="Set Environment Variables">
```bash
export OPENAI_API_KEY='your-api-key'
```
</Step>
<Step title="Create Example File">
Create a new TypeScript file (e.g., `app.ts`) with any of the above examples.
</Step>
<Step title="Run the Example">
```bash
npx ts-node app.ts
```
</Step>
</Steps>
+18
View File
@@ -74,6 +74,10 @@
{
"name": "Tools",
"url": "/tools"
},
{
"name": "JS",
"url": "/js"
}
],
"navigation": [
@@ -115,14 +119,18 @@
{
"group": "Features",
"pages": [
"features/cli",
"features/autoagents",
"features/image-generation",
"features/selfreflection",
"features/rag",
"features/reasoning-extract",
"features/reasoning",
"features/multimodal",
"features/langchain",
"features/async",
"features/mini",
"features/generate-reasoning",
"features/codeagent",
"features/mathagent",
"features/structured",
@@ -232,6 +240,16 @@
"tools/googlecalendar"
]
},
{
"group": "JavaScript",
"pages": [
"js/js",
"js/typescript",
"js/nodejs",
"js/typescript-async",
"js/development"
]
},
{
"group": "Other Features",
"pages": [
+42
View File
@@ -125,6 +125,48 @@ praisonai --init "your task description"
</Step>
</Steps>
</Tab>
<Tab title="JavaScript">
<Steps>
<Step title="Install Package">
```bash
npm install praisonai
```
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Create File">
Create `app.js` file
## Code Example
<CodeGroup>
```javascript Single Agent
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');
```
```javascript Multi Agents
const { Agent, PraisonAIAgents } = require('praisonai');
const researchAgent = new Agent({ instructions: 'Research about AI' });
const summariseAgent = new Agent({ instructions: 'Summarise research agent\'s findings' });
const agents = new PraisonAIAgents({ agents: [researchAgent, summariseAgent] });
agents.start();
```
</CodeGroup>
</Step>
<Step title="Run Script">
```bash
node app.js
```
</Step>
</Steps>
</Tab>
</Tabs>
<Note>
+142
View File
@@ -0,0 +1,142 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import cot_save, cot_upload_to_huggingface
from pydantic import BaseModel
import os
# Define Pydantic model for structured output
class DecisionModel(BaseModel):
response: str
decision: str
def write_csv(file_path, data):
"""Write data to CSV file."""
if not os.path.exists(file_path):
with open(file_path, 'w') as file:
file.write(data + '\n')
else:
with open(file_path, 'a') as file:
file.write(data + '\n')
return f"Data appended to {file_path}"
def count_questions(file_path):
"""Count lines in file."""
with open(file_path, 'r') as file:
return sum(1 for _ in file)
# Keep existing agents with minimal changes
qa_generator = Agent(
name="Generator",
role="Question Creator",
goal="Create challenging math and logic questions",
backstory="Expert in educational content creation",
llm="gpt-4o-mini",
tools=[write_csv, count_questions]
)
total_questions_evaluator = Agent(
name="TotalQuestionsEvaluator",
role="Total Questions Evaluator",
goal="Evaluate the total number of questions in qa_pairs.csv file",
backstory="Expert in evaluating the total number of questions in a file",
llm="gpt-4o-mini",
tools=[count_questions],
verbose=False
)
cot_generator = Agent(
name="COTGenerator",
role="Chain of Thought Specialist",
goal="Generate and manage chain of thought solutions for Q&A pairs",
backstory="Expert in breaking down problems and generating detailed solution steps",
tools=[cot_save],
llm="gpt-4o-mini",
verbose=False
)
upload_to_huggingface = Agent(
name="UploadToHuggingface",
role="Upload to Huggingface",
goal="Upload the generated chain of thought solutions to a Huggingface dataset",
backstory="Expert in saving data to Huggingface",
tools=[cot_upload_to_huggingface],
llm="gpt-4o-mini",
verbose=False
)
# Define tasks with workflow improvements
generate_task = Task(
description="""Generate question and answer in csv format without headers: question, answer and append to qa_pairs.csv file
generate 10 unique questions and answers and don't repeat on the same question and answer. Reponse with 'done' when done
with append mode as 'a'
Example question and answer:
question, answer
What is the sum of numbers from 1 to 10?, 55
Number of r's in the word strawberry, 3
""",
expected_output="append to qa_pairs.csv file with questions and answers and move to next task",
agent=qa_generator,
name="generate_task",
is_start=True,
next_tasks=["evaluate_total_questions"],
task_type="decision",
condition={
"more": "generate_task",
"done": "evaluate_total_questions"
}
)
evaluate_total_questions_task = Task(
description="Evaluate the total number of questions in qa_pairs.csv file is 1",
expected_output="Total number of questions in qa_pairs.csv file",
agent=total_questions_evaluator,
task_type="decision",
name="evaluate_total_questions",
condition={
"more": "generate_task",
"done": "generate_cot"
}
)
generate_cot_task = Task(
name="generate_cot",
description="""Generate chain of thought solutions for each question in the input file.
Save to cot_solutions.csv file
Don't generate chain of thought solutions again after receiving the response from Tool Call
After calling the tool, respond with a JSON object:
{
"response": "done",
"decision": "done"
}
""",
expected_output="done",
agent=cot_generator,
input_file="qa_pairs.csv",
task_type="loop",
next_tasks=["upload_to_huggingface"],
condition={
"done": ["upload_to_huggingface"],
"exit": [],
},
output_pydantic=DecisionModel # Use Pydantic model for output validation
)
upload_to_huggingface_task = Task(
name="upload_to_huggingface",
description="""Upload to Huggingface:
1. Save to cot_solutions.csv
2. Upload to mervinpraison/cot-dataset""",
expected_output="Dataset published successfully",
agent=upload_to_huggingface,
tools=[cot_upload_to_huggingface]
)
# Initialize workflow
agents = PraisonAIAgents(
agents=[qa_generator, total_questions_evaluator, cot_generator, upload_to_huggingface],
tasks=[generate_task, evaluate_total_questions_task, generate_cot_task, upload_to_huggingface_task],
process="workflow",
max_iter=30,
verbose=False
)
agents.start()
+15
View File
@@ -0,0 +1,15 @@
import asyncio
from praisonaiagents import ImageAgent
async def main():
agent = ImageAgent(
name="ImageCreator",
llm="dall-e-3",
style="natural"
)
result = await agent.achat("A cute baby sea otter playing with a laptop")
print(f"Image generation result: {result}")
if __name__ == "__main__":
asyncio.run(main())
+8
View File
@@ -0,0 +1,8 @@
from praisonaiagents.agent.image_agent import ImageAgent
# Create an image agent with normal mode
agent = ImageAgent(llm="dall-e-3")
# Generate an image
result = agent.chat("A cute baby sea otter playing with a laptop")
print("Image generation result:", result)
+1 -1
View File
@@ -3,7 +3,7 @@ class Praisonai < Formula
desc "AI tools for various AI applications"
homepage "https://github.com/MervinPraison/PraisonAI"
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/2.0.57.tar.gz"
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/2.0.65.tar.gz"
sha256 "1828fb9227d10f991522c3f24f061943a254b667196b40b1a3e4a54a8d30ce32" # Replace with actual SHA256 checksum
license "MIT"
+101 -8
View File
@@ -25,7 +25,7 @@ CALL_MODULE_AVAILABLE = False
CREWAI_AVAILABLE = False
AUTOGEN_AVAILABLE = False
PRAISONAI_AVAILABLE = False
TRAIN_AVAILABLE = False
try:
# Create necessary directories and set CHAINLIT_APP_ROOT
if "CHAINLIT_APP_ROOT" not in os.environ:
@@ -72,6 +72,12 @@ try:
except ImportError:
pass
try:
import accelerate
TRAIN_AVAILABLE = True
except ImportError:
pass
logging.basicConfig(level=os.environ.get('LOGLEVEL', 'INFO'), format='%(asctime)s - %(levelname)s - %(message)s')
logging.getLogger('alembic').setLevel(logging.ERROR)
logging.getLogger('gradio').setLevel(logging.ERROR)
@@ -140,6 +146,8 @@ class PraisonAI:
provided arguments.
"""
args = self.parse_args()
# Store args for use in handle_direct_prompt
self.args = args
invocation_cmd = "praisonai"
version_string = f"PraisonAI version {__version__}"
@@ -148,8 +156,16 @@ class PraisonAI:
if args.command:
if args.command.startswith("tests.test"): # Argument used for testing purposes
print("test")
return "test"
else:
self.agent_file = args.command
elif hasattr(args, 'direct_prompt') and args.direct_prompt:
result = self.handle_direct_prompt(args.direct_prompt)
print(result)
return result
else:
# Default to agents.yaml if no command provided
self.agent_file = "agents.yaml"
if args.deploy:
from .deploy import CloudDeployer
@@ -285,14 +301,18 @@ class PraisonAI:
"""
Parse the command-line arguments for the PraisonAI CLI.
"""
# Define special commands
special_commands = ['chat', 'code', 'call', 'realtime', 'train', 'ui']
parser = argparse.ArgumentParser(prog="praisonai", description="praisonAI command-line interface")
parser.add_argument("--framework", choices=["crewai", "autogen", "praisonai"], help="Specify the framework")
parser.add_argument("--ui", choices=["chainlit", "gradio"], help="Specify the UI framework (gradio or chainlit).")
parser.add_argument("--auto", nargs=argparse.REMAINDER, help="Enable auto mode and pass arguments for it")
parser.add_argument("--init", nargs=argparse.REMAINDER, help="Initialize agents with optional topic")
parser.add_argument("command", nargs="?", help="Command to run")
parser.add_argument("command", nargs="?", help="Command to run or direct prompt")
parser.add_argument("--deploy", action="store_true", help="Deploy the application")
parser.add_argument("--model", type=str, help="Model name")
parser.add_argument("--llm", type=str, help="LLM model to use for direct prompts")
parser.add_argument("--hf", type=str, help="Hugging Face model name")
parser.add_argument("--ollama", type=str, help="Ollama model name")
parser.add_argument("--dataset", type=str, help="Dataset name for training", default="yahma/alpaca-cleaned")
@@ -301,6 +321,7 @@ class PraisonAI:
parser.add_argument("--public", action="store_true", help="Use ngrok to expose the server publicly (only with --call)")
args, unknown_args = parser.parse_known_args()
# Handle special cases first
if unknown_args and unknown_args[0] == '-b' and unknown_args[1] == 'api:app':
args.command = 'agents.yaml'
if args.command == 'api:app' or args.command == '/app/api:app':
@@ -331,9 +352,7 @@ class PraisonAI:
call_module.main(call_args)
sys.exit(0)
# Handle special commands first
special_commands = ['chat', 'code', 'call', 'realtime', 'train', 'ui']
# Handle special commands
if args.command in special_commands:
if args.command == 'chat':
if not CHAINLIT_AVAILABLE:
@@ -380,9 +399,13 @@ class PraisonAI:
sys.exit(0)
elif args.command == 'train':
print("[red]ERROR: Train feature is not installed. Install with:[/red]")
print("\npip install \"praisonai[train]\"\n")
sys.exit(1)
if not TRAIN_AVAILABLE:
print("[red]ERROR: Train feature is not installed. Install with:[/red]")
print("\npip install \"praisonai[train]\"\n")
sys.exit(1)
package_root = os.path.dirname(os.path.abspath(__file__))
config_yaml_destination = os.path.join(os.getcwd(), 'config.yaml')
elif args.command == 'ui':
if not CHAINLIT_AVAILABLE:
@@ -402,8 +425,78 @@ class PraisonAI:
print("pip install praisonaiagents # For PraisonAIAgents\n")
sys.exit(1)
# Handle direct prompt if command is not a special command or file
if args.command and not args.command.endswith('.yaml') and args.command not in special_commands:
args.direct_prompt = args.command
args.command = None
return args
def handle_direct_prompt(self, prompt):
"""
Handle direct prompt by creating a single agent and running it.
"""
if PRAISONAI_AVAILABLE:
agent_config = {
"name": "DirectAgent",
"role": "Assistant",
"goal": "Complete the given task",
"backstory": "You are a helpful AI assistant"
}
# Add llm if specified
if hasattr(self, 'args') and self.args.llm:
agent_config["llm"] = self.args.llm
agent = PraisonAgent(**agent_config)
result = agent.start(prompt)
return ""
elif CREWAI_AVAILABLE:
agent_config = {
"name": "DirectAgent",
"role": "Assistant",
"goal": "Complete the given task",
"backstory": "You are a helpful AI assistant"
}
# Add llm if specified
if hasattr(self, 'args') and self.args.llm:
agent_config["llm"] = self.args.llm
agent = Agent(**agent_config)
task = Task(
description=prompt,
agent=agent
)
crew = Crew(
agents=[agent],
tasks=[task]
)
return crew.kickoff()
elif AUTOGEN_AVAILABLE:
config_list = self.config_list
# Add llm if specified
if hasattr(self, 'args') and self.args.llm:
config_list[0]['model'] = self.args.llm
assistant = autogen.AssistantAgent(
name="DirectAgent",
llm_config={"config_list": config_list}
)
user_proxy = autogen.UserProxyAgent(
name="UserProxy",
code_execution_config={"work_dir": "coding"}
)
user_proxy.initiate_chat(assistant, message=prompt)
return "Task completed"
else:
print("[red]ERROR: No framework is installed. Please install at least one framework:[/red]")
print("\npip install \"praisonai\\[crewai]\" # For CrewAI")
print("pip install \"praisonai\\[autogen]\" # For AutoGen")
print("pip install \"praisonai\\[crewai,autogen]\" # For both frameworks\n")
print("pip install praisonaiagents # For PraisonAIAgents\n")
sys.exit(1)
def create_chainlit_chat_interface(self):
"""
Create a Chainlit interface for the chat application.
+1 -1
View File
@@ -56,7 +56,7 @@ class CloudDeployer:
file.write("FROM python:3.11-slim\n")
file.write("WORKDIR /app\n")
file.write("COPY . .\n")
file.write("RUN pip install flask praisonai==2.0.57 gunicorn markdown\n")
file.write("RUN pip install flask praisonai==2.0.65 gunicorn markdown\n")
file.write("EXPOSE 8080\n")
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
+55 -22
View File
@@ -11,6 +11,38 @@ if [[ "$OSTYPE" == "darwin"* ]]; then
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
# Linux
MINICONDA_URL="https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh"
# Install libcurl development package if not present (Debian based)
if command -v dpkg &> /dev/null; then
if ! dpkg -s libcurl4-openssl-dev &> /dev/null; then
echo "libcurl4-openssl-dev is not installed. Installing..."
sudo apt-get update
sudo apt-get install -y libcurl4-openssl-dev
else
echo "libcurl4-openssl-dev is already installed."
fi
else
echo "Non-Debian based Linux detected. Please ensure libcurl development libraries are installed."
fi
# Check if ollama is installed and executable; if not, install it
if ! command -v ollama &> /dev/null; then
echo "Ollama is not installed. Installing Ollama..."
curl -fsSL https://ollama.com/install.sh | sh
# Generate SSH key non-interactively only if it doesn't already exist
if [ ! -f ~/.ssh/id_ed25519 ]; then
echo "Generating SSH key for Ollama..."
ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519 -q
else
echo "SSH key ~/.ssh/id_ed25519 already exists. Skipping generation."
fi
echo "Copying SSH key to /usr/share/ollama/.ollama..."
sudo cp ~/.ssh/id_ed25519 /usr/share/ollama/.ollama
else
echo "Ollama is already installed."
fi
elif [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
# Windows
MINICONDA_URL="https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe"
@@ -21,12 +53,12 @@ else
exit 1
fi
# Check if conda is already installed
# Check if conda is installed
if ! command -v conda &> /dev/null; then
echo "Conda is not installed. Installing Miniconda..."
wget $MINICONDA_URL -O ~/miniconda.sh
bash ~/miniconda.sh -b -p $HOME/miniconda
source $HOME/miniconda/bin/activate
wget "$MINICONDA_URL" -O ~/miniconda.sh
bash ~/miniconda.sh -b -p "$HOME/miniconda"
source "$HOME/miniconda/bin/activate"
conda init
else
echo "Conda is already installed."
@@ -34,39 +66,40 @@ fi
# Create and activate the Conda environment
ENV_NAME="praison_env"
if conda info --envs | grep -q $ENV_NAME; then
if conda info --envs | grep -q "$ENV_NAME"; then
echo "Environment $ENV_NAME already exists. Recreating..."
conda env remove -y -n $ENV_NAME # Remove existing environment
conda env remove -y -n "$ENV_NAME"
if [[ "$OSTYPE" == "darwin"* ]]; then
# macOS (both Intel and M1/M2)
conda create --name $ENV_NAME python=3.10 pytorch=2.3.0 -c pytorch -y
conda create --name "$ENV_NAME" python=3.10 pytorch=2.3.0 -c pytorch -y
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
# Linux
conda create --name $ENV_NAME python=3.10 pytorch=2.3.0 cudatoolkit=11.8 -c pytorch -c nvidia -y
conda create --name "$ENV_NAME" python=3.10 pytorch=2.3.0 cudatoolkit=11.8 -c pytorch -c nvidia -y
fi
# conda activate $ENV_NAME
else
echo "Creating new environment $ENV_NAME..."
if [[ "$OSTYPE" == "darwin"* ]]; then
# macOS (both Intel and M1/M2)
conda create --name $ENV_NAME python=3.10 pytorch=2.3.0 -c pytorch -y
conda create --name "$ENV_NAME" python=3.10 pytorch=2.3.0 -c pytorch -y
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
# Linux
conda create --name $ENV_NAME python=3.10 pytorch=2.3.0 cudatoolkit=11.8 -c pytorch -c nvidia -y
conda create --name "$ENV_NAME" python=3.10 pytorch=2.3.0 cudatoolkit=11.8 -c pytorch -c nvidia -y
fi
# conda activate $ENV_NAME
fi
# source $HOME/miniconda/bin/activate $ENV_NAME
# Activate the environment
source "$HOME/miniconda/bin/activate" "$ENV_NAME"
# Get full path of pip
PIP_FULL_PATH=$(conda run -n $ENV_NAME which pip)
# Install cmake via conda
echo "Installing cmake..."
conda install -y cmake
# Install other packages within the activated environment
# Use PIP_FULL_PATH to run pip commands
# Get full path of pip within the activated environment
PIP_FULL_PATH=$(conda run -n "$ENV_NAME" which pip)
# Install other packages using pip
$PIP_FULL_PATH install --upgrade pip
$PIP_FULL_PATH install "xformers==0.0.26.post1"
$PIP_FULL_PATH install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git@4e570be9ae4ced8cdc64e498125708e34942befc"
$PIP_FULL_PATH install "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git@038e6d4c8d40207a87297ab3aaf787c19b1006d1"
$PIP_FULL_PATH install --no-deps "trl<0.9.0" peft accelerate bitsandbytes
$PIP_FULL_PATH install unsloth_zoo
$PIP_FULL_PATH install cut_cross_entropy
$PIP_FULL_PATH install sentencepiece protobuf datasets huggingface_hub hf_transfer
echo "Setup completed successfully!"
+234 -136
View File
@@ -1,168 +1,281 @@
import subprocess
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script finetunes a model using Unsloth’s fast training framework.
It supports both ShareGPT and Alpaca‑style datasets by converting raw conversation
data into plain-text prompts using a chat template, then pre‑tokenizing the prompts.
Extra debug logging is added to help trace the root cause of errors.
"""
import os
import sys
import yaml
import torch
import shutil
import subprocess
from transformers import TextStreamer
from unsloth import FastLanguageModel, is_bfloat16_supported
from trl import SFTTrainer
from transformers import TrainingArguments
from datasets import load_dataset, concatenate_datasets, Dataset
from datasets import load_dataset, concatenate_datasets
from psutil import virtual_memory
from unsloth.chat_templates import standardize_sharegpt, get_chat_template
from functools import partial
class train:
#####################################
# Step 1: Formatting Raw Conversations
#####################################
def formatting_prompts_func(examples, tokenizer):
"""
Converts each example’s conversation into a single plain-text prompt.
If the example has a "conversations" field, process it as ShareGPT-style.
Otherwise, assume Alpaca-style data with "instruction", "input", and "output" fields.
"""
print("DEBUG: formatting_prompts_func() received batch with keys:", list(examples.keys()))
texts = []
# Check if the example has a "conversations" field.
if "conversations" in examples:
for convo in examples["conversations"]:
try:
formatted = tokenizer.apply_chat_template(
convo,
tokenize=False, # Return a plain string
add_generation_prompt=False
)
except Exception as e:
print(f"ERROR in apply_chat_template (conversations): {e}")
formatted = ""
# Flatten list if necessary
if isinstance(formatted, list):
formatted = formatted[0] if len(formatted) == 1 else "\n".join(formatted)
texts.append(formatted)
else:
# Assume Alpaca format: use "instruction", "input", and "output" keys.
instructions = examples.get("instruction", [])
inputs_list = examples.get("input", [])
outputs_list = examples.get("output", [])
# If any field is missing, replace with empty string.
for ins, inp, out in zip(instructions, inputs_list, outputs_list):
# Create a conversation-like structure.
convo = [
{"role": "user", "content": ins + (f"\nInput: {inp}" if inp.strip() != "" else "")},
{"role": "assistant", "content": out}
]
try:
formatted = tokenizer.apply_chat_template(
convo,
tokenize=False,
add_generation_prompt=False
)
except Exception as e:
print(f"ERROR in apply_chat_template (alpaca): {e}")
formatted = ""
if isinstance(formatted, list):
formatted = formatted[0] if len(formatted) == 1 else "\n".join(formatted)
texts.append(formatted)
if texts:
print("DEBUG: Raw texts sample (first 200 chars):", texts[0][:200])
return {"text": texts}
#####################################
# Step 2: Tokenizing the Prompts
#####################################
def tokenize_function(examples, hf_tokenizer, max_length):
"""
Tokenizes a batch of text prompts with padding and truncation enabled.
"""
flat_texts = []
for t in examples["text"]:
if isinstance(t, list):
t = t[0] if len(t) == 1 else " ".join(t)
flat_texts.append(t)
print("DEBUG: Tokenizing a batch of size:", len(flat_texts))
tokenized = hf_tokenizer(
flat_texts,
padding="max_length",
truncation=True,
max_length=max_length,
return_tensors="pt",
)
tokenized = {key: value.tolist() for key, value in tokenized.items()}
sample_key = list(tokenized.keys())[0]
print("DEBUG: Tokenized sample (first 10 tokens of", sample_key, "):", tokenized[sample_key][0][:10])
return tokenized
#####################################
# Main Training Class
#####################################
class TrainModel:
def __init__(self, config_path="config.yaml"):
self.load_config(config_path)
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model, self.tokenizer = None, None
self.model = None
self.hf_tokenizer = None # The underlying HF tokenizer
self.chat_tokenizer = None # Chat wrapper for formatting
def load_config(self, path):
with open(path, "r") as file:
self.config = yaml.safe_load(file)
print("DEBUG: Loaded config:", self.config)
def print_system_info(self):
print(f"PyTorch version: {torch.__version__}")
print(f"CUDA version: {torch.version.cuda}")
print("DEBUG: PyTorch version:", torch.__version__)
print("DEBUG: CUDA version:", torch.version.cuda)
if torch.cuda.is_available():
device_capability = torch.cuda.get_device_capability()
print(f"CUDA Device Capability: {device_capability}")
print("DEBUG: CUDA Device Capability:", torch.cuda.get_device_capability())
else:
print("CUDA is not available")
python_version = sys.version
pip_version = subprocess.check_output(['pip', '--version']).decode().strip()
python_path = sys.executable
pip_path = subprocess.check_output(['which', 'pip']).decode().strip()
print(f"Python Version: {python_version}")
print(f"Pip Version: {pip_version}")
print(f"Python Path: {python_path}")
print(f"Pip Path: {pip_path}")
print("DEBUG: CUDA is not available")
print("DEBUG: Python Version:", sys.version)
print("DEBUG: Python Path:", sys.executable)
def check_gpu(self):
gpu_stats = torch.cuda.get_device_properties(0)
print(f"GPU = {gpu_stats.name}. Max memory = {round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)} GB.")
print(f"DEBUG: GPU = {gpu_stats.name}. Max memory = {round(gpu_stats.total_memory/(1024**3),3)} GB.")
def check_ram(self):
ram_gb = virtual_memory().total / 1e9
print('Your runtime has {:.1f} gigabytes of available RAM\n'.format(ram_gb))
print(f"DEBUG: Your runtime has {ram_gb:.1f} gigabytes of available RAM")
if ram_gb < 20:
print('Not using a high-RAM runtime')
print("DEBUG: Not using a high-RAM runtime")
else:
print('You are using a high-RAM runtime!')
# def install_packages(self):
# subprocess.run(["pip", "install", "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git@4e570be9ae4ced8cdc64e498125708e34942befc"])
# subprocess.run(["pip", "install", "--no-deps", "trl<0.9.0", "peft==0.12.0", "accelerate==0.33.0", "bitsandbytes==0.43.3"])
print("DEBUG: You are using a high-RAM runtime!")
def prepare_model(self):
self.model, self.tokenizer = FastLanguageModel.from_pretrained(
print("DEBUG: Preparing model and tokenizer...")
self.model, original_tokenizer = FastLanguageModel.from_pretrained(
model_name=self.config["model_name"],
max_seq_length=self.config["max_seq_length"],
dtype=None,
load_in_4bit=self.config["load_in_4bit"]
load_in_4bit=self.config["load_in_4bit"],
)
print("DEBUG: Model and original tokenizer loaded.")
if original_tokenizer.pad_token is None:
original_tokenizer.pad_token = original_tokenizer.eos_token
original_tokenizer.model_max_length = self.config["max_seq_length"]
self.chat_tokenizer = get_chat_template(original_tokenizer, chat_template="llama-3.1")
self.hf_tokenizer = original_tokenizer
print("DEBUG: Chat tokenizer created; HF tokenizer saved.")
self.model = FastLanguageModel.get_peft_model(
self.model,
r=self.config["lora_r"],
target_modules=self.config["lora_target_modules"],
lora_alpha=self.config["lora_alpha"],
lora_dropout=self.config["lora_dropout"],
bias=self.config["lora_bias"],
use_gradient_checkpointing=self.config["use_gradient_checkpointing"],
random_state=self.config["random_state"],
use_rslora=self.config["use_rslora"],
loftq_config=self.config["loftq_config"],
r=16,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
lora_alpha=16,
lora_dropout=0,
bias="none",
use_gradient_checkpointing="unsloth",
random_state=3407,
use_rslora=False,
loftq_config=None,
)
print("DEBUG: LoRA adapters added.")
def process_dataset(self, dataset_info):
dataset_name = dataset_info["name"]
split_type = dataset_info.get("split_type", "train")
processing_func = getattr(self, dataset_info.get("processing_func", "format_prompts"))
rename = dataset_info.get("rename", {})
filter_data = dataset_info.get("filter_data", False)
filter_column_value = dataset_info.get("filter_column_value", "id")
filter_value = dataset_info.get("filter_value", "alpaca")
num_samples = dataset_info.get("num_samples", 20000)
print(f"DEBUG: Loading dataset '{dataset_name}' split '{split_type}'...")
dataset = load_dataset(dataset_name, split=split_type)
if rename:
dataset = dataset.rename_columns(rename)
if filter_data:
dataset = dataset.filter(lambda example: filter_value in example[filter_column_value]).shuffle(seed=42).select(range(num_samples))
dataset = dataset.map(processing_func, batched=True)
print("DEBUG: Dataset columns:", dataset.column_names)
if "conversations" in dataset.column_names:
print("DEBUG: Standardizing dataset (ShareGPT style)...")
dataset = standardize_sharegpt(dataset)
else:
print("DEBUG: Dataset does not have 'conversations'; assuming Alpaca format.")
print("DEBUG: Applying formatting function to dataset...")
format_func = partial(formatting_prompts_func, tokenizer=self.chat_tokenizer)
dataset = dataset.map(format_func, batched=True, remove_columns=dataset.column_names)
sample = dataset[0]
print("DEBUG: Sample processed example keys:", list(sample.keys()))
if "text" in sample:
print("DEBUG: Sample processed 'text' type:", type(sample["text"]))
print("DEBUG: Sample processed 'text' content (first 200 chars):", sample["text"][:200])
else:
print("DEBUG: Processed sample does not contain 'text'.")
return dataset
def format_prompts(self, examples):
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{}
### Input:
{}
### Response:
{}"""
texts = [alpaca_prompt.format(ins, inp, out) + self.tokenizer.eos_token for ins, inp, out in zip(examples["instruction"], examples["input"], examples["output"])]
return {"text": texts}
def tokenize_dataset(self, dataset):
print("DEBUG: Tokenizing the entire dataset...")
tokenized_dataset = dataset.map(
lambda examples: tokenize_function(examples, self.hf_tokenizer, self.config["max_seq_length"]),
batched=True
)
tokenized_dataset = tokenized_dataset.remove_columns(["text"])
print("DEBUG: Tokenized dataset sample keys:", tokenized_dataset[0].keys())
return tokenized_dataset
def load_datasets(self):
datasets = []
for dataset_info in self.config["dataset"]:
print("DEBUG: Processing dataset info:", dataset_info)
datasets.append(self.process_dataset(dataset_info))
return concatenate_datasets(datasets)
combined = concatenate_datasets(datasets)
print("DEBUG: Combined dataset has", len(combined), "examples.")
return combined
def train_model(self):
dataset = self.load_datasets()
print("DEBUG: Starting training...")
raw_dataset = self.load_datasets()
tokenized_dataset = self.tokenize_dataset(raw_dataset)
print("DEBUG: Dataset tokenization complete.")
training_args = TrainingArguments(
per_device_train_batch_size=2,
gradient_accumulation_steps=4,
warmup_steps=5,
max_steps=60,
learning_rate=2e-4,
fp16=not is_bfloat16_supported(),
bf16=is_bfloat16_supported(),
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.01,
lr_scheduler_type="linear",
seed=3407,
output_dir="outputs",
report_to="none",
remove_unused_columns=False,
)
# Since the dataset is pre-tokenized, we supply a dummy dataset_text_field.
trainer = SFTTrainer(
model=self.model,
tokenizer=self.tokenizer,
train_dataset=dataset,
dataset_text_field=self.config["dataset_text_field"],
tokenizer=self.hf_tokenizer,
train_dataset=tokenized_dataset,
dataset_text_field="input_ids", # Dummy field since data is numeric
max_seq_length=self.config["max_seq_length"],
dataset_num_proc=self.config["dataset_num_proc"],
packing=self.config["packing"],
args=TrainingArguments(
per_device_train_batch_size=self.config["per_device_train_batch_size"],
gradient_accumulation_steps=self.config["gradient_accumulation_steps"],
warmup_steps=self.config["warmup_steps"],
num_train_epochs=self.config["num_train_epochs"],
max_steps=self.config["max_steps"],
learning_rate=self.config["learning_rate"],
fp16=not is_bfloat16_supported(),
bf16=is_bfloat16_supported(),
logging_steps=self.config["logging_steps"],
optim=self.config["optim"],
weight_decay=self.config["weight_decay"],
lr_scheduler_type=self.config["lr_scheduler_type"],
seed=self.config["seed"],
output_dir=self.config["output_dir"],
),
dataset_num_proc=1, # Use a single process to avoid pickling issues
packing=False,
args=training_args,
)
from unsloth.chat_templates import train_on_responses_only
trainer = train_on_responses_only(
trainer,
instruction_part="<|start_header_id|>user<|end_header_id|>\n\n",
response_part="<|start_header_id|>assistant<|end_header_id|>\n\n",
)
print("DEBUG: Beginning trainer.train() ...")
trainer.train()
self.model.save_pretrained("lora_model") # Local saving
self.tokenizer.save_pretrained("lora_model")
print("DEBUG: Training complete. Saving model and tokenizer locally...")
self.model.save_pretrained("lora_model")
self.hf_tokenizer.save_pretrained("lora_model")
print("DEBUG: Saved model and tokenizer to 'lora_model'.")
def inference(self, instruction, input_text):
FastLanguageModel.for_inference(self.model)
alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
messages = [{"role": "user", "content": f"{instruction}\n\nInput: {input_text}"}]
inputs = self.hf_tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_tensors="pt"
).to("cuda")
outputs = self.model.generate(
input_ids=inputs,
max_new_tokens=64,
use_cache=True,
temperature=1.5,
min_p=0.1
)
print("DEBUG: Inference output:", self.hf_tokenizer.batch_decode(outputs))
### Instruction:
{}
### Input:
{}
### Response:
{}"""
inputs = self.tokenizer([alpaca_prompt.format(instruction, input_text, "")], return_tensors="pt").to("cuda")
outputs = self.model.generate(**inputs, max_new_tokens=64, use_cache=True)
print(self.tokenizer.batch_decode(outputs))
def load_model(self):
"""Loads the model and tokenizer using the FastLanguageModel library."""
from unsloth import FastLanguageModel
model, tokenizer = FastLanguageModel.from_pretrained(
model_name=self.config["output_dir"],
@@ -177,33 +290,31 @@ class train:
shutil.rmtree(self.config["hf_model_name"])
self.model.push_to_hub_merged(
self.config["hf_model_name"],
self.tokenizer,
self.hf_tokenizer,
save_method="merged_16bit",
token=os.getenv('HF_TOKEN')
token=os.getenv("HF_TOKEN")
)
def push_model_gguf(self):
self.model.push_to_hub_gguf(
self.config["hf_model_name"],
self.tokenizer,
self.hf_tokenizer,
quantization_method=self.config["quantization_method"],
token=os.getenv('HF_TOKEN')
token=os.getenv("HF_TOKEN")
)
def save_model_gguf(self):
self.model.save_pretrained_gguf(
self.config["hf_model_name"],
self.tokenizer,
self.hf_tokenizer,
quantization_method="q4_k_m"
)
def prepare_modelfile_content(self):
output_model = self.config["hf_model_name"]
gguf_path = f"{output_model}/unsloth.Q4_K_M.gguf"
# Check if the GGUF file exists. If not, generate it ## TODO Multiple Quantisation other than Q4_K_M.gguf
if not os.path.exists(gguf_path):
self.model, self.tokenizer = self.load_model()
self.model, self.hf_tokenizer = self.load_model()
self.save_model_gguf()
return f"""FROM {output_model}/unsloth.Q4_K_M.gguf
@@ -224,9 +335,8 @@ PARAMETER stop "<|reserved_special_token_"
def create_and_push_ollama_model(self):
modelfile_content = self.prepare_modelfile_content()
with open('Modelfile', 'w') as file:
with open("Modelfile", "w") as file:
file.write(modelfile_content)
subprocess.run(["ollama", "serve"])
subprocess.run(["ollama", "create", f"{self.config['ollama_model']}:{self.config['model_parameters']}", "-f", "Modelfile"])
subprocess.run(["ollama", "push", f"{self.config['ollama_model']}:{self.config['model_parameters']}"])
@@ -235,42 +345,30 @@ PARAMETER stop "<|reserved_special_token_"
self.print_system_info()
self.check_gpu()
self.check_ram()
# self.install_packages()
if self.config.get("train", "true").lower() == "true":
self.prepare_model()
self.train_model()
if self.config.get("huggingface_save", "true").lower() == "true":
# self.model, self.tokenizer = self.load_model()
self.save_model_merged()
if self.config.get("huggingface_save_gguf", "true").lower() == "true":
# self.model, self.tokenizer = self.load_model()
self.push_model_gguf()
# if self.config.get("save_gguf", "true").lower() == "true": ## TODO
# self.model, self.tokenizer = self.load_model()
# self.save_model_gguf()
# if self.config.get("save_merged", "true").lower() == "true": ## TODO
# self.model, self.tokenizer = self.load_model()
# self.save_model_merged()
if self.config.get("ollama_save", "true").lower() == "true":
self.create_and_push_ollama_model()
def main():
import argparse
parser = argparse.ArgumentParser(description='PraisonAI Training Script')
parser.add_argument('command', choices=['train'], help='Command to execute')
parser.add_argument('--config', default='config.yaml', help='Path to configuration file')
parser = argparse.ArgumentParser(description="PraisonAI Training Script")
parser.add_argument("command", choices=["train"], help="Command to execute")
parser.add_argument("--config", default="config.yaml", help="Path to configuration file")
parser.add_argument("--model", type=str, help="Model name")
parser.add_argument("--hf", type=str, help="Hugging Face model name")
parser.add_argument("--ollama", type=str, help="Ollama model name")
parser.add_argument("--dataset", type=str, help="Dataset name for training")
args = parser.parse_args()
if args.command == 'train':
ai = train(config_path=args.config)
ai.run()
if args.command == "train":
trainer_obj = TrainModel(config_path=args.config)
trainer_obj.run()
if __name__ == '__main__':
if __name__ == "__main__":
main()
+4 -4
View File
@@ -1,6 +1,6 @@
[project]
name = "PraisonAI"
version = "2.0.57"
version = "2.0.65"
description = "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."
readme = "README.md"
license = ""
@@ -12,7 +12,7 @@ dependencies = [
"rich>=13.7",
"markdown>=3.5",
"pyparsing>=3.0.0",
"praisonaiagents>=0.0.50",
"praisonaiagents>=0.0.61",
"python-dotenv>=0.19.0",
"instructor>=1.3.3",
"PyYAML>=6.0",
@@ -84,7 +84,7 @@ autogen = ["pyautogen>=0.2.19", "praisonai-tools>=0.0.7", "crewai"]
[tool.poetry]
name = "PraisonAI"
version = "2.0.57"
version = "2.0.65"
description = "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."
authors = ["Mervin Praison"]
license = ""
@@ -102,7 +102,7 @@ python = ">=3.10,<3.13"
rich = ">=13.7"
markdown = ">=3.5"
pyparsing = ">=3.0.0"
praisonaiagents = ">=0.0.50"
praisonaiagents = ">=0.0.61"
python-dotenv = ">=0.19.0"
instructor = ">=1.3.3"
PyYAML = ">=6.0"
+150
View File
@@ -0,0 +1,150 @@
1. Make minimal code changes as possible
2. if you are creating function, make sure to name it in more easy, user friendly , optimised manner.
3. Never copy the exact code if presented with a code from other location or file or codebase, just make it optimised
4. Always Follow the principle LESS IS MORE
5. Make it minimal change as possible
6. Firstly try not to make any modification to the existing code as possible
7. Only modify the existing code if its highly required, without that if it cant be done, then add new code section.
8. If you are adding new code, make sure to add it in a way that it can be easily integrated with the existing codebase.
Below is a **detailed technical overview** of the issues that have been coming up in the workflow execution (specifically around loops, resetting tasks, and continuing on to subsequent tasks). It includes:
1. **How the workflow currently flows**
2. **What logic marks a task as “completed”**
3. **What issues arose in `loop` tasks**
4. **Why the workflow can end up “stuck” or “looping indefinitely”**
---
## 1. Overall Workflow Flow
### a. Building relationships among tasks
- At startup, the code iterates through all `tasks`.
- For each `task`:
- It looks at `task.next_tasks`, and for each `next_task_name`:
- Finds the corresponding `Task` object
- Appends the current task’s name to the found `next_task`'s `previous_tasks` list.
- This means if Task A has `next_tasks=["B"]`, then Task B’s `previous_tasks` will include `"A"`.
### b. Finding and starting with a “start task”
- The workflow code tries to locate a task with `is_start=True`.
- If no such task is found, it uses the first item in the tasks dictionary instead.
- That “start task” is what the workflow tries to run first.
### c. Execution loop in the method (e.g., `workflow()` or `aworkflow()`)
- There is a `while current_task:` loop that processes tasks in sequence, or conditionally, based on `task.condition`.
- Each time a task runs (if non-loop), it yields the `task_id` or triggers an agent to run. Once the agent finishes (with or without a final result), the workflow picks up again to see what to do next:
- If the `task` is a `loop` type, the code tries to create or manage sub-tasks for each row/line in an “input_file.”
- If the `task` is a normal (“decision” or “task” or “some-other-type”), it just executes once, sets `status="completed"`, and the code moves on.
### d. Condition-based branching
- If a task has a result that includes a “decision” (like `{"decision":"more"}` or `"done"`), the code checks `task.condition`. For example:
```python
condition = {
"more": "generate_task",
"done": "evaluate_total_questions"
}
```
- If the result’s decision is `"done"`, it jumps to the task named `"evaluate_total_questions"`.
- If the result’s decision is `"more"`, it jumps right back to `"generate_task"`.
- If no condition matches, it can fallback to the first item in `task.next_tasks`.
### e. Marking tasks as “completed”
- After a task’s execution (like a typical “non-loop” task), the code sets `task.status = "completed"`.
- Then the code has a snippet that says:
```python
if self.tasks[task_id].status == "completed":
# Possibly reset to "not started" so we can re-run if needed
```
- By default, the system tries to “reset” tasks to `"not started"`, **unless** it is a loop task or a subtask of a loop.
---
## 2. How a “completed” task is marked
Generally, tasks are marked `status="completed"` in two primary ways:
1. **Non-Loop Execution**
A normal task (like a “decision” or “task”) is executed once the code calls the agent, the agent returns a final result, and the system sets `task.status = "completed"`.
2. **Loop Execution**
A loop-type task is *programmatically* set to `status="completed"` when all of its sub-tasks have finished. That is:
- The code checks: “Have all child tasks of this loop finished?”
- If `True`, the loop task is set to `completed`.
---
## 3. Issues Specifically in `loop` Tasks
### a. Re-Entering the Loop
- Before, the same snippet that “resets completed tasks to ‘not started’ so they can re-run if needed” **also** tried to reset loop tasks or their subtasks.
- If a loop task got reset to `"not started"`, the code would eventually pick it back up again, leading to repeated creation of sub-tasks (or repeated attempts to re-run them).
- This caused an **infinite loop** or repeating the same steps in the workflow, never truly exiting the loop stage.
### b. Subtasks Not Marked or Overwritten
- Another tricky scenario: If sub-tasks themselves got reset, the parent loop would see them as “not started” again, and might wait for them to “complete,” or might re-run them. That can lead to indefinite re-running of sub-tasks.
### c. Not Proceeding to Next (e.g., “upload_to_huggingface”)
- If the loop kept “restarting,” the workflow never ended up hitting the next tasks. For example, if your workflow is:
1. `generate_task`
2. `evaluate_total_questions`
3. `generate_cot` (loop)
4. `upload_to_huggingface`
- The system might get stuck in step #3 indefinitely (the sub-tasks keep getting reset, so it never actually transitions to step #4).
### d. Condition Logic vs. Next Tasks
- Another subtlety: If the loop tasks had a `condition` that pointed them back to a prior step, it might cause unintentional re-entry. Typically, you only want loop tasks to proceed once, **unless** you explicitly want to re-visit. But if it’s a data ingestion process, you usually want to do it once, then move on to the next step.
---
## 4. Why the System Can End Up Stuck or “Looping Indefinitely”
1. **Reset Mechanism**
- The code tries to “reset tasks to ‘not started’ once they complete,” so they can be re-run in some dynamic multi-run scenario.
- But that same logic can cause loop tasks to revert back to “not started” the moment they end. The system sees “Oh, a task is ‘not started’? Let’s run it!” and you’re in a cycle.
2. **No Condition for Exit**
- If the loop has a condition that leads back to a prior step (like `"more" -> generate_cot`), it can keep re-running.
3. **Subtasks Not Marked**
- If the subtask or the loop tries to “reactivate” each other, it never exits.
---
## Summary of the “Core Problem”
1. We want to keep the resetting mechanism for **non-loop tasks** – because in some advanced workflows, we like re-running them from a different path or after some condition.
2. But we want **loop tasks** to remain `"completed"` once all sub-tasks are done, so the code can seamlessly proceed to the next major step.
3. Before the fix, loop tasks or their sub-tasks got reset. This triggered the system to re-enter the loop, re-run the sub-tasks, etc., causing an infinite loop and preventing the workflow from reaching tasks like “upload_to_huggingface.”
---
## Technical Highlights to Pass On
- **In the reset snippet**:
```python
if self.tasks[task_id].status == "completed":
# never reset if loop or subtask-of-loop
# else reset to "not started"
```
This is crucial to skipping re-runs on loop tasks.
- **Ensure** that once a loop’s sub-tasks are all “completed,” the loop’s status is set to “completed,” and it transitions to the next major tasks (like `upload_to_huggingface`).
- **Check** if the loop’s condition is correct. If you want a single pass, do not implement a condition that leads back to the same loop.
- Also, you can check you do not have “overlapping conditions” that cause re-entry.
---
### Conclusion
**Hence,** the main challenge is that the reset logic (meant to let normal tasks be re-run) conflicts with a loop task’s one-pass usage. Once you avoid resetting the loop tasks or sub-tasks, you can finish them once, mark them “completed,” and properly proceed to the next stage.
Dont remove any logging or debug statements, as it will help you to understand the flow of the code.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+73
View File
@@ -0,0 +1,73 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import cot_save, cot_upload_to_huggingface
# Create a COT agent for generating and managing chain of thought solutions
cot_agent = Agent(
name="COTGenerator",
role="Chain of Thought Specialist",
goal="Generate and manage chain of thought solutions for Q&A pairs",
backstory="Expert in breaking down problems and generating detailed solution steps",
tools=[cot_save],
llm="gpt-4o-mini", # Using recommended model
)
save_to_huggingface_agent = Agent(
name="SaveToHuggingface",
role="Save to Huggingface",
goal="Save the generated chain of thought solutions to a Huggingface dataset",
backstory="Expert in saving data to Huggingface",
tools=[cot_upload_to_huggingface],
llm="gpt-4o-mini", # Using recommended model
)
# Define question-answer pairs to process in batches
qa_pairs = [
{
"question": "What is the sum of numbers from 1 to 10?",
"answer": "55"
},
{
"question": "Calculate the area of a circle with radius 5",
"answer": "78.54"
}
]
# Process qa_pairs in batches
batch_size = 2
for i in range(0, len(qa_pairs), batch_size):
batch_qa = qa_pairs[i:i + batch_size]
# Create task for current batch
qa_text = "\n".join(
f"- Q: {qa['question']}\n A: {qa['answer']}"
for qa in batch_qa
)
cot_task = Task(
description=(
"For each Q&A pair:\n"
"1. Use the tool cot_save to generate a chain of thought solution\n"
"2. Save to CSV file with filename 'cot_dataset.csv'\n\n"
f"Q&A Pairs:\n{qa_text}"
),
expected_output="Chain of thought solutions saved to CSV",
agent=cot_agent,
name=f"generate_cot_solutions_batch_{i//batch_size + 1}"
)
save_to_huggingface_task = Task(
description="Save to Huggingface dataset at mervinpraison/cot-dataset , cot_dataset.csv",
expected_output="Chain of thought solutions saved to Huggingface",
agent=save_to_huggingface_agent,
name=f"save_to_huggingface_batch_{i//batch_size + 1}"
)
# Initialize and run the agent
agents = PraisonAIAgents(
agents=[cot_agent, save_to_huggingface_agent],
tasks=[cot_task, save_to_huggingface_task]
)
# Execute current batch
result = agents.start()
print(f"\nBatch {i//batch_size + 1} completed. Solutions appended to CSV file.")
+142
View File
@@ -0,0 +1,142 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import cot_save, cot_upload_to_huggingface
from pydantic import BaseModel
import os
# Define Pydantic model for structured output
class DecisionModel(BaseModel):
response: str
decision: str
def write_csv(file_path, data):
"""Write data to CSV file."""
if not os.path.exists(file_path):
with open(file_path, 'w') as file:
file.write(data + '\n')
else:
with open(file_path, 'a') as file:
file.write(data + '\n')
return f"Data appended to {file_path}"
def count_questions(file_path):
"""Count lines in file."""
with open(file_path, 'r') as file:
return sum(1 for _ in file)
# Keep existing agents with minimal changes
qa_generator = Agent(
name="Generator",
role="Question Creator",
goal="Create challenging math and logic questions",
backstory="Expert in educational content creation",
llm="gpt-4o-mini",
tools=[write_csv, count_questions]
)
total_questions_evaluator = Agent(
name="TotalQuestionsEvaluator",
role="Total Questions Evaluator",
goal="Evaluate the total number of questions in qa_pairs.csv file",
backstory="Expert in evaluating the total number of questions in a file",
llm="gpt-4o-mini",
tools=[count_questions],
verbose=False
)
cot_generator = Agent(
name="COTGenerator",
role="Chain of Thought Specialist",
goal="Generate and manage chain of thought solutions for Q&A pairs",
backstory="Expert in breaking down problems and generating detailed solution steps",
tools=[cot_save],
llm="gpt-4o-mini",
verbose=False
)
upload_to_huggingface = Agent(
name="UploadToHuggingface",
role="Upload to Huggingface",
goal="Upload the generated chain of thought solutions to a Huggingface dataset",
backstory="Expert in saving data to Huggingface",
tools=[cot_upload_to_huggingface],
llm="gpt-4o-mini",
verbose=False
)
# Define tasks with workflow improvements
generate_task = Task(
description="""Generate question and answer in csv format without headers: question, answer and append to qa_pairs.csv file
generate 10 unique questions and answers and don't repeat on the same question and answer. Reponse with 'done' when done
with append mode as 'a'
Example question and answer:
question, answer
What is the sum of numbers from 1 to 10?, 55
Number of r's in the word strawberry, 3
""",
expected_output="append to qa_pairs.csv file with questions and answers and move to next task",
agent=qa_generator,
name="generate_task",
is_start=True,
next_tasks=["evaluate_total_questions"],
task_type="decision",
condition={
"more": "generate_task",
"done": "evaluate_total_questions"
}
)
evaluate_total_questions_task = Task(
description="Evaluate the total number of questions in qa_pairs.csv file is 1",
expected_output="Total number of questions in qa_pairs.csv file",
agent=total_questions_evaluator,
task_type="decision",
name="evaluate_total_questions",
condition={
"more": "generate_task",
"done": "generate_cot"
}
)
generate_cot_task = Task(
name="generate_cot",
description="""Generate chain of thought solutions for each question in the input file.
Save to cot_solutions.csv file
Don't generate chain of thought solutions again after receiving the response from Tool Call
After calling the tool, respond with a JSON object:
{
"response": "done",
"decision": "done"
}
""",
expected_output="done",
agent=cot_generator,
input_file="qa_pairs.csv",
task_type="loop",
next_tasks=["upload_to_huggingface"],
condition={
"done": ["upload_to_huggingface"],
"exit": [],
},
output_pydantic=DecisionModel # Use Pydantic model for output validation
)
upload_to_huggingface_task = Task(
name="upload_to_huggingface",
description="""Upload to Huggingface:
1. Save to cot_solutions.csv
2. Upload to mervinpraison/cot-dataset""",
expected_output="Dataset published successfully",
agent=upload_to_huggingface,
tools=[cot_upload_to_huggingface]
)
# Initialize workflow
agents = PraisonAIAgents(
agents=[qa_generator, total_questions_evaluator, cot_generator, upload_to_huggingface],
tasks=[generate_task, evaluate_total_questions_task, generate_cot_task, upload_to_huggingface_task],
process="workflow",
max_iter=30,
verbose=False
)
agents.start()
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+142
View File
@@ -0,0 +1,142 @@
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import cot_save, cot_upload_to_huggingface
from pydantic import BaseModel
import os
# Define Pydantic model for structured output
class DecisionModel(BaseModel):
response: str
decision: str
def write_csv(file_path, data):
"""Write data to CSV file."""
if not os.path.exists(file_path):
with open(file_path, 'w') as file:
file.write(data + '\n')
else:
with open(file_path, 'a') as file:
file.write(data + '\n')
return f"Data appended to {file_path}"
def count_questions(file_path):
"""Count lines in file."""
with open(file_path, 'r') as file:
return sum(1 for _ in file)
# Keep existing agents with minimal changes
qa_generator = Agent(
name="Generator",
role="Question Creator",
goal="Create challenging math and logic questions",
backstory="Expert in educational content creation",
llm="deepseek/deepseek-reasoner",
tools=[write_csv, count_questions]
)
total_questions_evaluator = Agent(
name="TotalQuestionsEvaluator",
role="Total Questions Evaluator",
goal="Evaluate the total number of questions in qa_pairs.csv file",
backstory="Expert in evaluating the total number of questions in a file",
llm="deepseek/deepseek-reasoner",
tools=[count_questions],
verbose=False
)
cot_generator = Agent(
name="COTGenerator",
role="Chain of Thought Specialist",
goal="Generate and manage chain of thought solutions for Q&A pairs",
backstory="Expert in breaking down problems and generating detailed solution steps",
tools=[cot_save],
llm="deepseek/deepseek-reasoner",
verbose=False
)
upload_to_huggingface = Agent(
name="UploadToHuggingface",
role="Upload to Huggingface",
goal="Upload the generated chain of thought solutions to a Huggingface dataset",
backstory="Expert in saving data to Huggingface",
tools=[cot_upload_to_huggingface],
llm="deepseek/deepseek-reasoner",
verbose=False
)
# Define tasks with workflow improvements
generate_task = Task(
description="""Generate question and answer in csv format without headers: question, answer and append to qa_pairs.csv file
generate 10 unique questions and answers and don't repeat on the same question and answer. Reponse with 'done' when done
with append mode as 'a'
Example question and answer:
question, answer
What is the sum of numbers from 1 to 10?, 55
Number of r's in the word strawberry, 3
""",
expected_output="append to qa_pairs.csv file with questions and answers and move to next task",
agent=qa_generator,
name="generate_task",
is_start=True,
next_tasks=["evaluate_total_questions"],
task_type="decision",
condition={
"more": "generate_task",
"done": "evaluate_total_questions"
}
)
evaluate_total_questions_task = Task(
description="Evaluate the total number of questions in qa_pairs.csv file is 1",
expected_output="Total number of questions in qa_pairs.csv file",
agent=total_questions_evaluator,
task_type="decision",
name="evaluate_total_questions",
condition={
"more": "generate_task",
"done": "generate_cot"
}
)
generate_cot_task = Task(
name="generate_cot",
description="""Generate chain of thought solutions for each question in the input file.
Save to cot_solutions.csv file
Don't generate chain of thought solutions again after receiving the response from Tool Call
After calling the tool, respond with a JSON object:
{
"response": "done",
"decision": "done"
}
""",
expected_output="done",
agent=cot_generator,
input_file="qa_pairs.csv",
task_type="loop",
next_tasks=["upload_to_huggingface"],
condition={
"done": ["upload_to_huggingface"],
"exit": [],
},
output_pydantic=DecisionModel # Use Pydantic model for output validation
)
upload_to_huggingface_task = Task(
name="upload_to_huggingface",
description="""Upload to Huggingface:
1. Save to cot_solutions.csv
2. Upload to mervinpraison/cot-dataset""",
expected_output="Dataset published successfully",
agent=upload_to_huggingface,
tools=[cot_upload_to_huggingface]
)
# Initialize workflow
agents = PraisonAIAgents(
agents=[qa_generator, total_questions_evaluator, cot_generator, upload_to_huggingface],
tasks=[generate_task, evaluate_total_questions_task, generate_cot_task, upload_to_huggingface_task],
process="workflow",
max_iter=30,
verbose=False
)
agents.start()
@@ -0,0 +1,39 @@
from praisonaiagents import Agent
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "praison",
"path": ".praison"
}
},
"llm": {
"provider": "ollama",
"config": {
"model": "deepseek-r1:latest",
"temperature": 0,
"max_tokens": 8000,
"ollama_base_url": "http://localhost:11434",
},
},
"embedder": {
"provider": "ollama",
"config": {
"model": "nomic-embed-text:latest",
"ollama_base_url": "http://localhost:11434",
"embedding_dims": 1536
},
},
}
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["kag-research-paper.pdf"], # Indexing
knowledge_config=config,
user_id="user1",
llm="deepseek-r1"
)
agent.start("What is KAG in one line?") # Querying
Loaded 100 of 309 files, more files were not shown because too many files have changed in this diff. Show more