Compare commits

...
324 Commits
Author SHA1 Message Date
Mervin Praison f36415d4ea Merge pull request #519 from MervinPraison/develop
Update version to 2.2.16 across project files
2025-05-27 06:10:32 +01:00
MervinPraison 13c3e31458 Update version to 2.2.16 across project files
- Incremented PraisonAI version from 2.2.15 to 2.2.16 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Updated dependency version for `praisonaiagents` from 0.0.88 to 0.0.89.
- Ensured minimal changes to existing code while maintaining versioning accuracy across the project.
2025-05-27 06:10:01 +01:00
Mervin Praison 41d550c4a5 Merge pull request #518 from MervinPraison/claude/issue-484-20250527_043953
feat: Add context management for workflow loops
2025-05-27 05:54:45 +01:00
Mervin Praison ac570e5b93 Rename test_context_management.py to tests/unit/test_context_management.py 2025-05-27 05:54:18 +01:00
claude[bot]andMervinPraison a5465882ee feat: Add context management for workflow loops to prevent context length issues
- Add retain_full_context parameter to Task class (default False)
- By default, only include most recent previous task in context
- Maintain backwards compatibility with retain_full_context=True
- Add _build_task_context helper method to Process class  
- Update both async and sync workflow methods to use new context building
- Add test script to verify functionality

Fixes context accumulation issue in workflow loops where all previous
task results were being appended, causing exponential context growth.

Co-authored-by: MervinPraison <[email protected]>
2025-05-27 04:47:37 +00:00
Mervin Praison f86b03e5d8 Merge pull request #517 from MervinPraison/develop
Update version to 2.2.15 across project files
2025-05-27 05:47:27 +01:00
MervinPraison 397a466f55 Update version to 2.2.15 across project files
- Incremented PraisonAI version from 2.2.14 to 2.2.15 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Updated dependency version for `praisonaiagents` from 0.0.87 to 0.0.88.
- Ensured minimal changes to existing code while maintaining versioning accuracy across the project.
2025-05-27 05:36:34 +01:00
Mervin Praison 36c3066ba4 Merge pull request #515 from MervinPraison/claude/issue-514-20250526_155559
fix: Add asyncio import to local scope in launch() method
2025-05-26 20:00:06 +01:00
claude[bot]andMervinPraison df06e794b3 fix: Add asyncio import to local scope in launch() method
This fixes the NameError: cannot access free variable 'asyncio' where it is not associated with a value in enclosing scope error that occurs at line 1563.

The issue was that the handle_agent_query function (containing line 1563) is defined inside a try/except block that imports FastAPI dependencies but didn't include asyncio. Added import asyncio to the try block and removed redundant import from line 1659.

Fixes #514

Co-authored-by: MervinPraison <[email protected]>
2025-05-26 15:59:29 +00:00
Mervin Praison 71fe678d66 Merge pull request #513 from MervinPraison/develop
Update version to 2.2.14 across project files
2025-05-25 06:47:58 +01:00
MervinPraison c8875eec81 Update version to 2.2.14 across project files
- Incremented PraisonAI version from 2.2.13 to 2.2.14 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Ensured minimal changes to existing code while maintaining versioning accuracy across the project.
2025-05-25 06:47:32 +01:00
Mervin Praison f88204d2e8 Merge pull request #512 from MervinPraison/develop
Update version to 2.2.13 across project files
2025-05-24 23:18:37 +01:00
MervinPraison fc01a80956 Update version to 2.2.13 across project files
- Incremented PraisonAI version from 2.2.12 to 2.2.13 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Ensured minimal changes to existing code while maintaining versioning accuracy across the project.
2025-05-24 23:18:09 +01:00
Mervin Praison cd91565b12 Merge pull request #511 from MervinPraison/develop
Update version to 2.2.12 across project files
2025-05-24 22:59:55 +01:00
MervinPraison d233d4597c Update version to 2.2.12 across project files
- Incremented PraisonAI version from 2.2.11 to 2.2.12 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Ensured minimal changes to existing code while maintaining versioning accuracy across the project.
2025-05-24 22:59:36 +01:00
Mervin Praison a9fabce0ea Merge pull request #510 from MervinPraison/develop
Develop
2025-05-24 22:46:10 +01:00
MervinPraison 6bcd3ba9bd Update version to 2.2.11 across project files
- Incremented PraisonAI version from 2.2.10 to 2.2.11 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Ensured minimal changes to existing code while maintaining versioning accuracy across the project.
2025-05-24 22:45:46 +01:00
MervinPraison 37028b0dd2 Enhance backup process for root configuration files in GitHub Actions workflow
- Updated echo statements to provide clearer context regarding the backup of `agents.yaml` and `tools.py`, preventing default file resolution interference during tests.
- Ensured minimal changes to existing code while improving clarity and user understanding of the backup process.
2025-05-24 22:38:10 +01:00
MervinPraison 6807d0e017 Add backup and restore steps for root configuration files in GitHub Actions workflow
- Introduced steps to back up and restore `agents.yaml` and `tools.py` during the workflow execution, preventing interference and ensuring a clean environment for tests.
- Added comprehensive execution debug step to provide detailed insights into the execution path and configuration status.
- Ensured minimal changes to existing code while enhancing the debugging and testing process for configuration management.
2025-05-24 22:35:23 +01:00
MervinPraison bca845d771 Add debug steps for logging level and researcher role detection in GitHub Actions workflow
- Introduced a new environment variable for log level and additional steps to search for the 'Researcher' role in YAML files, enhancing visibility during the workflow execution.
- Added a step to trace the AutoGen execution path, providing insights into framework decisions and available roles.
- Ensured minimal changes to existing code while improving the debugging and testing process for configuration and role management.
2025-05-24 22:07:21 +01:00
Mervin Praison 0596d2da2e Merge pull request #509 from MervinPraison/develop
Develop
2025-05-24 22:02:07 +01:00
MervinPraison 368498452c Add debug steps for YAML loading and framework detection in GitHub Actions workflow
- Introduced new steps in `unittest.yml` to debug YAML file loading and framework detection, providing detailed output on available YAML files and their content.
- Enhanced error handling to ensure visibility of issues during framework detection.
- Ensured minimal changes to existing code while improving the debugging process for configuration and role management.
2025-05-24 22:01:42 +01:00
MervinPraison 47e5ad2a65 Update version to 2.2.10 across project files
- Incremented PraisonAI version from 2.2.9 to 2.2.10 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Updated `litellm` dependency version from `1.41.8` to `1.68.0` across multiple files to ensure compatibility and improvements.
- Ensured minimal changes to existing code while maintaining versioning accuracy and optimising dependency management.
2025-05-24 21:58:27 +01:00
MervinPraison eb346be5f8 Add debug step for PraisonAIModel API key handling in GitHub Actions workflow
- Introduced a new step in `unittest.yml` to debug the handling of the PraisonAIModel API key, providing detailed output on its status and configuration.
- Ensured minimal changes to existing code while enhancing the testing process for API key integration and error visibility.
2025-05-24 21:53:47 +01:00
MervinPraison 62ab76f3e9 Add API key validation step in GitHub Actions workflow
- Introduced a new step in `unittest.yml` to validate the OpenAI API key by making a minimal API call, providing feedback on its status.
- Ensured minimal changes to existing code while enhancing the testing process for API configurations.
2025-05-24 21:50:48 +01:00
MervinPraison ac26c5fbe8 Add debug and test steps in GitHub Actions workflow
- Introduced a new step in `unittest.yml` to debug Python environment variables, checking the status of OpenAI API keys and other related variables for better visibility.
- Added a test step for direct PraisonAI execution to validate local functionality.
- Ensured minimal changes to existing code while enhancing the testing and debugging process in the workflow.
2025-05-24 21:45:36 +01:00
MervinPraison 22c10ff6ac Enhance error handling in test cases for API authentication
- Added try-except blocks in `test_agents_playbook.py` to handle API authentication errors gracefully, allowing tests to skip when encountering specific exceptions.
- Ensured minimal changes to existing code while improving robustness in test execution.
2025-05-24 21:40:25 +01:00
Mervin Praison 494f835e73 Merge pull request #508 from MervinPraison/develop
Develop
2025-05-24 21:36:27 +01:00
MervinPraison 3686eb2eaa Update version to 2.2.9 across project files
- Incremented PraisonAI version from 2.2.8 to 2.2.9 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Enhanced model retrieval logic in `agents_generator.py` for improved fallback handling.
- Ensured minimal changes to existing code while maintaining versioning accuracy and optimising model configuration.
2025-05-24 21:35:30 +01:00
MervinPraison 58c63f0dd4 Update LLM models in agents-advanced.yaml for consistency
- Replaced existing LLM model references with "openai/gpt-4o-mini" across various roles to standardise the configuration.
- Ensured minimal changes to existing code while enhancing model uniformity.
2025-05-24 21:20:43 +01:00
MervinPraison 7bf5c0a4d8 Add debug step for API key status in GitHub Actions workflow
- Introduced a new step in `unittest.yml` to check the availability of the OpenAI API key, providing feedback on its status and fallback usage.
- Ensured minimal changes to existing code while enhancing the debugging process for API configurations.
2025-05-24 21:16:47 +01:00
Mervin Praison 082d802fd9 Merge pull request #507 from MervinPraison/develop
Develop
2025-05-24 21:13:54 +01:00
MervinPraison 8cd926a244 Update version to 2.2.8 across project files
- Incremented PraisonAI version from 2.2.7 to 2.2.8 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Ensured minimal changes to existing code while maintaining versioning accuracy.
2025-05-24 21:13:31 +01:00
MervinPraison 987f63f032 Update environment variable setup in GitHub Actions workflows
- Modified `test-comprehensive.yml`, `test-core.yml`, `test-extended.yml`, and `test-frameworks.yml` to include default values for OpenAI API configuration, enhancing robustness during testing.
- Ensured minimal changes to existing code while improving the handling of environment variables.
2025-05-24 20:53:59 +01:00
Mervin Praison bec938883d Merge pull request #506 from MervinPraison/develop
Update version to 2.2.7 across project files
2025-05-24 18:15:04 +01:00
MervinPraison 76079a92fe Update version to 2.2.7 across project files
- Incremented PraisonAI version from 2.2.6 to 2.2.7 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Updated Python version specification in `test-comprehensive.yml` to focus solely on Python 3.11.
- Ensured minimal changes to existing code while maintaining versioning accuracy.
2025-05-24 18:13:59 +01:00
Mervin Praison c14fb2ee5d Merge pull request #505 from MervinPraison/develop
Update version to 2.2.6 across project files
2025-05-24 17:39:59 +01:00
MervinPraison 31c9a6a994 Update version to 2.2.6 across project files
- Incremented PraisonAI version from 2.2.5 to 2.2.6 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Updated test command patterns in GitHub Actions workflows for improved clarity and functionality.
- Ensured minimal changes to existing code while maintaining versioning accuracy.
2025-05-24 17:39:41 +01:00
Mervin Praison b5b4370cc8 Merge pull request #504 from MervinPraison/develop
Update Python version format in GitHub Actions workflow
2025-05-24 17:28:59 +01:00
MervinPraison 745f82b9c4 Update version to 2.2.5 across project files
- Incremented PraisonAI version from 2.2.4 to 2.2.5 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Ensured minimal changes to existing code while maintaining versioning accuracy.
2025-05-24 17:28:26 +01:00
MervinPraison 6845c7b0f6 Update Python version format in GitHub Actions workflow
- Changed the Python version specification in `test-comprehensive.yml` from unquoted to quoted strings for consistency and improved readability.
- Ensured minimal changes to existing code while enhancing clarity in the workflow configuration.
2025-05-24 17:20:27 +01:00
Mervin Praison e7be52722e Merge pull request #503 from MervinPraison/develop
Develop
2025-05-24 17:10:20 +01:00
MervinPraison e673189454 Update version to 2.2.4 across project files
- Incremented PraisonAI version from 2.2.3 to 2.2.4 in `pyproject.toml`, `uv.lock`, and all relevant Dockerfiles for consistency.
- Ensured minimal changes to existing code while maintaining versioning accuracy.
2025-05-24 17:09:45 +01:00
MervinPraison ab9192c57e Enhance GitHub Actions workflows and update test assertions
- Added environment variable setup in `test-extended.yml` for OpenAI API configuration.
- Updated test command in `unittest.yml` to use a pattern for faster execution.
- Refined assertions in `test_base_url_api_base_fix.py` to reflect changes in parameter naming from `base_url` to `api_base`.
- Improved mock tool listing in `test_mcp_integration.py` for clarity.
- Adjusted knowledge update logic in `test_rag_integration.py` to handle existing knowledge more effectively.
- Ensured minimal changes to existing code while enhancing test clarity and functionality.
2025-05-24 17:03:52 +01:00
Mervin Praison 819874275f Merge pull request #502 from MervinPraison/develop
Update GitHub Actions workflows to remove Python 3.9 support
2025-05-24 16:31:46 +01:00
MervinPraison 0a36fdb966 Update GitHub Actions workflows to remove Python 3.9 support
- Modified workflow files to exclude Python 3.9 from the test matrix, focusing on Python 3.10 and 3.11 for improved compatibility.
- Ensured minimal changes to existing code while streamlining the testing process.
2025-05-24 16:29:14 +01:00
Mervin Praison 768549bb52 Merge pull request #501 from MervinPraison/develop
Develop
2025-05-24 16:00:41 +01:00
MervinPraison 5d1bc19e15 Update version to 2.2.3 and enhance test configurations
- Incremented PraisonAI version from 2.2.2 to 2.2.3 in `pyproject.toml`, `uv.lock`, and Dockerfiles for consistency.
- Updated `.gitignore` to include exceptions for CrewAI test directories.
- Added new test markers in `pytest.ini` for better categorisation of tests.
- Enhanced GitHub Actions workflows to include new test patterns for AutoGen and CrewAI frameworks.
- Refactored test runner to improve clarity and user experience, including warnings for real tests and full execution tests.
- Ensured minimal changes to existing code while improving overall test structure and documentation.
2025-05-24 15:59:57 +01:00
MervinPraison 05a114f939 Update GitHub Actions workflows to use actions/setup-python@v5
- Modified multiple workflow files to upgrade actions/setup-python from version 4 to version 5 for improved functionality and consistency.
- Ensured minimal changes to existing code while enhancing the setup process for Python environments.
2025-05-24 14:00:02 +01:00
MervinPraison 4b9d291d16 Update GitHub Actions workflows to use latest action versions
- Upgraded actions/checkout to version 4 and actions/setup-python to version 5 across multiple workflow files for improved functionality.
- Updated actions/upload-artifact to version 4 in relevant workflows to enhance artifact management.
2025-05-24 13:54:03 +01:00
MervinPraison 5eb8862a7e Update dependencies and refactor test functions for clarity
- Added `pytest-asyncio` as a dependency in `pyproject.toml` for improved async testing capabilities.
- Updated GitHub Actions workflow to include `pytest-cov` for coverage reporting.
- Renamed test functions in `advanced_example.py` and `basic_example.py` for better clarity and user-friendliness.
- Removed unused event loop fixture from `conftest.py` to streamline test setup.
- Enhanced assertions in various tests to ensure better error reporting and maintainability.
2025-05-24 13:48:22 +01:00
MervinPraison 0bacff3997 Add simple test runner and basic diagnostic tests
- Introduced a new simple test runner (`simple_test_runner.py`) that operates without pytest dependency at import time.
- Added a basic diagnostic test script (`test_basic.py`) to validate Python and module imports.
- Updated `README.md` to include new test runner instructions and troubleshooting tips for pytest import issues.
- Enhanced `test_runner.py` to conditionally import pytest and fallback to subprocess if not available, maintaining existing functionality.
- Ensured backward compatibility with existing tests and workflows.
2025-05-24 13:14:24 +01:00
MervinPraison ac8e6daadf Refactor GitHub Actions workflow for quick validation tests
- Renamed workflow from 'Run specific unittest' to 'Quick Validation Tests'.
- Introduced a new job 'quick-test' for streamlined testing.
- Added installation of pytest and pytest-asyncio for enhanced testing capabilities.
- Updated test command to run legacy example tests using pytest with improved output options.
- Included environment variable for PYTHONPATH to facilitate module resolution.
2025-05-24 13:08:14 +01:00
MervinPraison f4cf97abdb Update GitHub Actions workflow to use latest action versions and improve installation commands
- Upgraded actions/checkout and actions/setup-python to version 4.
- Changed UV installation method to use a script for better integration.
- Modified dependency installation commands to include the --system flag for UV.
- Enhanced unittest command to run with verbose output for clearer test results.
2025-05-24 08:25:23 +01:00
Mervin Praison 2f0e3c0507 Merge pull request #498 from MervinPraison/develop
Update version numbers and dependencies to 2.2.2 and 0.0.87 across pr…
2025-05-24 08:23:33 +01:00
MervinPraison 5e11f7566d Update version numbers and dependencies to 2.2.2 and 0.0.87 across project files
- Incremented PraisonAI version from 2.2.1 to 2.2.2 in pyproject.toml, uv.lock, Dockerfiles, and documentation.
- Updated praisonaiagents version from 0.0.85 to 0.0.87 in relevant files.
- Adjusted installation commands in GitHub Actions workflow to use 'uv' for dependency management.
- Enhanced test scripts to return meaningful results for better assertion checks.
2025-05-24 08:22:57 +01:00
Mervin Praison 66a8c9e074 Merge pull request #497 from MervinPraison/claude/issue-467-20250524_055552
Claude/issue 467 20250524 055552
2025-05-24 07:33:18 +01:00
Mervin Praison 2ef8250d49 Delete tests/test_base_url_api_base_fix.py 2025-05-24 07:33:11 +01:00
Mervin Praison 090f1d1339 Merge pull request #493 from MervinPraison/claude/issue-411-20250524_055043
Fix Mini Agents sequential task data passing issue
2025-05-24 07:31:19 +01:00
Mervin Praison e299a5aaf3 Merge pull request #495 from MervinPraison/claude/issue-410-20250524_055025
Fix agent tool calls expecting strings for integer parameters
2025-05-24 07:30:42 +01:00
Mervin Praison 15bda4df81 Rename test_mini_agents_sequential.py to tests/unit/agent/test_mini_agents_sequential.py 2025-05-24 07:25:32 +01:00
Mervin Praison 57fdc5e4ed Rename test_mini_agents_fix.py to tests/unit/agent/test_mini_agents_fix.py 2025-05-24 07:25:12 +01:00
claude[bot]andMervinPraison 54cb01426f Fix undefined variable in _cast_arguments logging statement
- Replace undefined `function_name` with `getattr(func, '__name__', 'unknown function')`
- This prevents NameError when type casting fails and provides robust function name extraction
- Addresses CodeRabbit review feedback

Co-authored-by: MervinPraison <[email protected]>
2025-05-24 06:22:54 +00:00
Mervin Praison f3d61459fe Delete test_type_casting.py 2025-05-24 07:19:06 +01:00
claude[bot]andMervinPraison 53d7d7e7f7 Improve Mini Agents code quality based on review feedback
- Add TaskStatus enum for consistent status string handling
- Create centralized process_task_context() helper function to eliminate code duplication
- Fix poetry.lock sync issue by regenerating lock file
- Maintain existing functionality while improving maintainability

Addresses review feedback from CodeRabbit and Gemini reviewers about:
1. Hardcoded status strings (now use TaskStatus enum)
2. Code duplication between async/sync methods (now use shared helper)
3. CI failure due to poetry lock mismatch (regenerated lock file)

Co-authored-by: MervinPraison <[email protected]>
2025-05-24 06:18:32 +00:00
Mervin Praison c133e24816 Merge pull request #496 from MervinPraison/claude/issue-467-20250524_060326
Add comprehensive integration test for base_url to api_base mapping
2025-05-24 07:14:53 +01:00
Mervin Praison 318131bb92 Merge pull request #494 from MervinPraison/claude/issue-410-20250524_060223
Create unit test structure and add test_type_casting.py
2025-05-24 07:08:11 +01:00
claude[bot]andMervinPraison 6cfa8f30d7 Add comprehensive integration test for base_url to api_base mapping
Addresses Issue #467: Organize test suite with proper directory structure

- Created tests/integration/ directory following TypeScript test patterns
- Added comprehensive test_base_url_api_base_fix.py as integration test
- Tests specific KoboldCPP and OpenAI-compatible endpoint scenarios
- Includes backward compatibility and environment variable tests
- Mock-based testing for reliable CI/CD

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: MervinPraison <[email protected]>
2025-05-24 06:05:32 +00:00
claude[bot]andMervinPraison f6b1517aa0 Create unit test structure and add test_type_casting.py
- Created tests/unit/ directory structure following TypeScript pattern
- Added comprehensive test_type_casting.py in tests/unit/agent/
- Tests cover integer, float, boolean, mixed types, and edge cases
- Tests include graceful fallback for conversion failures
- Ready for when _cast_arguments method is implemented

Co-authored-by: MervinPraison <[email protected]>
2025-05-24 06:04:56 +00:00
claude[bot]andMervinPraison 624837356e Add comprehensive test suite for base_url to api_base mapping fix
- Addresses Issue #467: litellm compatibility with OpenAI-compatible endpoints
- Tests specific KoboldCPP and OpenAI-compatible endpoint scenarios
- Includes backward compatibility and environment variable tests
- Mock-based testing to avoid external dependencies
- Verifies both base_url and api_base parameters are properly passed to litellm

Co-authored-by: MervinPraison <[email protected]>
2025-05-24 05:58:19 +00:00
claude[bot]andMervinPraison df12ae032f Fix Mini Agents sequential task data passing issue
- Improved context processing to validate task completion status
- Fixed context formatting from space-separated to newline-separated 
- Added better error handling for incomplete tasks
- Enhanced debugging with verbose logging
- Added test scripts to verify the fix

This resolves the issue where output from previous tasks was not 
properly passed to subsequent tasks in Mini Agents sequential workflows.

Co-authored-by: MervinPraison <[email protected]>
2025-05-24 05:57:15 +00:00
claude[bot]andMervinPraison c405aaf121 Fix agent tool calls expecting strings for integer parameters
Added type casting utility to Agent class that converts arguments to their expected types based on function signatures:
- Converts string arguments to int, float, bool when annotations are present
- Graceful fallback if conversion fails
- Preserves existing behavior for non-annotated parameters

Fixes #410

Co-authored-by: MervinPraison <[email protected]>
2025-05-24 05:54:12 +00:00
Mervin Praison 03e2bb94f2 Merge pull request #492 from MervinPraison/claude/issue-469-20250523_220748
Fix UnicodeDecodeError in Docker for MCP Google Maps
2025-05-23 23:21:23 +01:00
claude[bot]andMervinPraison 5e3e503dd9 Fix UnicodeDecodeError in Docker for MCP Google Maps initialization
- Add explicit UTF-8 encoding to all subprocess.run() calls in npx_mcp_wrapper_main.py
- Set UTF-8 environment variables (PYTHONIOENCODING, LC_ALL, LANG) in both MCP classes  
- Add UTF-8 encoding to temporary script file creation
- Ensure environment variables are passed to subprocess calls

This resolves the 'ascii' codec can't decode byte 0xc2 error that occurs during
MCP server initialization in Docker containers with minimal locale settings.

Fixes #469

Co-authored-by: MervinPraison <[email protected]>
2025-05-23 22:12:35 +00:00
Mervin Praison 633d724eb2 Merge pull request #485 from MervinPraison/develop
Increment version to 0.0.84 in `pyproject.toml` and `uv.lock`, update…
2025-05-23 23:00:34 +01:00
MervinPraison 5cfda3fa54 Increment version to 2.2.1 in pyproject.toml, uv.lock, and Dockerfiles, and update praisonaiagents version to 0.0.85 across relevant files for improved functionality and compatibility. 2025-05-23 23:00:10 +01:00
MervinPraison 370cb108f2 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI into develop 2025-05-23 22:54:18 +01:00
Mervin Praison 83cb80e907 Merge pull request #487 from MervinPraison/claude/issue-482-20250523_112045
fix: Pass base_url, api_key, and other essential parameters to all litellm calls
2025-05-23 13:37:08 +01:00
claude[bot]andMervinPraison f385de04e0 fix: Pass base_url, api_key, and other essential parameters to all litellm calls
- Add _build_completion_params() method to centralize parameter handling
- Update all 24+ litellm.completion() and litellm.acompletion() calls to use the new method
- Fix async/sync inconsistencies in get_response_async() method
- Ensure base_url, api_key, api_version, timeout, and other configured parameters are consistently passed to litellm
- Resolves connection issues for Ollama and other providers using custom base URLs

Fixes #482

Co-authored-by: MervinPraison <[email protected]>
2025-05-23 11:28:45 +00:00
Mervin Praison 18695543e5 Merge pull request #486 from MervinPraison/add-claude-github-actions-1747999126084
Add Claude Code GitHub Workflow
2025-05-23 12:20:13 +01:00
Mervin Praison 267f223a3e Add Claude PR Assistant workflow 2025-05-23 12:18:47 +01:00
MervinPraison 02bd52a06d Increment version to 0.0.84 in pyproject.toml and uv.lock, update agent functionality in mcp-sse.py and openai-mcp.py for improved task handling, and enhance timeout management in MCP tools for better performance. 2025-05-22 15:35:45 +01:00
Mervin Praison 076576af85 Merge pull request #480 from MervinPraison/develop
v2.2 with MCP SSE and STDIO
2025-05-17 05:03:27 +01:00
MervinPraison 17547073ec v2.2 with MCP SSE and STDIO 2025-05-15 16:01:28 +01:00
Mervin Praison 124a95d7d0 Merge pull request #479 from MervinPraison/develop
Remove agent names and version constraints in MCP server documentation
2025-05-15 12:04:45 +01:00
MervinPraison 8ca4e3285d Remove agent names and version constraints in MCP server documentation 2025-05-15 12:04:07 +01:00
Mervin Praison 5eac60dab3 Merge pull request #478 from MervinPraison/develop
2.1.6
2025-05-15 07:54:46 +01:00
MervinPraison 59ee7cbbe5 Add MCP server examples and deployment docs with version bump to 2.1.6 2025-05-15 07:54:17 +01:00
MervinPraison 81517b58e5 Increment version to 0.0.82 in pyproject.toml and uv.lock, and enhance agent launch functionality in agents.py to support both HTTP and MCP protocols, including improved endpoint management, healthcheck capabilities, and error handling for agent execution. 2025-05-15 07:42:53 +01:00
Mervin Praison c1a8338a24 Merge pull request #477 from MervinPraison/develop
multi agents deploy
2025-05-14 13:08:57 +01:00
MervinPraison dba5a49569 multi agents deploy 2025-05-14 13:08:18 +01:00
Mervin Praison 6dab69e9d7 Merge pull request #476 from MervinPraison/develop
Add multi-agent API functionality in `multi-agents-api.py` and `multi…
2025-05-14 12:50:13 +01:00
MervinPraison 90563207f7 Add multi-agent API functionality in multi-agents-api.py and multi-agents-group-api.py, increment version to 0.0.80 in pyproject.toml and uv.lock, and enhance agent launch logic in agents.py with improved endpoint management and healthcheck capabilities. 2025-05-14 12:49:58 +01:00
Mervin Praison 46330b0487 Merge pull request #475 from MervinPraison/develop
v2.1.4
2025-05-14 10:49:01 +01:00
MervinPraison a133f0d5e2 Update package versions and add deployment documentation 2025-05-14 10:48:27 +01:00
MervinPraison fb22e6e1c7 Refactor agent launch functionality in multi-agent-api.py to remove blocking parameters, update version to 0.0.79 in pyproject.toml and uv.lock, and enhance server startup logic in agent.py with healthcheck endpoint and improved thread management. 2025-05-14 09:13:40 +01:00
Mervin Praison e938fe63ea Merge pull request #473 from emmanuel-ferdman/main
Resolve Python Logger warnings
2025-05-14 06:33:25 +01:00
Mervin Praison ef96e53843 Merge pull request #474 from MervinPraison/develop
Increment version to 0.0.78 in `pyproject.toml`, add API dependencies…
2025-05-14 06:32:05 +01:00
MervinPraison 036c463a43 Increment version to 0.0.78 in pyproject.toml, add API dependencies for FastAPI and Uvicorn, and implement HTTP API launch functionality in agent.py for enhanced agent interaction. 2025-05-14 06:30:42 +01:00
Emmanuel Ferdman 0e6b4aefc3 Resolve Python Logger warnings
Signed-off-by: Emmanuel Ferdman <[email protected]>
2025-05-13 14:08:22 -07:00
Mervin Praison bbb9f677ae Merge pull request #472 from MervinPraison/develop
Add STDIO MCP documentation and update navigation menu
2025-05-13 16:40:35 +01:00
MervinPraison 0da201b3b6 Add STDIO MCP documentation and update navigation menu 2025-05-13 16:40:20 +01:00
Mervin Praison a7b85043e1 Merge pull request #470 from elandau1260/add_repot_path_to_env
Added PRAISONAI_CODE_REPO_PATH env variable to point code to differen…
2025-05-13 14:55:28 +01:00
Mervin Praison dc393e1211 Merge pull request #456 from MervinPraison/develop
Increment version to 0.0.77 in `pyproject.toml` and update `markitdow…
2025-05-13 14:47:44 +01:00
MervinPraison fdff17faf9 MCP SSE Docs 2025-05-13 14:46:11 +01:00
MervinPraison b3d893fae1 Implement SSEMCPClient and SSEMCPTool for MCP server interaction, enhance logging configuration, and increment version to 0.0.77 in pyproject.toml and uv.lock for improved functionality. 2025-05-13 14:29:41 +01:00
MervinPraison d92dede515 Re-add mcp-sse-direct-agent.py without API key 2025-05-13 14:01:35 +01:00
MervinPraison a1882233dc mcp sse 2025-05-13 13:55:32 +01:00
Ed Landau aa6b6ac62e Added PRAISONAI_CODE_REPO_PATH env variable to point code to different repot 2025-05-02 13:01:21 -07:00
MervinPraison c540ba34fb Increment version to 0.0.76 in pyproject.toml and update markitdown dependency to include all extras in uv.lock for enhanced functionality. 2025-04-08 12:05:03 +01:00
Mervin Praison 0abb1b659a Merge pull request #455 from MervinPraison/develop
Increment version to 0.0.75 in `pyproject.toml` and update Python com…
2025-04-08 11:49:15 +01:00
MervinPraison 81adb28688 Increment version to 0.0.75 in pyproject.toml and update Python compatibility requirements in uv.lock to support Python 3.11 and above. 2025-04-08 11:48:53 +01:00
Mervin Praison 5fbe6e948c Merge pull request #450 from ihsankursadunal/add-to-vector-store-fifth-positional-argument
RAG knowledge positional argument error fix
2025-04-08 11:48:11 +01:00
Mervin Praison 6128e4c885 Merge pull request #454 from MervinPraison/develop
Add new Databutton and Research agents in `databutton-mcp.py` and `mc…
2025-04-08 11:35:34 +01:00
MervinPraison 0e563989ed Add new Databutton and Research agents in databutton-mcp.py and mcp-llama4.py, respectively. Increment version to 0.0.74 in pyproject.toml and update Python requirements in uv.lock for compatibility with Python 3.13. 2025-04-08 11:34:37 +01:00
Mervin Praison 510a853e05 Merge pull request #453 from chonknick/update-chonkie-v102
Fix: breaking change with Chonkie `v1.0.2` — `WordChunker` not found
2025-04-08 11:32:13 +01:00
Bhavnick @ chonkie.ai d6084cb7ce Update chonkie dependency version to 1.0.2 in pyproject.toml and requirements.txt for improved compatibility. 2025-04-07 23:45:26 +05:30
Bhavnick @ chonkie.ai 8d4b1c411b Enhance chunking method: Disable unsupported context parameters and add warning for future support. Track in https://github.com/chonkie-inc/chonkie/issues/21 2025-04-07 23:38:37 +05:30
bhavnicksm 3be05c855b Fix: Remove WordChunker + Disable OverlapRefinery (temporarily) 2025-04-07 23:18:43 +05:30
bhavnicksm 3e5a2f76f4 Update chonkie version to the latest v1.0.2 2025-04-07 23:18:14 +05:30
ihsankursadunal 8eee881d2e RAG knowledge positional argument error fix 2025-04-06 13:09:35 +03:00
Mervin Praison d75f4be41a Merge pull request #448 from MervinPraison/develop
Develop
2025-04-03 06:47:51 +01:00
MervinPraison 9ea89448ef Increment version number to 0.0.73 in pyproject.toml and uv.lock to reflect recent updates. 2025-04-03 06:47:35 +01:00
MervinPraison 0a5e2df278 Merge PR #409: Support chat without stream while maintaining stream=True as default 2025-04-03 06:30:23 +01:00
MervinPraison cc3b64f89b fix: keep default stream=True while supporting stream=False option 2025-04-03 06:30:04 +01:00
Mervin Praison 546dc5a441 Merge pull request #391 from yiranwu0/main
Update AG2 reference
2025-04-02 21:44:22 +01:00
Mervin Praison bd7422c7ca Merge pull request #443 from MervinPraison/develop
Add WhatsApp and Perplexity MCP Integrations
2025-04-02 09:54:17 +01:00
MervinPraison 0c2c6da8dd Add WhatsApp and Perplexity MCP Integrations
- Included new MCP tools for WhatsApp and Perplexity in `mint.json` for enhanced functionality.
- Updated installation instructions in `openrouter.mdx` and `xai.mdx` to specify the correct package format.
- Added detailed documentation for WhatsApp and Perplexity integrations, including setup steps and example scripts.
- Incremented version number to 0.0.72 in `pyproject.toml` and `uv.lock` to reflect recent changes.
2025-04-02 09:54:02 +01:00
Mervin Praison b43688086f Merge pull request #442 from MervinPraison/develop
Update to version 2.1.1
2025-04-01 22:22:06 +01:00
MervinPraison 820619e8d9 Update to version 2.1.1
- Incremented version number to 2.1.1 in `pyproject.toml`, `praisonai.rb`, and `uv.lock` to reflect recent changes.
- Updated dependency version for `praisonaiagents` to 0.0.71 in `pyproject.toml` and `uv.lock`.
- Modified Dockerfile and deployment scripts to install the updated version of `praisonai`.
- Added new documentation files for various MCP integrations, including Anthropic, Gemini, Groq, Mistral, Ollama, OpenAI, and XAI.
- Introduced example scripts for each MCP integration to facilitate user understanding and implementation.
- Enhanced the LLM class to process tool results based on the original user query for improved response accuracy.
2025-04-01 22:21:50 +01:00
Mervin Praison 94202adddd Merge pull request #441 from MervinPraison/develop
Version 2.1
2025-04-01 21:14:15 +01:00
MervinPraison c7911629b1 Version 2.1 2025-04-01 21:13:30 +01:00
Mervin Praison 5a4e3ba707 Merge pull request #440 from MervinPraison/develop
Update LLM and MCP Integration
2025-04-01 17:54:05 +01:00
MervinPraison 641057b622 Update LLM and MCP Integration
- Changed the LLM model from "groq/llama-3.3-70b-versatile" to "groq/llama-3.2-90b-vision-preview" in `groq-mcp.py` for improved performance.
- Added a new example script `ollama-python.py` for stock price retrieval using the Ollama model.
- Incremented version number to 0.0.70 in `pyproject.toml` to reflect recent changes.
- Updated Python version requirement in `uv.lock` to support Python 3.11 and above for better compatibility.
- Enhanced the LLM class to handle tool calls specifically for Ollama models, ensuring proper processing of tool results.
2025-04-01 17:53:45 +01:00
Mervin Praison db1dbf142e Merge pull request #438 from MervinPraison/develop
groq support included
2025-04-01 13:51:43 +01:00
MervinPraison d9a19ae277 groq support included 2025-04-01 13:51:24 +01:00
Mervin Praison 3c9d889b4f Merge pull request #437 from MervinPraison/develop
Add MCP Integration and Update Documentation
2025-03-31 13:24:04 +01:00
MervinPraison 2f324e74db Add MCP Integration and Update Documentation
- Added `mcp` dependency to `pyproject.toml` for enhanced functionality.
- Introduced new example scripts for various MCP tools, including `fetch-mcp.py`, `git-mcp.py`, `ollama.py`, `sentry-mcp.py`, and `time-mcp.py`, to demonstrate their usage.
- Updated `airbnb.mdx` to reflect the addition of the Airbnb tool to the AI agent.
- Enhanced the `Agent` class to support MCP tools and ensure proper integration with custom LLMs.
- Improved logging for better debugging and tool management.
- Incremented version number to 0.0.68 in `pyproject.toml` for release clarity.
2025-03-31 13:23:49 +01:00
Mervin Praison c22fef3e6d Merge pull request #436 from MervinPraison/develop
Enhance MCP Documentation and Integration
2025-03-31 09:47:52 +01:00
MervinPraison 53bee19948 Enhance MCP Documentation and Integration
- Updated `mint.json` to include additional MCP pages for improved navigation.
- Added new documentation files for various MCP integrations, including AWS KB Retrieval, Everart, Filesystem, Google Drive, GitHub, GitLab, Google Maps, Memory, PostgreSQL, Puppeteer, Redis, Sequential Thinking, Slack, and Stock Price.
- Introduced example scripts for each MCP integration to facilitate user understanding and implementation.
- Ensured consistency in documentation format and clarity in instructions for setting up and using MCP tools.
2025-03-31 09:47:38 +01:00
kevin666aa 798fe68908 update reference 2025-03-30 16:40:06 -04:00
kevin666aa 95796cd4c7 Merge remote-tracking branch 'upstream/main' 2025-03-30 16:22:40 -04:00
Mervin Praison b447b7e6eb Merge pull request #434 from MervinPraison/develop
Add Gradio UI for Airbnb Booking Assistant
2025-03-29 20:55:04 +00:00
MervinPraison 29dfe4b192 Add Gradio UI for Airbnb Booking Assistant
- Introduced a new Gradio interface in `airbnb.mdx` and `ui.py` for searching and booking apartments on Airbnb.
- Implemented the `search_airbnb` function to handle user queries and display results.
- Enhanced user experience with a clear input prompt and structured output format.
2025-03-29 20:54:38 +00:00
Mervin Praison aca95b1713 Merge pull request #433 from MervinPraison/develop
Update navigation and MCP integration
2025-03-29 19:18:34 +00:00
MervinPraison b4cc3d7a8e Update navigation and MCP integration
- Added "MCP" section to `mint.json` for improved documentation navigation.
- Integrated environment variable for `BRAVE_API_KEY` in `mcp-npx-brave.py` to enhance security and flexibility.
- Updated search agent prompt for better clarity.
2025-03-29 19:17:27 +00:00
Mervin Praison c6c27e58a6 Merge pull request #432 from MervinPraison/develop
adding other changes
2025-03-29 17:59:16 +00:00
MervinPraison ae21881522 adding other changes 2025-03-29 17:58:51 +00:00
Mervin Praison 68efb982af Merge pull request #429 from MervinPraison/develop
Add MCP integration for stock price retrieval
2025-03-29 17:58:05 +00:00
MervinPraison c539306b96 Increment version number in pyproject.toml to 2.0.81 2025-03-29 17:57:31 +00:00
MervinPraison c2f2d43d0d adding mcp 2025-03-29 17:57:10 +00:00
MervinPraison 7847515b4b adding mcp npx 2025-03-29 17:55:09 +00:00
Mervin Praison 1f2c412521 Merge pull request #428 from asiffarhankhan/main
Add .py files for all existing .mdx tools, Add .mdx, .py for the new AgentQL tool
2025-03-26 06:06:06 +00:00
asiffarhankhan 355fe1e59c Add local test file 2025-03-23 12:26:56 +05:30
asiffarhankhan 2ed64adc48 Remove API key from code 2025-03-23 12:19:55 +05:30
asiffarhankhan b8bc8583b1 Add agentql tool 2025-03-23 12:13:04 +05:30
asiffarhankhan 51a3a065c4 Add Python Files for existing MDX tools 2025-03-23 04:52:18 +05:30
Mervin Praison 4ba8745544 Merge pull request #427 from bhavnicksm/update-chonkie-config
Fix: `tokenizer` is not recognized error with `chonkie.RecursiveChunker`
2025-03-20 06:03:10 +00:00
bhavnicksm efc347f507 Update chonkie dependency version to ensure compatibility 2025-03-20 05:45:05 +05:30
bhavnicksm 72a162c722 Refactor tokenizer parameter in Chunking class for consistency and clarity 2025-03-20 05:41:02 +05:30
bhavnicksm 734a632dd4 Update chonkie dependency version in requirements.txt 2025-03-20 05:35:11 +05:30
MervinPraison dfaa3ed671 Add MCP integration for stock price retrieval
- Introduced multiple new files for MCP agent functionality, including `mcp-agents-detailed.py`, `mcp-agents.py`, `mcp-basic.py`, `mcp-multiagents.py`, and `mcp-test.py`.
- Implemented a dedicated `MCP` class for managing connections and tool execution.
- Created an asynchronous function to retrieve stock prices using MCP tools.
- Added example agents for stock price checking and web searching.
- Updated `pyproject.toml` and `uv.lock` to reflect version increment to 0.0.66.
- Ensured backward compatibility and improved tool function generation for better usability.
2025-03-18 18:23:39 +00:00
Mervin Praison 175b55704d Merge pull request #425 from asiffarhankhan/main
Add Bearly, Azure and Jina Code Interpreter
2025-03-18 16:56:19 +00:00
asiffarhankhan 084d1a2820 Add Azure and Jina, Bearly Code Interpreter 2025-03-17 23:46:41 +05:30
asiffarhankhan 8518c3ae9d Add Azure and Jina Code Inerpreter 2025-03-17 23:33:33 +05:30
Mervin Praison ac95c0000b Merge pull request #419 from asiffarhankhan/main
Add SearchAPI, YouSearch, TavillySearch tools
2025-03-17 13:38:39 +00:00
asiffarhankhan 8447e02f5d Merge branch 'main' of github.com:asiffarhankhan/PraisonAI 2025-03-15 15:07:38 +05:30
asiffarhankhan 3e612f61dc Add SearchAPI, YouSearch, TavillySearch tools 2025-03-15 15:06:07 +05:30
Mervin Praison b39c04dfb5 Merge pull request #417 from asiffarhankhan/main
Add MDX for Google and Jina Search
2025-03-14 04:46:44 +00:00
asiffarhankhan 8fc367ee6d Add "YOUR_API_KEY" placeholder to empty API variable 2025-03-12 14:26:43 +05:30
asiffarhankhan f7f157d3e7 Update Jina Search to MDX format 2025-03-12 14:19:49 +05:30
asiffarhankhan 05ede2a366 Add Google, Jina Search tools 2025-03-12 14:14:06 +05:30
Mervin Praison f8a2a93400 Merge pull request #416 from MervinPraison/develop
Add playground documentation to navigation
2025-03-11 10:34:12 +00:00
MervinPraison 1a77826a21 Add playground documentation to navigation
- Updated `mint.json` to include the "playground" page in the documentation navigation
- Positioned under the "Other Features" group for easy access
2025-03-11 10:33:54 +00:00
Mervin Praison adfd982547 Merge pull request #415 from MervinPraison/develop
updates
2025-03-11 09:43:36 +00:00
MervinPraison facd52103e updates 2025-03-11 09:42:04 +00:00
Mervin Praison 06d3d3decb Merge pull request #414 from MervinPraison/develop
Add course documentation for AI Agents
2025-03-11 04:59:27 +00:00
MervinPraison 7f35ac6113 Add course documentation for AI Agents
- Created a comprehensive course on AI Agents covering 20 lessons
- Included documentation for course topics like agent architecture, tools, memory, multi-agent systems, and deployment
- Added structured MDX files for each lesson with code examples, explanations, and best practices
- Updated `mint.json` to include new course navigation and pages
- Provided a step-by-step learning path for understanding and building AI agents
2025-03-11 04:58:56 +00:00
Mervin Praison e68fbb46f6 Merge pull request #413 from MervinPraison/develop
Add documentation for additional search tools
2025-03-11 04:10:25 +00:00
MervinPraison 50a7bf6c91 Add documentation for additional search tools
- Updated `mint.json` to include new search tools
- Added documentation pages for DuckDuckGo, Exa, Google Serper, Serp, and Wikipedia search tools
- Included installation instructions, overview, and example code for each search tool
2025-03-11 04:10:02 +00:00
Yuga Sun eaf337b301 fix: remove default stream value for agent 2025-03-11 04:07:40 +00:00
Mervin Praison bce6e424d8 Merge pull request #412 from asiffarhankhan/main
Add search based tools using wikipedia, serper, serp, brave, exa, duckduckgo
2025-03-11 04:01:30 +00:00
asiffarhankhan 5cad05dc0d Align .py files with existing .mdx files 2025-03-11 00:37:40 +05:30
asiffarhankhan 3ecc722866 Add search based tools using wikipedia, serper, serp, brave, exa, duckduckgo 2025-03-11 00:32:02 +05:30
Yuga Sun 2f73cf1882 fix: support chat without stream 2025-03-10 08:00:05 +00:00
Mervin Praison c881fb3280 Merge pull request #408 from MervinPraison/develop
Refactor tools documentation with comprehensive examples and improved…
2025-03-10 06:20:01 +00:00
MervinPraison 15f9cbbe47 Refactor tools documentation with comprehensive examples and improved structure
- Updated tools documentation with new tabbed interface
- Added detailed code and no-code examples for tool creation
- Simplified tool registration and agent configuration examples
- Improved readability and provided step-by-step guidance for tool implementation
2025-03-10 06:19:41 +00:00
Mervin Praison f431347793 Merge pull request #407 from MervinPraison/develop
Add Langchain external search tool examples for PraisonAI agents
2025-03-10 06:03:11 +00:00
MervinPraison e0725c1296 Add Langchain external search tool examples for PraisonAI agents
- Introduced example scripts for Brave Search, Google Trends, and SerpAPI
- Demonstrated multi-agent workflows using external search tools
- Added API key configuration instructions for each search tool
- Included examples of research and content generation agents using search capabilities
2025-03-10 06:02:45 +00:00
Mervin Praison b40295efb9 Merge pull request #406 from MervinPraison/develop
Add external search tool documentation for PraisonAI agents
2025-03-10 05:54:34 +00:00
MervinPraison 2f7769d334 Add external search tool documentation for PraisonAI agents
- Updated `mint.json` to include new external tools section
- Expanded `langchain_tools.mdx` with more comprehensive examples and explanations
- Added documentation pages for BraveSearch, Google Trends, and SerpAPI tools
- Included installation, setup, and usage examples for external search tools
- Organized new documentation under the "External Tools" group
2025-03-10 05:54:13 +00:00
Mervin Praison c326aaf015 Merge pull request #405 from MervinPraison/develop
Add TypeScript documentation and examples for AI agent tools
2025-03-04 20:52:08 +00:00
MervinPraison 03874553eb Add TypeScript documentation and examples for AI agent tools
- Expanded documentation for TypeScript AI agents with tool registration examples
- Added new documentation pages for custom tools in TypeScript
- Updated installation and quickstart guides to include TypeScript sections
- Created example scripts demonstrating single and multi-agent tool usage
- Introduced new documentation for external tools like Google Trends
2025-03-04 20:51:53 +00:00
Mervin Praison 97ae6647c9 Merge pull request #403 from MervinPraison/develop
Expand tool registration documentation and examples
2025-03-03 08:25:09 +00:00
MervinPraison 046fb7cbe7 Expand tool registration documentation and examples
- Added comprehensive TypeScript documentation for tool registration methods in `docs/js/typescript.mdx`
- Created new README example file `examples/README-tool-examples.md` with detailed tool registration approaches
- Updated example scripts to demonstrate direct function tool registration
- Refined agent tool registration logic to support multiple function registration styles
- Bumped package version to 1.0.19
2025-03-03 08:24:46 +00:00
Mervin Praison afdd6ab6f8 Merge pull request #402 from MervinPraison/develop
Enhance agent tool function registration with direct function support
2025-03-03 08:13:52 +00:00
MervinPraison 4581486a81 Enhance agent tool function registration with direct function support
- Added support for directly registering tool functions without global declaration
- Implemented auto-generation of tool definitions for registered functions
- Created new example scripts demonstrating direct function tool registration
- Updated package version to 1.0.18
- Expanded Agent configuration to support `toolFunctions` property
- Added type exports for improved type safety
2025-03-03 08:13:31 +00:00
Mervin Praison e10b991fab Merge pull request #401 from MervinPraison/develop
npm 1.0.17 praisonai
2025-03-03 07:52:40 +00:00
MervinPraison 2d790f79a9 Add tool call support for agents with multi-tool and single-tool test cases
- Enhanced OpenAI service to support tool calls in chat and text generation methods
- Updated Agent classes to register and process tool functions dynamically
- Added new test cases for single and multi-tool agent interactions
- Improved type safety and conversion for OpenAI tool and message formats
- Bumped package version to 1.0.17
2025-03-03 07:52:07 +00:00
MervinPraison ec04dd7a91 test 7 2025-02-28 17:12:25 +00:00
MervinPraison bd49416f2b test 6 2025-02-28 17:05:09 +00:00
MervinPraison da2e11921c test 5 2025-02-28 17:03:42 +00:00
MervinPraison 8287c3a3d4 test 4 2025-02-28 16:57:02 +00:00
MervinPraison 6904f86557 test 3 2025-02-28 16:54:54 +00:00
MervinPraison cbebb3a900 test 2 2025-02-28 16:53:48 +00:00
MervinPraison 413484ea9f test 2025-02-28 16:36:58 +00:00
MervinPraison 785317c4fa test 2025-02-28 11:56:13 +00:00
MervinPraison c70f9ebf1f Add package.json and update documentation requirements
- Created package.json for documentation with Mintlify dev and build scripts
- Updated requirements.in with additional documentation and tool dependencies
- Removed redundant requirements.txt file
- Added support for enhanced documentation generation and API documentation
2025-02-28 11:51:31 +00:00
Mervin Praison d278f2d2b2 Merge pull request #399 from MervinPraison/develop
Bump version to 2.0.80 and update praisonaiagents dependency
2025-02-28 10:25:47 +00:00
MervinPraison df4596a699 Bump version to 2.0.80 and update praisonaiagents dependency
- Updated version to 2.0.80 across multiple files including praisonai.rb, pyproject.toml, uv.lock, Dockerfile, and docs
- Upgraded praisonaiagents dependency from 0.0.64 to 0.0.65
- Enhanced agent start methods with optional return_dict parameter
- Improved result handling in start and astart methods to return final response by default
- Synchronized version updates across project configuration files
2025-02-28 10:25:32 +00:00
Mervin Praison dd0f47ec81 Merge pull request #398 from MervinPraison/develop
Bump version to 2.0.79 and update praisonaiagents dependency
2025-02-28 07:26:52 +00:00
MervinPraison e53017a2fe Bump version to 2.0.79 and update praisonaiagents dependency
- Updated version to 2.0.79 across multiple files including praisonai.rb, pyproject.toml, uv.lock, Dockerfile, and docs
- Upgraded praisonaiagents dependency from 0.0.63 to 0.0.64
- Updated example agent scripts for Anthropic and Gemini LLMs
- Added parameter modification support in LLM initialization
- Synchronized version updates across project configuration files
2025-02-28 07:26:22 +00:00
Mervin Praison fe034ba8f4 Merge pull request #397 from MervinPraison/develop
Enhance Agent Tool Execution Logging and Debugging
2025-02-28 07:05:13 +00:00
MervinPraison 063e5780d6 Enhance Agent Tool Execution Logging and Debugging
- Added comprehensive debug logging for tool execution in LLM and Agent components
- Improved display of tool call messages with more detailed information
- Added logging for empty content and tool execution scenarios
- Enhanced error handling and logging in display functions
- Added new Anthropic LLM example script in src/praisonai-agents
- Bumped version to 2.0.78 and updated praisonaiagents dependency to 0.0.63
2025-02-28 07:04:50 +00:00
Mervin Praison 904e21ca87 Merge pull request #396 from MervinPraison/develop
v2.0.77
2025-02-27 09:12:33 +00:00
MervinPraison 526665ea11 Bump version to 2.0.77 and update praisonaiagents dependency
- Updated version to 2.0.77 across multiple files including praisonai.rb, pyproject.toml, uv.lock, Dockerfile, and docs
- Upgraded praisonaiagents dependency from 0.0.61 to 0.0.62
- Synchronized version updates across project configuration files
2025-02-27 09:11:18 +00:00
MervinPraison c2e97d2432 adding litellm tools fix 2025-02-27 09:08:22 +00:00
MervinPraison 60be6a1f99 Add Comprehensive Debug Logging to LLM and Agent Components
- Enhanced LLM and Agent classes with detailed debug logging capabilities
- Added parameter and configuration logging for get_response and chat methods
- Implemented time tracking for method execution in debug mode
- Masked sensitive information like API keys in logs
- Created new Wikipedia agent example script demonstrating agent initialization
2025-02-27 06:54:32 +00:00
kevin666aa 680949742e Merge remote-tracking branch 'upstream/main' 2025-02-13 15:44:32 -05:00
kevin666aa 560219dcd7 update 2025-02-13 13:39:48 -05:00
Mervin Praison 0ba7d2e834 Merge pull request #385 from MervinPraison/develop
Add Vision Model Upload Functionality and Enhance Training Workflow
2025-02-09 21:23:38 +00:00
MervinPraison 184b241395 Add Vision Model Upload Functionality and Enhance Training Workflow
- Introduced new upload_vision.py script for comprehensive model upload capabilities
- Extended train_vision.py with additional upload methods for Hugging Face and Ollama
- Added support for saving merged models, pushing GGUF models, and creating Ollama models
- Implemented flexible upload targeting with configurable options
- Enhanced model preparation and deployment workflow for vision models
2025-02-09 21:23:24 +00:00
Mervin Praison 4354e76fe5 Merge pull request #383 from MervinPraison/develop
Enhance Vision Model Training with Robust Dataset Conversion and Memo…
2025-02-09 02:46:01 +00:00
MervinPraison 4dd77efb75 Enhance Vision Model Training with Robust Dataset Conversion and Memory Optimization
- Significantly improved train_vision.py with more robust dataset conversion process
- Added detailed debugging and logging for dataset loading and conversion
- Implemented advanced memory management techniques for vision model training
- Enhanced tokenizer handling with fallback mechanisms
- Updated version to 2.0.76 across all relevant files
2025-02-09 02:45:47 +00:00
Mervin Praison 11db6e18ba Merge pull request #382 from MervinPraison/develop
Add Vision Model Training Support and Update Unsloth Dependency
2025-02-09 00:31:40 +00:00
MervinPraison 0d6f698e6c Add Vision Model Training Support and Update Unsloth Dependency
- Enhanced CLI to dynamically select training script based on model type (vision vs. standard)
- Added support for detecting vision models through flexible name matching
- Updated Unsloth dependency to latest commit
- Bumped version to 2.0.75 across all relevant files
2025-02-09 00:31:20 +00:00
Mervin Praison b8574f78e2 Merge pull request #381 from MervinPraison/develop
Bump version to 2.0.74 and refactor train.py template generation
2025-02-07 13:14:32 +00:00
MervinPraison e631774a0f Bump version to 2.0.74 and refactor train.py template generation
- Updated version to 2.0.74 across multiple files (praisonai.rb, pyproject.toml, uv.lock, Dockerfile, docs)
- Simplified training template generation in train.py
- Removed complex stop tokens and simplified template structure
- Dynamically built training arguments with improved configuration flexibility
2025-02-07 13:14:16 +00:00
Mervin Praison df735aa748 Merge pull request #378 from MervinPraison/develop
Enhance train.py with Configurable Training Parameters
2025-02-06 07:48:00 +00:00
MervinPraison 3bdf5b6c65 Enhance train.py with Configurable Training Parameters
- Updated version to 2.0.73 across multiple files
- Refactored TrainModel to use configurable training parameters with default fallbacks
- Improved flexibility of training configuration by allowing custom settings via config
- Dynamically set training arguments based on provided configuration
2025-02-06 07:47:40 +00:00
Mervin Praison 361fa67108 Merge pull request #377 from MervinPraison/develop
Bump version to 2.0.72 and enhance CLI configuration in train and cli…
2025-02-06 07:26:59 +00:00
MervinPraison c5abcf362a Bump version to 2.0.72 and enhance CLI configuration in train and cli modules
- Updated version to 2.0.72 across multiple files (praisonai.rb, pyproject.toml, uv.lock, Dockerfile, docs)
- Refined CLI configuration handling in cli.py for config.yaml generation
- Simplified train.py main function to always use provided config path
- Improved configuration flexibility for training and model setup
2025-02-06 07:26:41 +00:00
Mervin Praison 7ed2d99a11 Merge pull request #376 from MervinPraison/develop
Enhance train.py CLI configuration handling and bump version to 2.0.71
2025-02-06 07:19:11 +00:00
MervinPraison 81307da7c8 Enhance train.py CLI configuration handling and bump version to 2.0.71
- Updated version to 2.0.71 across multiple files (praisonai.rb, pyproject.toml, uv.lock, Dockerfile, docs)
- Modified train.py to use existing config.yaml when no CLI arguments are provided
- Improved CLI configuration flexibility for training command
2025-02-06 07:18:56 +00:00
Mervin Praison fb75153b5c Merge pull request #373 from MervinPraison/develop
Bump version to 2.0.70 and update configuration handling
2025-02-05 06:28:07 +00:00
MervinPraison cddcfcf170 Bump version to 2.0.70 and update configuration handling
- Updated version to 2.0.70 across multiple files (praisonai.rb, pyproject.toml, uv.lock, Dockerfile, docs)
- Enhanced CLI configuration handling in cli.py to load existing config when not creating a new one
- Minor improvements to configuration management and deployment scripts
2025-02-05 06:27:50 +00:00
Mervin Praison 398b0473e0 Merge pull request #372 from MervinPraison/develop
Update train.mdx with Wandb configuration and requirements
2025-02-05 05:07:23 +00:00
MervinPraison c5d260782a Update train.mdx with Wandb configuration and requirements
- Added detailed requirements for training, including Huggingface token and model details
- Included Wandb login and configuration instructions
- Updated documentation with environment variables for Wandb logging
2025-02-05 05:07:08 +00:00
Mervin Praison 116ac5a64d Merge pull request #370 from MervinPraison/develop
Add Wandb Support for Training and Bump Version to 2.0.69
2025-02-04 11:18:42 +00:00
MervinPraison abf6e2e8d1 Add Wandb Support for Training and Bump Version to 2.0.69
- Updated version to 2.0.69 across multiple files (praisonai.rb, pyproject.toml, uv.lock, Dockerfile, docs)
- Enhanced train.py with optional Wandb logging support
- Added environment variable-based Wandb configuration
- Implemented dynamic Wandb reporting and run naming
2025-02-04 11:18:20 +00:00
Mervin Praison cb2b3617fa Merge pull request #369 from MervinPraison/develop
Bump version to 2.0.68 and enhance Ollama model template generation
2025-02-04 11:10:50 +00:00
MervinPraison 6de67c7d0d Bump version to 2.0.68 and enhance Ollama model template generation
- Updated version across multiple files (praisonai.rb, pyproject.toml, uv.lock, Dockerfile, docs)
- Significantly improved train.py's prepare_modelfile_content() method
- Added comprehensive template and stop token mapping for multiple model architectures
- Implemented dynamic template selection based on model name
- Enhanced Ollama model file generation with more flexible configuration
2025-02-04 11:10:26 +00:00
Mervin Praison 5699d90894 Merge pull request #368 from MervinPraison/develop
Enhance train.py with Dynamic Stop Token Generation for Ollama Models
2025-02-04 10:33:19 +00:00
MervinPraison 2982e8ea9c Enhance train.py with Dynamic Stop Token Generation for Ollama Models
- Added intelligent stop token inference for various model architectures in train.py
- Implemented dynamic stop token selection based on model name
- Supported models include Phi, LLaVA, Mistral, Qwen, DeepSeek, and default models
- Updated Modelfile generation to include model-specific stop tokens
- Improved Ollama model preparation flexibility
2025-02-04 10:33:05 +00:00
Mervin Praison 9dd2146342 Merge pull request #367 from MervinPraison/develop
Bump version to 2.0.66 and remove TRAIN_AVAILABLE flag
2025-02-04 09:31:20 +00:00
MervinPraison f79184a6ee Bump version to 2.0.66 and remove TRAIN_AVAILABLE flag
- Updated version across multiple files (praisonai.rb, pyproject.toml, uv.lock, Dockerfile, deploy.py, docs)
- Removed TRAIN_AVAILABLE flag from cli.py
- Simplified CLI configuration by removing optional training feature check
2025-02-04 09:31:07 +00:00
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
587 changed files with 58031 additions and 7117 deletions

No files matched your search

+8 -1885
View File
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
name: Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
claude:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
+2 -2
View File
@@ -19,9 +19,9 @@ jobs:
python-version: ["3.10", "3.11"]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v3
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
+2 -2
View File
@@ -21,9 +21,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v3
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install dependencies
+2 -2
View File
@@ -64,7 +64,7 @@ jobs:
git reset --hard ${{ steps.get_commit.outputs.commit_hash }}
- name: Setup Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'pip'
@@ -422,7 +422,7 @@ jobs:
- name: Upload test artifacts
if: always()
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: praisonai-output-${{ matrix.os }}-${{ matrix.framework }}
path: test_output/
+177
View File
@@ -0,0 +1,177 @@
name: Comprehensive Test Suite
on:
workflow_dispatch: # Allow manual triggering
inputs:
test_type:
description: 'Type of tests to run'
required: true
default: 'all'
type: choice
options:
- all
- unit
- integration
- fast
- performance
- frameworks
- autogen
- crewai
release:
types: [published, prereleased]
schedule:
# Run comprehensive tests weekly on Sundays at 3 AM UTC
- cron: '0 3 * * 0'
jobs:
comprehensive-test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.11"]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install UV
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Install dependencies
run: |
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system duckduckgo_search
uv pip install --system pytest pytest-asyncio pytest-cov pytest-benchmark
- name: Set environment variables
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
- name: Run Comprehensive Test Suite
run: |
# Determine test type from input or default to 'all'
TEST_TYPE="${{ github.event.inputs.test_type || 'all' }}"
echo "🧪 Running comprehensive test suite (type: $TEST_TYPE)"
case $TEST_TYPE in
"unit")
python tests/test_runner.py --pattern unit
;;
"integration")
python tests/test_runner.py --pattern integration
;;
"fast")
python tests/test_runner.py --pattern fast
;;
"performance")
python tests/test_runner.py --pattern "performance"
;;
"frameworks")
python tests/test_runner.py --pattern frameworks
;;
"autogen")
python tests/test_runner.py --pattern autogen
;;
"crewai")
python tests/test_runner.py --pattern crewai
;;
"all"|*)
python tests/test_runner.py --pattern all
;;
esac
- name: Generate Comprehensive Test Report
if: always()
run: |
echo "# 📋 Comprehensive Test Report" > comprehensive_report.md
echo "" >> comprehensive_report.md
echo "**Python Version:** ${{ matrix.python-version }}" >> comprehensive_report.md
echo "**Test Type:** ${{ github.event.inputs.test_type || 'all' }}" >> comprehensive_report.md
echo "**Trigger:** ${{ github.event_name }}" >> comprehensive_report.md
echo "**Date:** $(date -u)" >> comprehensive_report.md
echo "" >> comprehensive_report.md
echo "## 🧪 Test Categories Covered:" >> comprehensive_report.md
echo "" >> comprehensive_report.md
echo "### Unit Tests:" >> comprehensive_report.md
echo "- ✅ Core agent functionality" >> comprehensive_report.md
echo "- ✅ Async operations" >> comprehensive_report.md
echo "- ✅ Tool integrations" >> comprehensive_report.md
echo "- ✅ UI components" >> comprehensive_report.md
echo "" >> comprehensive_report.md
echo "### Integration Tests:" >> comprehensive_report.md
echo "- ✅ MCP (Model Context Protocol)" >> comprehensive_report.md
echo "- ✅ RAG (Retrieval Augmented Generation)" >> comprehensive_report.md
echo "- ✅ Base URL API mapping" >> comprehensive_report.md
echo "- ✅ Multi-agent workflows" >> comprehensive_report.md
echo "- ✅ AutoGen framework integration" >> comprehensive_report.md
echo "- ✅ CrewAI framework integration" >> comprehensive_report.md
echo "- 💬 LLM integrations (OpenAI, Anthropic, etc.)" >> comprehensive_report.md
echo "- 🖥️ UI frameworks (Gradio, Streamlit)" >> comprehensive_report.md
echo "- 📊 Memory and persistence" >> comprehensive_report.md
echo "- 🌐 Multi-modal capabilities" >> comprehensive_report.md
echo "- ✅ AutoGen framework integration" >> comprehensive_report.md
echo "- ✅ CrewAI framework integration" >> comprehensive_report.md
echo "" >> comprehensive_report.md
echo "### Key Features Tested:" >> comprehensive_report.md
echo "- 🤖 Agent creation and configuration" >> comprehensive_report.md
echo "- 📋 Task management and execution" >> comprehensive_report.md
echo "- 🔄 Sync/async workflows" >> comprehensive_report.md
echo "- 🛠️ Custom tools and error handling" >> comprehensive_report.md
echo "- 🧠 Knowledge bases and RAG" >> comprehensive_report.md
echo "- 🔌 MCP server connections" >> comprehensive_report.md
echo "- 💬 LLM integrations (OpenAI, Anthropic, etc.)" >> comprehensive_report.md
- name: Upload Comprehensive Test Results
uses: actions/upload-artifact@v4
if: always()
with:
name: comprehensive-test-results-python-${{ matrix.python-version }}
path: |
comprehensive_report.md
htmlcov/
coverage.xml
.coverage
retention-days: 30
test-matrix-summary:
runs-on: ubuntu-latest
needs: comprehensive-test
if: always()
steps:
- name: Generate Matrix Summary
run: |
echo "# 🎯 Test Matrix Summary" > matrix_summary.md
echo "" >> matrix_summary.md
echo "## Python Version Results:" >> matrix_summary.md
echo "- Python 3.10: ${{ needs.comprehensive-test.result }}" >> matrix_summary.md
echo "- Python 3.11: ${{ needs.comprehensive-test.result }}" >> matrix_summary.md
echo "" >> matrix_summary.md
echo "## Overall Status:" >> matrix_summary.md
if [ "${{ needs.comprehensive-test.result }}" == "success" ]; then
echo "✅ **All tests passed across all Python versions!**" >> matrix_summary.md
else
echo "❌ **Some tests failed. Check individual job logs for details.**" >> matrix_summary.md
fi
- name: Upload Matrix Summary
uses: actions/upload-artifact@v4
with:
name: test-matrix-summary
path: matrix_summary.md
retention-days: 30
+75
View File
@@ -0,0 +1,75 @@
name: Core Tests
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
test-core:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.11]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install UV
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Install dependencies
run: |
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system duckduckgo_search
uv pip install --system pytest pytest-asyncio pytest-cov
- name: Set environment variables
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
- name: Run Unit Tests
run: |
python -m pytest tests/unit/ -v --tb=short --disable-warnings --cov=praisonaiagents --cov-report=term-missing
- name: Run Integration Tests
run: |
python -m pytest tests/integration/ -v --tb=short --disable-warnings
- name: Run AutoGen Framework Tests
run: |
echo "🤖 Testing AutoGen Framework Integration..."
python tests/test_runner.py --pattern autogen --verbose || echo "⚠️ AutoGen tests completed with issues"
continue-on-error: true
- name: Run CrewAI Framework Tests
run: |
echo "⛵ Testing CrewAI Framework Integration..."
python tests/test_runner.py --pattern crewai --verbose || echo "⚠️ CrewAI tests completed with issues"
continue-on-error: true
- name: Run Legacy Tests
run: |
python -m pytest tests/test.py -v --tb=short --disable-warnings
- name: Upload Coverage Reports
if: matrix.python-version == '3.11'
uses: actions/upload-artifact@v4
with:
name: coverage-reports
path: |
.coverage
htmlcov/
retention-days: 7
+156
View File
@@ -0,0 +1,156 @@
name: Extended Tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
schedule:
# Run nightly at 2 AM UTC
- cron: '0 2 * * *'
workflow_dispatch: # Allow manual triggering
jobs:
test-examples:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: 3.11
- name: Install UV
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Install dependencies
run: |
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system duckduckgo_search
- name: Set environment variables
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
- name: Test Key Example Scripts
run: |
echo "🧪 Testing key example scripts from praisonai-agents..."
# Create a timeout function for consistent handling
timeout_run() {
timeout 30s "$@" || echo "⏱️ $1 test completed/timed out"
}
# Test basic agent functionality
timeout_run python src/praisonai-agents/basic-agents.py
# Test async functionality
timeout_run python src/praisonai-agents/async_example.py
# Test knowledge/RAG functionality
timeout_run python src/praisonai-agents/knowledge-agents.py
# Test MCP functionality
timeout_run python src/praisonai-agents/mcp-basic.py
# Test UI functionality
timeout_run python src/praisonai-agents/ui.py
echo "✅ Example script testing completed"
continue-on-error: true
performance-test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: 3.11
- name: Install UV
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Install dependencies
run: |
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system pytest pytest-benchmark
- name: Run Performance Benchmarks
run: |
echo "🏃 Running performance benchmarks..."
python -c "
import time
import sys
import statistics
sys.path.insert(0, 'src/praisonai-agents')
print('🏃 Testing agent creation performance...')
times = []
try:
from praisonaiagents import Agent
for i in range(5):
start_time = time.time()
agent = Agent(name=f'PerfAgent{i}')
times.append(time.time() - start_time)
avg_time = statistics.mean(times)
print(f'✅ Average agent creation time: {avg_time:.3f}s')
print(f'📊 Min: {min(times):.3f}s, Max: {max(times):.3f}s')
except Exception as e:
print(f'❌ Agent creation benchmark failed: {e}')
print('🏃 Testing import performance...')
start_time = time.time()
try:
import praisonaiagents
import_time = time.time() - start_time
print(f'✅ Import completed in {import_time:.3f}s')
except Exception as e:
print(f'❌ Import benchmark failed: {e}')
print('🏃 Testing memory usage...')
try:
import psutil
import os
process = psutil.Process(os.getpid())
memory_mb = process.memory_info().rss / 1024 / 1024
print(f'📊 Memory usage: {memory_mb:.1f} MB')
except ImportError:
print('⚠️ psutil not available for memory testing')
except Exception as e:
print(f'❌ Memory benchmark failed: {e}')
"
continue-on-error: true
- name: Generate Performance Report
run: |
echo "## 📊 Performance Test Results" > performance_report.md
echo "" >> performance_report.md
echo "### Benchmarks Run:" >> performance_report.md
echo "- ⚡ Agent creation speed" >> performance_report.md
echo "- 📦 Import performance" >> performance_report.md
echo "- 💾 Memory usage" >> performance_report.md
echo "- 🧪 Example script execution" >> performance_report.md
echo "" >> performance_report.md
echo "_Performance results are logged in the CI output above._" >> performance_report.md
- name: Upload Performance Report
uses: actions/upload-artifact@v4
with:
name: performance-report
path: performance_report.md
retention-days: 30
+152
View File
@@ -0,0 +1,152 @@
name: Framework Integration Tests
on:
workflow_dispatch: # Allow manual triggering
inputs:
framework:
description: 'Framework to test'
required: true
default: 'all'
type: choice
options:
- all
- autogen
- crewai
schedule:
# Run framework tests daily at 6 AM UTC
- cron: '0 6 * * *'
push:
paths:
- 'tests/integration/autogen/**'
- 'tests/integration/crewai/**'
- '.github/workflows/test-frameworks.yml'
jobs:
framework-tests:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.11]
framework: [autogen, crewai]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install UV
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Install dependencies
run: |
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system duckduckgo_search
uv pip install --system pytest pytest-asyncio pytest-cov
- name: Set environment variables
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
- name: Test ${{ matrix.framework }} Framework
run: |
echo "🧪 Testing ${{ matrix.framework }} framework integration with Python ${{ matrix.python-version }}"
python tests/test_runner.py --pattern ${{ matrix.framework }} --verbose --coverage
continue-on-error: false
- name: Generate Framework Test Report
if: always()
run: |
echo "# 🤖 ${{ matrix.framework }} Framework Test Report" > ${{ matrix.framework }}_report.md
echo "" >> ${{ matrix.framework }}_report.md
echo "**Framework:** ${{ matrix.framework }}" >> ${{ matrix.framework }}_report.md
echo "**Python Version:** ${{ matrix.python-version }}" >> ${{ matrix.framework }}_report.md
echo "**Date:** $(date -u)" >> ${{ matrix.framework }}_report.md
echo "**Trigger:** ${{ github.event_name }}" >> ${{ matrix.framework }}_report.md
echo "" >> ${{ matrix.framework }}_report.md
if [ "${{ matrix.framework }}" == "autogen" ]; then
echo "## AutoGen Integration Tests" >> ${{ matrix.framework }}_report.md
echo "- ✅ AutoGen import verification" >> ${{ matrix.framework }}_report.md
echo "- ✅ Basic agent creation through PraisonAI" >> ${{ matrix.framework }}_report.md
echo "- ✅ Conversation flow testing" >> ${{ matrix.framework }}_report.md
echo "- ✅ Configuration validation" >> ${{ matrix.framework }}_report.md
elif [ "${{ matrix.framework }}" == "crewai" ]; then
echo "## CrewAI Integration Tests" >> ${{ matrix.framework }}_report.md
echo "- ✅ CrewAI import verification" >> ${{ matrix.framework }}_report.md
echo "- ✅ Basic crew creation through PraisonAI" >> ${{ matrix.framework }}_report.md
echo "- ✅ Multi-agent workflow testing" >> ${{ matrix.framework }}_report.md
echo "- ✅ Agent collaboration verification" >> ${{ matrix.framework }}_report.md
echo "- ✅ Configuration validation" >> ${{ matrix.framework }}_report.md
fi
echo "" >> ${{ matrix.framework }}_report.md
echo "## Test Commands" >> ${{ matrix.framework }}_report.md
echo '```bash' >> ${{ matrix.framework }}_report.md
echo "# Run ${{ matrix.framework }} tests locally:" >> ${{ matrix.framework }}_report.md
echo "python tests/test_runner.py --pattern ${{ matrix.framework }} --verbose" >> ${{ matrix.framework }}_report.md
echo '```' >> ${{ matrix.framework }}_report.md
- name: Upload Framework Test Results
uses: actions/upload-artifact@v4
if: always()
with:
name: ${{ matrix.framework }}-test-results-python-${{ matrix.python-version }}
path: |
${{ matrix.framework }}_report.md
htmlcov/
coverage.xml
.coverage
retention-days: 14
framework-summary:
runs-on: ubuntu-latest
needs: framework-tests
if: always()
steps:
- name: Generate Framework Summary
run: |
echo "# 🚀 Framework Integration Test Summary" > framework_summary.md
echo "" >> framework_summary.md
echo "## Test Results by Framework and Python Version:" >> framework_summary.md
echo "" >> framework_summary.md
echo "### AutoGen Framework:" >> framework_summary.md
echo "- Python 3.11: ${{ needs.framework-tests.result }}" >> framework_summary.md
echo "" >> framework_summary.md
echo "### CrewAI Framework:" >> framework_summary.md
echo "- Python 3.11: ${{ needs.framework-tests.result }}" >> framework_summary.md
echo "" >> framework_summary.md
echo "## Overall Status:" >> framework_summary.md
if [ "${{ needs.framework-tests.result }}" == "success" ]; then
echo "✅ **All framework integration tests passed!**" >> framework_summary.md
else
echo "❌ **Some framework tests failed. Check individual job logs for details.**" >> framework_summary.md
fi
echo "" >> framework_summary.md
echo "## Frameworks Tested:" >> framework_summary.md
echo "- **AutoGen**: Microsoft's conversational AI framework" >> framework_summary.md
echo "- **CrewAI**: Multi-agent collaboration framework" >> framework_summary.md
echo "" >> framework_summary.md
echo "## Test Coverage:" >> framework_summary.md
echo "- Import verification" >> framework_summary.md
echo "- Agent/crew creation" >> framework_summary.md
echo "- Workflow execution" >> framework_summary.md
echo "- Configuration validation" >> framework_summary.md
echo "- Integration with PraisonAI" >> framework_summary.md
- name: Upload Framework Summary
uses: actions/upload-artifact@v4
with:
name: framework-test-summary
path: framework_summary.md
retention-days: 30
+164
View File
@@ -0,0 +1,164 @@
name: Real End-to-End Tests
# ⚠️ WARNING: This workflow makes real API calls and incurs costs!
# Only runs when manually triggered to prevent accidental charges
on:
workflow_dispatch: # Manual trigger only
inputs:
framework:
description: 'Framework to test (⚠️ Will incur API costs!)'
required: true
default: 'none'
type: choice
options:
- none
- autogen
- crewai
- all
confirm_costs:
description: 'I understand this will make real API calls and may incur costs'
required: true
type: boolean
default: false
jobs:
real-tests:
runs-on: ubuntu-latest
if: ${{ github.event.inputs.confirm_costs == 'true' && github.event.inputs.framework != 'none' }}
strategy:
matrix:
python-version: [3.11] # Single version to minimize costs
steps:
- name: 🚨 Cost Warning
run: |
echo "⚠️ WARNING: This workflow will make real API calls!"
echo "💰 This may incur charges on your API accounts"
echo "🎯 Framework: ${{ github.event.inputs.framework }}"
echo "✅ Cost confirmation: ${{ github.event.inputs.confirm_costs }}"
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install UV
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Install dependencies
run: |
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system pytest pytest-asyncio pytest-cov
- name: Set environment variables
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY }}" >> $GITHUB_ENV
echo "ANTHROPIC_API_KEY=${{ secrets.ANTHROPIC_API_KEY }}" >> $GITHUB_ENV
echo "GOOGLE_API_KEY=${{ secrets.GOOGLE_API_KEY }}" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
- name: Verify API Keys
run: |
if [ -z "${{ secrets.OPENAI_API_KEY }}" ]; then
echo "❌ OPENAI_API_KEY not set in secrets"
echo "🔧 Add your API key to repository secrets"
exit 1
fi
echo "✅ API keys configured"
- name: Run Real AutoGen Tests
if: ${{ github.event.inputs.framework == 'autogen' || github.event.inputs.framework == 'all' }}
run: |
echo "🤖 Running REAL AutoGen tests (⚠️ API costs may apply)"
python -m pytest tests/e2e/autogen/ -v -m real --tb=short
continue-on-error: false
- name: Run Real CrewAI Tests
if: ${{ github.event.inputs.framework == 'crewai' || github.event.inputs.framework == 'all' }}
run: |
echo "⛵ Running REAL CrewAI tests (⚠️ API costs may apply)"
python -m pytest tests/e2e/crewai/ -v -m real --tb=short
continue-on-error: false
- name: Generate Real Test Report
if: always()
run: |
echo "# 🔥 Real End-to-End Test Report" > real_test_report.md
echo "" >> real_test_report.md
echo "⚠️ **WARNING: This report represents tests that made real API calls**" >> real_test_report.md
echo "" >> real_test_report.md
echo "**Framework Tested:** ${{ github.event.inputs.framework }}" >> real_test_report.md
echo "**Python Version:** ${{ matrix.python-version }}" >> real_test_report.md
echo "**Date:** $(date -u)" >> real_test_report.md
echo "**Triggered by:** ${{ github.actor }}" >> real_test_report.md
echo "" >> real_test_report.md
echo "## 🧪 Test Results" >> real_test_report.md
echo "" >> real_test_report.md
if [ "${{ github.event.inputs.framework }}" == "autogen" ] || [ "${{ github.event.inputs.framework }}" == "all" ]; then
echo "### AutoGen Real Tests:" >> real_test_report.md
echo "- Environment verification" >> real_test_report.md
echo "- Agent creation with real API calls" >> real_test_report.md
echo "- Configuration validation" >> real_test_report.md
echo "" >> real_test_report.md
fi
if [ "${{ github.event.inputs.framework }}" == "crewai" ] || [ "${{ github.event.inputs.framework }}" == "all" ]; then
echo "### CrewAI Real Tests:" >> real_test_report.md
echo "- Environment verification" >> real_test_report.md
echo "- Crew creation with real API calls" >> real_test_report.md
echo "- Multi-agent setup validation" >> real_test_report.md
echo "" >> real_test_report.md
fi
echo "## 💰 Cost Considerations" >> real_test_report.md
echo "- These tests made actual API calls to LLM providers" >> real_test_report.md
echo "- Costs depend on your API pricing tier" >> real_test_report.md
echo "- Tests are designed to be minimal to reduce costs" >> real_test_report.md
echo "- Check your API provider dashboard for actual usage" >> real_test_report.md
echo "## 📋 Next Steps" >> real_test_report.md
echo "- Review test results for any failures" >> real_test_report.md
echo "- Check API usage in your provider dashboard" >> real_test_report.md
echo "- Use mock tests (tests/integration/) for routine testing" >> real_test_report.md
- name: Upload Real Test Results
uses: actions/upload-artifact@v4
if: always()
with:
name: real-test-results-${{ github.event.inputs.framework }}-python-${{ matrix.python-version }}
path: |
real_test_report.md
retention-days: 30
# Safety job that runs when costs not confirmed
safety-check:
runs-on: ubuntu-latest
if: ${{ github.event.inputs.confirm_costs != 'true' || github.event.inputs.framework == 'none' }}
steps:
- name: 🛡️ Safety Check Failed
run: |
echo "🚨 Real tests not executed due to safety checks:"
echo ""
echo "✅ Costs confirmed: ${{ github.event.inputs.confirm_costs }}"
echo "✅ Framework selected: ${{ github.event.inputs.framework }}"
echo ""
echo "To run real tests:"
echo "1. Select a framework (autogen, crewai, or all)"
echo "2. Check 'I understand this will make real API calls and may incur costs'"
echo "3. Ensure API keys are set in repository secrets"
echo ""
echo "💡 For cost-free testing, use mock tests instead:"
echo " - Run 'python -m pytest tests/integration/' locally"
echo " - Or trigger other workflows that use mock tests"
exit 1
+462 -14
View File
@@ -1,36 +1,484 @@
name: Run specific unittest
name: Quick Validation Tests
on: [push, pull_request]
jobs:
test:
quick-test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v2
uses: actions/setup-python@v5
with:
python-version: 3.11
- name: Install Poetry
- name: Install UV
run: |
curl -sSL https://install.python-poetry.org | python3 -
export PATH="$HOME/.local/bin:$PATH"
curl -LsSf https://astral.sh/uv/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Install dependencies
run: |
poetry install
poetry run python -m pip install duckduckgo_search
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system duckduckgo_search
uv pip install --system pytest pytest-asyncio pytest-cov
- name: Set environment variables
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME }}" >> $GITHUB_ENV
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "LOGLEVEL=DEBUG" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
- name: Run specific unittest
- name: Backup Root Config Files
run: |
poetry run python -m unittest tests.test.TestExamples
echo "🔄 Backing up root configuration files to prevent default file resolution interference..."
echo "ℹ️ PraisonAI automatically uses 'agents.yaml' in working directory when no file specified"
echo "ℹ️ This can interfere with test files that specify their own YAML files"
if [ -f "agents.yaml" ]; then
mv agents.yaml agents.yaml.backup
echo "✅ Moved root agents.yaml to agents.yaml.backup"
echo " - This prevents default file fallback during tests"
fi
if [ -f "tools.py" ]; then
mv tools.py tools.py.backup
echo "✅ Moved tools.py to tools.py.backup"
fi
- name: Debug API Key Status
run: |
echo "🔍 Checking API key availability..."
if [ -n "${{ secrets.OPENAI_API_KEY }}" ]; then
echo "✅ GitHub secret OPENAI_API_KEY is available"
echo "🔑 API key starts with: $(echo "$OPENAI_API_KEY" | cut -c1-7)..."
else
echo "⚠️ GitHub secret OPENAI_API_KEY is NOT set - using fallback"
echo "🔑 Using fallback key: sk-test-key..."
fi
echo "🌐 API Base: $OPENAI_API_BASE"
echo "🤖 Model: $OPENAI_MODEL_NAME"
echo "🐛 Log Level: $LOGLEVEL"
echo "📊 Environment Check:"
echo " - OPENAI_API_KEY length: ${#OPENAI_API_KEY}"
echo " - OPENAI_API_BASE: $OPENAI_API_BASE"
echo " - OPENAI_MODEL_NAME: $OPENAI_MODEL_NAME"
echo " - LOGLEVEL: $LOGLEVEL"
- name: Debug Python Environment Variables
run: |
python -c "
import os
print('🐍 Python Environment Variable Check:')
api_key = os.environ.get('OPENAI_API_KEY', 'NOT_SET')
if api_key != 'NOT_SET':
print(f' ✅ OPENAI_API_KEY: {api_key[:7]}... (length: {len(api_key)})')
else:
print(' ❌ OPENAI_API_KEY: NOT_SET')
print(f' 🌐 OPENAI_API_BASE: {os.environ.get(\"OPENAI_API_BASE\", \"NOT_SET\")}')
print(f' 🤖 OPENAI_MODEL_NAME: {os.environ.get(\"OPENAI_MODEL_NAME\", \"NOT_SET\")}')
print(f' 📋 All OPENAI env vars:')
for key, value in os.environ.items():
if key.startswith('OPENAI'):
print(f' {key}: {value[:10] if len(value) > 10 else value}...')
"
- name: Find Researcher Role Source
run: |
echo "🔍 Hunting for the mysterious 'Researcher' role..."
python -c "
import os
import yaml
import glob
print('📋 Searching for Researcher role in all YAML files:')
yaml_files = glob.glob('tests/*.yaml')
for yaml_file in yaml_files:
try:
with open(yaml_file, 'r') as f:
config = yaml.safe_load(f)
# Check if any role contains 'researcher'
roles = config.get('roles', {})
for role_key, role_data in roles.items():
role_name = role_data.get('role', '')
if 'researcher' in role_key.lower() or 'researcher' in role_name.lower():
print(f' 🎯 FOUND in {yaml_file}:')
print(f' Framework: {config.get(\"framework\", \"NOT_SET\")}')
print(f' Role key: {role_key}')
print(f' Role name: {role_name}')
print(f' All roles: {list(roles.keys())}')
print()
except Exception as e:
print(f' ❌ Error reading {yaml_file}: {e}')
print('🔍 Checking for default configurations...')
# Check if there are any default configs or hardcoded roles
try:
import praisonai
print(f' PraisonAI package location: {praisonai.__file__}')
# Check if there are any example YAML files in the package
package_dir = os.path.dirname(praisonai.__file__)
for root, dirs, files in os.walk(package_dir):
for file in files:
if file.endswith(('.yaml', '.yml')):
file_path = os.path.join(root, file)
print(f' 📁 Found YAML in package: {file_path}')
except Exception as e:
print(f' ❌ Error checking package: {e}')
"
continue-on-error: true
- name: Trace AutoGen Execution Path
run: |
echo "🔍 Tracing AutoGen execution to find where it diverges..."
python -c "
import os
import sys
sys.path.insert(0, '.')
try:
from praisonai import PraisonAI
from praisonai.agents_generator import AgentsGenerator
# Test the exact execution path
print('🎯 Testing AutoGen execution path:')
praisonai = PraisonAI(agent_file='tests/autogen-agents.yaml')
print(f' 1. PraisonAI framework: \"{praisonai.framework}\"')
agents_gen = AgentsGenerator(
agent_file='tests/autogen-agents.yaml',
framework=praisonai.framework,
config_list=praisonai.config_list
)
print(f' 2. AgentsGenerator framework: \"{agents_gen.framework}\"')
# Load the YAML to check what it contains
import yaml
with open('tests/autogen-agents.yaml', 'r') as f:
config = yaml.safe_load(f)
framework = agents_gen.framework or config.get('framework')
print(f' 3. Final framework decision: \"{framework}\"')
print(f' 4. Available frameworks:')
# Check framework availability
try:
import autogen
print(f' ✅ AutoGen available')
except ImportError:
print(f' ❌ AutoGen NOT available')
try:
from praisonaiagents import Agent
print(f' ✅ PraisonAI agents available')
except ImportError:
print(f' ❌ PraisonAI agents NOT available')
try:
from crewai import Agent
print(f' ✅ CrewAI available')
except ImportError:
print(f' ❌ CrewAI NOT available')
print(f' 5. Roles in YAML: {list(config.get(\"roles\", {}).keys())}')
# Now test the actual framework execution
if framework == 'autogen':
print(f' 6. ✅ Should execute _run_autogen')
elif framework == 'praisonai':
print(f' 6. ❌ Would execute _run_praisonai (WRONG!)')
else:
print(f' 6. ❌ Would execute _run_crewai (DEFAULT FALLBACK)')
except Exception as e:
print(f'❌ Error tracing execution: {e}')
import traceback
traceback.print_exc()
"
continue-on-error: true
- name: Debug YAML Loading and Roles
run: |
echo "🔍 Tracing YAML file loading and role creation..."
python -c "
import os
import sys
import yaml
sys.path.insert(0, '.')
print('📁 Available YAML files in tests/:')
import glob
yaml_files = glob.glob('tests/*.yaml')
for f in yaml_files:
print(f' {f}')
print()
print('📋 Content of autogen-agents.yaml:')
with open('tests/autogen-agents.yaml', 'r') as f:
config = yaml.safe_load(f)
print(f' Framework: {config.get(\"framework\")}')
print(f' Topic: {config.get(\"topic\")}')
print(f' Roles: {list(config.get(\"roles\", {}).keys())}')
for role_key, role_data in config.get('roles', {}).items():
print(f' {role_key} -> {role_data.get(\"role\", \"NO_ROLE\")}')
print()
print('🔍 Checking if execution uses a different YAML:')
# Check other YAML files for 'Researcher' role
for yaml_file in yaml_files:
try:
with open(yaml_file, 'r') as f:
test_config = yaml.safe_load(f)
roles = test_config.get('roles', {})
for role_key, role_data in roles.items():
if 'researcher' in role_key.lower() or 'researcher' in role_data.get('role', '').lower():
print(f' 🎯 FOUND Researcher in {yaml_file}!')
print(f' Framework: {test_config.get(\"framework\")}')
print(f' Role key: {role_key} -> {role_data.get(\"role\")}')
except:
pass
"
continue-on-error: true
- name: Debug Framework Detection
run: |
echo "🔍 Testing framework detection and config flow..."
python -c "
import os
import sys
import yaml
sys.path.insert(0, '.')
print('🔧 Testing framework detection:')
# Load the YAML file
with open('tests/autogen-agents.yaml', 'r') as f:
config = yaml.safe_load(f)
print(f' 📋 YAML framework: {config.get(\"framework\", \"NOT_SET\")}')
print(f' 📋 YAML topic: {config.get(\"topic\", \"NOT_SET\")}')
try:
from praisonai import PraisonAI
from praisonai.agents_generator import AgentsGenerator
# Test PraisonAI initialization
praisonai = PraisonAI(agent_file='tests/autogen-agents.yaml')
print(f' 🎯 PraisonAI framework: {praisonai.framework}')
# Test AgentsGenerator initialization
agents_gen = AgentsGenerator(
agent_file='tests/autogen-agents.yaml',
framework=praisonai.framework,
config_list=praisonai.config_list
)
print(f' ⚙️ AgentsGenerator framework: {agents_gen.framework}')
print(f' ⚙️ Final framework decision: {agents_gen.framework or config.get(\"framework\")}')
# Check config_list
print(f' 🔑 Config list model: {praisonai.config_list[0].get(\"model\")}')
print(f' 🔑 Config list API key: {praisonai.config_list[0].get(\"api_key\", \"NOT_SET\")[:10]}...')
except Exception as e:
print(f'❌ Error in framework detection: {e}')
"
continue-on-error: true
- name: Debug PraisonAIModel API Key Flow
run: |
echo "🔍 Testing PraisonAIModel API key handling..."
python -c "
import os
import sys
sys.path.insert(0, '.')
print('🔑 Environment API Key Check:')
env_key = os.environ.get('OPENAI_API_KEY', 'NOT_FOUND')
print(f' OPENAI_API_KEY: {env_key[:10] if env_key != \"NOT_FOUND\" else \"NOT_FOUND\"}...')
try:
from praisonai.inc.models import PraisonAIModel
# Test PraisonAIModel with openai/gpt-4o-mini (from YAML)
model = PraisonAIModel(model='openai/gpt-4o-mini')
print('🤖 PraisonAIModel Configuration:')
print(f' model: {model.model}')
print(f' model_name: {model.model_name}')
print(f' api_key_var: {model.api_key_var}')
print(f' api_key: {model.api_key[:10] if model.api_key != \"nokey\" else \"DEFAULT_NOKEY\"}...')
print(f' base_url: {model.base_url}')
if model.api_key == 'nokey':
print('❌ FOUND THE ISSUE: PraisonAIModel is using default \"nokey\" instead of environment variable!')
else:
print('✅ PraisonAIModel has valid API key from environment')
except Exception as e:
print(f'❌ Error testing PraisonAIModel: {e}')
"
continue-on-error: true
- name: Validate API Key
run: |
echo "🔑 Testing API key validity with minimal OpenAI call..."
python -c "
import os
try:
from openai import OpenAI
client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
# Make a minimal API call to test key validity
response = client.models.list()
print('✅ API Key is VALID - OpenAI responded successfully')
print(f'📊 Available models: {len(list(response.data))} models found')
except Exception as e:
print(f'❌ API Key is INVALID - Error: {e}')
print('🔍 This explains why all API-dependent tests are failing')
print('💡 The GitHub secret OPENAI_API_KEY needs to be updated with a valid key')
"
continue-on-error: true
- name: Test Direct PraisonAI Execution
run: |
echo "🧪 Testing direct PraisonAI execution (what works locally)..."
python -m praisonai tests/autogen-agents.yaml
continue-on-error: true
- name: Comprehensive Execution Debug
run: |
echo "🔍 Comprehensive debugging of PraisonAI execution path..."
python -c "
import os
import sys
import yaml
sys.path.insert(0, '.')
print('=' * 60)
print('🔍 COMPREHENSIVE EXECUTION DEBUG')
print('=' * 60)
# Check current working directory
print(f'📁 Current working directory: {os.getcwd()}')
# List files in current directory
print('📋 Files in current directory:')
for f in os.listdir('.'):
print(f' {f}')
print()
print('📋 Files in tests/ directory:')
for f in os.listdir('tests'):
if f.endswith('.yaml'):
print(f' tests/{f}')
# Check if root agents.yaml exists
print()
if os.path.exists('agents.yaml'):
print('❌ ROOT agents.yaml EXISTS (this is the problem!)')
with open('agents.yaml', 'r') as f:
root_config = yaml.safe_load(f)
print(f' Root framework: {root_config.get(\"framework\")}')
print(f' Root roles: {list(root_config.get(\"roles\", {}).keys())}')
else:
print('✅ ROOT agents.yaml does NOT exist (good!)')
# Test the actual execution path
print()
print('🎯 Testing EXACT execution path:')
try:
from praisonai import PraisonAI
from praisonai.agents_generator import AgentsGenerator
# Test with full path
test_file = 'tests/autogen-agents.yaml'
print(f' Using test file: {test_file}')
print(f' File exists: {os.path.exists(test_file)}')
# Load the test file directly
with open(test_file, 'r') as f:
test_config = yaml.safe_load(f)
print(f' Test file framework: {test_config.get(\"framework\")}')
print(f' Test file roles: {list(test_config.get(\"roles\", {}).keys())}')
# Create PraisonAI instance
praisonai = PraisonAI(agent_file=test_file)
print(f' PraisonAI.agent_file: {praisonai.agent_file}')
print(f' PraisonAI.framework: {praisonai.framework}')
# Create AgentsGenerator
agents_gen = AgentsGenerator(
agent_file=test_file,
framework=praisonai.framework,
config_list=praisonai.config_list
)
print(f' AgentsGenerator.agent_file: {agents_gen.agent_file}')
print(f' AgentsGenerator.framework: {agents_gen.framework}')
# Test what would happen in generate_crew_and_kickoff
print()
print('🔧 Testing generate_crew_and_kickoff logic:')
# Simulate the loading logic
if agents_gen.agent_yaml:
loaded_config = yaml.safe_load(agents_gen.agent_yaml)
print(' Would load from agent_yaml')
else:
if agents_gen.agent_file == '/app/api:app' or agents_gen.agent_file == 'api:app':
agents_gen.agent_file = 'agents.yaml'
print(f' Would change agent_file to: {agents_gen.agent_file}')
try:
with open(agents_gen.agent_file, 'r') as f:
loaded_config = yaml.safe_load(f)
print(f' Successfully loaded: {agents_gen.agent_file}')
except FileNotFoundError:
print(f' FileNotFoundError: {agents_gen.agent_file}')
loaded_config = None
if loaded_config:
final_framework = agents_gen.framework or loaded_config.get('framework')
print(f' Final framework decision: {final_framework}')
print(f' Loaded roles: {list(loaded_config.get(\"roles\", {}).keys())}')
if 'researcher' in loaded_config.get('roles', {}):
print(' ❌ FOUND Researcher role in loaded config!')
else:
print(' ✅ No Researcher role in loaded config')
except Exception as e:
print(f'❌ Error during execution debug: {e}')
import traceback
traceback.print_exc()
"
continue-on-error: true
- name: Run Fast Tests
run: |
# Run the fastest, most essential tests
python tests/test_runner.py --pattern fast
- name: Run Legacy Example Tests
run: |
python -m pytest tests/test.py -v --tb=short --disable-warnings
continue-on-error: true
- name: Restore Root Config Files
run: |
echo "🔄 Restoring root configuration files..."
if [ -f "agents.yaml.backup" ]; then
mv agents.yaml.backup agents.yaml
echo "✅ Restored agents.yaml"
fi
if [ -f "tools.py.backup" ]; then
mv tools.py.backup tools.py
echo "✅ Restored tools.py"
fi
if: always() # Always run this step, even if previous steps failed
+6 -1
View File
@@ -1,3 +1,4 @@
workspace.code-workspace
.vscode
crewai
.cache
@@ -51,6 +52,8 @@ agentops.log
# crewAI
crewAI
!tests/integration/crewai
!tests/e2e/crewai
# virtualenv
.venv
@@ -66,4 +69,6 @@ agents/praisonaiagents/build
agents/praisonaiagents/dist
agents/praisonaiagents/praisonaiagents.egg-info
.codegpt
.praison
.praison
# Local Netlify folder
.netlify
+31 -8
View File
@@ -20,7 +20,7 @@
</div>
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.
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, AG2 (Formerly AutoGen), and CrewAI into a low-code solution, it streamlines the building and management of multi-agent LLM systems, emphasising simplicity, customisation, and effective human-agent collaboration.
<div align="center">
<a href="https://docs.praison.ai">
@@ -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
@@ -531,7 +548,7 @@ uv pip install -r pyproject.toml --extra "crewai,autogen"
## Other Features
- 🔄 Use CrewAI or AutoGen Framework
- 🔄 Use CrewAI or AG2 (Formerly AutoGen) Framework
- 💻 Chat with ENTIRE Codebase
- 🎨 Interactive UIs
- 📄 YAML-based Configuration
@@ -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.
-10
View File
@@ -1,10 +0,0 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a helpful assistant",
llm="gemini/gemini-1.5-flash-8b",
self_reflect=True,
verbose=True
)
agent.start("Why sky is Blue?")
-4
View File
@@ -1,4 +0,0 @@
"""Agent module for AI agents"""
from .agent import Agent
__all__ = ['Agent']
File diff suppressed because it is too large. Load diff
-823
View File
@@ -1,823 +0,0 @@
import logging
import os
import warnings
from typing import Any, Dict, List, Optional, Union, Literal, Callable
from pydantic import BaseModel
import time
import json
from ..main import (
display_error,
display_tool_call,
display_instruction,
display_interaction,
display_generating,
display_self_reflection,
ReflectionOutput,
)
from rich.console import Console
from rich.live import Live
class LLMContextLengthExceededException(Exception):
"""Raised when LLM context length is exceeded"""
def __init__(self, message: str):
self.message = message
super().__init__(self.message)
def _is_context_limit_error(self, error_message: str) -> bool:
"""Check if error is related to context length"""
context_limit_phrases = [
"maximum context length",
"context window is too long",
"context length exceeded",
"context_length_exceeded"
]
return any(phrase in error_message.lower() for phrase in context_limit_phrases)
class LLM:
"""
Easy to use wrapper for language models. Supports multiple providers like OpenAI,
Anthropic, and others through LiteLLM.
"""
# Default window sizes for different models (75% of actual to be safe)
MODEL_WINDOWS = {
# OpenAI
"gpt-4": 6144, # 8,192 actual
"gpt-4o": 96000, # 128,000 actual
"gpt-4o-mini": 96000, # 128,000 actual
"gpt-4-turbo": 96000, # 128,000 actual
"o1-preview": 96000, # 128,000 actual
"o1-mini": 96000, # 128,000 actual
# Anthropic
"claude-3-5-sonnet": 12288, # 16,384 actual
"claude-3-sonnet": 12288, # 16,384 actual
"claude-3-opus": 96000, # 128,000 actual
"claude-3-haiku": 96000, # 128,000 actual
# Gemini
"gemini-2.0-flash": 786432, # 1,048,576 actual
"gemini-1.5-pro": 1572864, # 2,097,152 actual
"gemini-1.5-flash": 786432, # 1,048,576 actual
"gemini-1.5-flash-8b": 786432, # 1,048,576 actual
# Deepseek
"deepseek-chat": 96000, # 128,000 actual
# Groq
"gemma2-9b-it": 6144, # 8,192 actual
"gemma-7b-it": 6144, # 8,192 actual
"llama3-70b-8192": 6144, # 8,192 actual
"llama3-8b-8192": 6144, # 8,192 actual
"mixtral-8x7b-32768": 24576, # 32,768 actual
"llama-3.3-70b-versatile": 96000, # 128,000 actual
"llama-3.3-70b-instruct": 96000, # 128,000 actual
# Other llama models
"llama-3.1-70b-versatile": 98304, # 131,072 actual
"llama-3.1-8b-instant": 98304, # 131,072 actual
"llama-3.2-1b-preview": 6144, # 8,192 actual
"llama-3.2-3b-preview": 6144, # 8,192 actual
"llama-3.2-11b-text-preview": 6144, # 8,192 actual
"llama-3.2-90b-text-preview": 6144 # 8,192 actual
}
def __init__(
self,
model: str,
timeout: Optional[int] = None,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
n: Optional[int] = None,
max_tokens: Optional[int] = None,
presence_penalty: Optional[float] = None,
frequency_penalty: Optional[float] = None,
logit_bias: Optional[Dict[int, float]] = None,
response_format: Optional[Dict[str, Any]] = None,
seed: Optional[int] = None,
logprobs: Optional[bool] = None,
top_logprobs: Optional[int] = None,
api_version: Optional[str] = None,
stop_phrases: Optional[Union[str, List[str]]] = None,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
events: List[Any] = [],
**extra_settings
):
try:
import litellm
# Set litellm options globally
litellm.set_verbose = False
litellm.success_callback = []
litellm._async_success_callback = []
litellm.callbacks = []
# Additional logging suppression
litellm.suppress_debug_messages = True
logging.getLogger("litellm.utils").setLevel(logging.WARNING)
logging.getLogger("litellm.main").setLevel(logging.WARNING)
except ImportError:
raise ImportError(
"LiteLLM is required but not installed. "
"Please install with: pip install 'praisonaiagents[llm]'"
)
self.model = model
self.timeout = timeout
self.temperature = temperature
self.top_p = top_p
self.n = n
self.max_tokens = max_tokens
self.presence_penalty = presence_penalty
self.frequency_penalty = frequency_penalty
self.logit_bias = logit_bias
self.response_format = response_format
self.seed = seed
self.logprobs = logprobs
self.top_logprobs = top_logprobs
self.api_version = api_version
self.stop_phrases = stop_phrases
self.api_key = api_key
self.base_url = base_url
self.events = events
self.extra_settings = extra_settings
self.console = Console()
self.chat_history = []
self.verbose = extra_settings.get('verbose', True)
self.markdown = extra_settings.get('markdown', True)
self.self_reflect = extra_settings.get('self_reflect', False)
self.max_reflect = extra_settings.get('max_reflect', 3)
self.min_reflect = extra_settings.get('min_reflect', 1)
# Enable error dropping for cleaner output
litellm.drop_params = True
self._setup_event_tracking(events)
def get_response(
self,
prompt: Union[str, List[Dict]],
system_prompt: Optional[str] = None,
chat_history: Optional[List[Dict]] = None,
temperature: float = 0.2,
tools: Optional[List[Any]] = None,
output_json: Optional[BaseModel] = None,
output_pydantic: Optional[BaseModel] = None,
verbose: bool = True,
markdown: bool = True,
self_reflect: bool = False,
max_reflect: int = 3,
min_reflect: int = 1,
console: Optional[Console] = None,
agent_name: Optional[str] = None,
agent_role: Optional[str] = None,
agent_tools: Optional[List[str]] = None,
execute_tool_fn: Optional[Callable] = None,
**kwargs
) -> str:
"""Enhanced get_response with all OpenAI-like features"""
try:
import litellm
# Disable litellm debug messages
litellm.set_verbose = False
# Build messages list
messages = []
if system_prompt:
if output_json:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_json.model_json_schema())}"
elif output_pydantic:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_pydantic.model_json_schema())}"
messages.append({"role": "system", "content": system_prompt})
if chat_history:
messages.extend(chat_history)
# Handle prompt modifications for JSON output
original_prompt = prompt
if output_json or output_pydantic:
if isinstance(prompt, str):
prompt += "\nReturn ONLY a valid JSON object. No other text or explanation."
elif isinstance(prompt, list):
for item in prompt:
if item["type"] == "text":
item["text"] += "\nReturn ONLY a valid JSON object. No other text or explanation."
break
# Add prompt to messages
if isinstance(prompt, list):
messages.append({"role": "user", "content": prompt})
else:
messages.append({"role": "user", "content": prompt})
start_time = time.time()
reflection_count = 0
while True:
try:
if verbose:
display_text = prompt
if isinstance(prompt, list):
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
if display_text and str(display_text).strip():
display_instruction(
f"Agent {agent_name} is processing prompt: {display_text}",
console=console,
agent_name=agent_name,
agent_role=agent_role,
agent_tools=agent_tools
)
# Get response from LiteLLM
start_time = time.time()
if verbose:
with Live(display_generating("", start_time), console=console, refresh_per_second=4) as live:
response_text = ""
for chunk in litellm.completion(
model=self.model,
messages=messages,
temperature=temperature,
stream=True,
**kwargs
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
response_text += content
live.update(display_generating(response_text, start_time))
else:
# Non-verbose mode, just collect the response
response_text = ""
for chunk in litellm.completion(
model=self.model,
messages=messages,
temperature=temperature,
stream=True,
**kwargs
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
response_text += chunk.choices[0].delta.content
response_text = response_text.strip()
# Get final completion to check for tool calls
final_response = litellm.completion(
model=self.model,
messages=messages,
temperature=temperature,
stream=False, # No streaming for tool call check
**kwargs
)
tool_calls = final_response["choices"][0]["message"].get("tool_calls")
# Handle tool calls
if tool_calls and execute_tool_fn:
messages.append({
"role": "assistant",
"content": response_text,
"tool_calls": tool_calls
})
for tool_call in tool_calls:
function_name = tool_call["function"]["name"]
arguments = json.loads(tool_call["function"]["arguments"])
if verbose:
display_tool_call(f"Agent {agent_name} is calling function '{function_name}' with arguments: {arguments}", console=console)
tool_result = execute_tool_fn(function_name, arguments)
if tool_result:
if verbose:
display_tool_call(f"Function '{function_name}' returned: {tool_result}", console=console)
messages.append({
"role": "tool",
"tool_call_id": tool_call["id"],
"content": json.dumps(tool_result)
})
else:
messages.append({
"role": "tool",
"tool_call_id": tool_call["id"],
"content": "Function returned an empty output"
})
# Get response after tool calls with streaming
if verbose:
with Live(display_generating("", start_time), console=console, refresh_per_second=4) as live:
response_text = ""
for chunk in litellm.completion(
model=self.model,
messages=messages,
temperature=temperature,
stream=True
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
response_text += content
live.update(display_generating(response_text, start_time))
else:
response_text = ""
for chunk in litellm.completion(
model=self.model,
messages=messages,
temperature=temperature,
stream=True
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
response_text += chunk.choices[0].delta.content
response_text = response_text.strip()
# Handle output formatting
if output_json or output_pydantic:
self.chat_history.append({"role": "user", "content": original_prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
if verbose:
display_interaction(original_prompt, response_text, markdown=markdown,
generation_time=time.time() - start_time, console=console)
return response_text
if not self_reflect:
if verbose:
display_interaction(original_prompt, response_text, markdown=markdown,
generation_time=time.time() - start_time, console=console)
return response_text
# Handle self-reflection
reflection_prompt = f"""
Reflect on your previous response: '{response_text}'.
Identify any flaws, improvements, or actions.
Provide a "satisfactory" status ('yes' or 'no').
Output MUST be JSON with 'reflection' and 'satisfactory'.
"""
reflection_messages = messages + [
{"role": "assistant", "content": response_text},
{"role": "user", "content": reflection_prompt}
]
# Get reflection response with streaming
if verbose:
with Live(display_generating("", start_time), console=console, refresh_per_second=4) as live:
reflection_text = ""
for chunk in litellm.completion(
model=self.model,
messages=reflection_messages,
temperature=temperature,
stream=True,
response_format={"type": "json_object"}
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
reflection_text += content
live.update(display_generating(reflection_text, start_time))
else:
reflection_text = ""
for chunk in litellm.completion(
model=self.model,
messages=reflection_messages,
temperature=temperature,
stream=True,
response_format={"type": "json_object"}
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
reflection_text += chunk.choices[0].delta.content
try:
reflection_data = json.loads(reflection_text)
satisfactory = reflection_data.get("satisfactory", "no").lower() == "yes"
if verbose:
display_self_reflection(
f"Agent {agent_name} self reflection: reflection='{reflection_data['reflection']}' satisfactory='{reflection_data['satisfactory']}'",
console=console
)
if satisfactory and reflection_count >= min_reflect - 1:
if verbose:
display_interaction(prompt, response_text, markdown=markdown,
generation_time=time.time() - start_time, console=console)
return response_text
if reflection_count >= max_reflect - 1:
if verbose:
display_interaction(prompt, response_text, markdown=markdown,
generation_time=time.time() - start_time, console=console)
return response_text
reflection_count += 1
messages.extend([
{"role": "assistant", "content": response_text},
{"role": "user", "content": reflection_prompt},
{"role": "assistant", "content": reflection_text},
{"role": "user", "content": "Now regenerate your response using the reflection you made"}
])
continue
except json.JSONDecodeError:
reflection_count += 1
if reflection_count >= max_reflect:
return response_text
continue
except Exception as e:
display_error(f"Error in LLM response: {str(e)}")
return None
except Exception as error:
display_error(f"Error in get_response: {str(error)}")
raise
async def get_response_async(
self,
prompt: Union[str, List[Dict]],
system_prompt: Optional[str] = None,
chat_history: Optional[List[Dict]] = None,
temperature: float = 0.2,
tools: Optional[List[Any]] = None,
output_json: Optional[BaseModel] = None,
output_pydantic: Optional[BaseModel] = None,
verbose: bool = True,
markdown: bool = True,
self_reflect: bool = False,
max_reflect: int = 3,
min_reflect: int = 1,
console: Optional[Console] = None,
agent_name: Optional[str] = None,
agent_role: Optional[str] = None,
agent_tools: Optional[List[str]] = None,
execute_tool_fn: Optional[Callable] = None,
**kwargs
) -> str:
"""Async version of get_response with identical functionality."""
try:
import litellm
litellm.set_verbose = False
# Build messages list
messages = []
if system_prompt:
if output_json:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_json.model_json_schema())}"
elif output_pydantic:
system_prompt += f"\nReturn ONLY a JSON object that matches this Pydantic model: {json.dumps(output_pydantic.model_json_schema())}"
messages.append({"role": "system", "content": system_prompt})
if chat_history:
messages.extend(chat_history)
# Handle prompt modifications for JSON output
original_prompt = prompt
if output_json or output_pydantic:
if isinstance(prompt, str):
prompt += "\nReturn ONLY a valid JSON object. No other text or explanation."
elif isinstance(prompt, list):
for item in prompt:
if item["type"] == "text":
item["text"] += "\nReturn ONLY a valid JSON object. No other text or explanation."
break
# Add prompt to messages
if isinstance(prompt, list):
messages.append({"role": "user", "content": prompt})
else:
messages.append({"role": "user", "content": prompt})
start_time = time.time()
reflection_count = 0
# Format tools for LiteLLM
formatted_tools = None
if tools:
logging.info(f"Starting tool formatting for {len(tools)} tools")
formatted_tools = []
for tool in tools:
logging.info(f"Processing tool: {tool.__name__ if hasattr(tool, '__name__') else str(tool)}")
if hasattr(tool, '__name__'):
tool_name = tool.__name__
tool_doc = tool.__doc__ or "No description available"
# Get function signature
import inspect
sig = inspect.signature(tool)
logging.debug(f"Tool signature: {sig}")
params = {}
required = []
for name, param in sig.parameters.items():
logging.debug(f"Processing parameter: {name} with annotation: {param.annotation}")
param_type = "string"
if param.annotation != inspect.Parameter.empty:
if param.annotation == int:
param_type = "integer"
elif param.annotation == float:
param_type = "number"
elif param.annotation == bool:
param_type = "boolean"
elif param.annotation == Dict:
param_type = "object"
elif param.annotation == List:
param_type = "array"
elif hasattr(param.annotation, "__name__"):
param_type = param.annotation.__name__.lower()
params[name] = {"type": param_type}
if param.default == inspect.Parameter.empty:
required.append(name)
logging.debug(f"Generated parameters: {params}")
logging.debug(f"Required parameters: {required}")
tool_def = {
"type": "function",
"function": {
"name": tool_name,
"description": tool_doc,
"parameters": {
"type": "object",
"properties": params,
"required": required
}
}
}
# Ensure tool definition is JSON serializable
print(f"Generated tool definition: {tool_def}")
try:
json.dumps(tool_def) # Test serialization
logging.info(f"Generated tool definition: {tool_def}")
formatted_tools.append(tool_def)
except TypeError as e:
logging.error(f"Tool definition not JSON serializable: {e}")
continue
# Validate final tools list
if formatted_tools:
try:
json.dumps(formatted_tools) # Final serialization check
logging.info(f"Final formatted tools: {json.dumps(formatted_tools, indent=2)}")
except TypeError as e:
logging.error(f"Final tools list not JSON serializable: {e}")
formatted_tools = None
response_text = ""
if verbose:
# ----------------------------------------------------
# 1) Make the streaming call WITHOUT tools
# ----------------------------------------------------
async for chunk in await litellm.acompletion(
model=self.model,
messages=messages,
temperature=temperature,
stream=True,
**kwargs
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
response_text += chunk.choices[0].delta.content
print("\033[K", end="\r")
print(f"Generating... {time.time() - start_time:.1f}s", end="\r")
else:
# Non-verbose streaming call, still no tools
async for chunk in await litellm.acompletion(
model=self.model,
messages=messages,
temperature=temperature,
stream=True,
**kwargs
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
response_text += chunk.choices[0].delta.content
response_text = response_text.strip()
# ----------------------------------------------------
# 2) If tool calls are needed, do a non-streaming call
# ----------------------------------------------------
if tools and execute_tool_fn:
# Next call with tools if needed
tool_response = await litellm.acompletion(
model=self.model,
messages=messages,
temperature=temperature,
stream=False,
tools=formatted_tools, # We safely pass tools here
**kwargs
)
# handle tool_calls from tool_response as usual...
tool_calls = tool_response.choices[0].message.get("tool_calls")
if tool_calls:
messages.append({
"role": "assistant",
"content": response_text,
"tool_calls": tool_calls
})
for tool_call in tool_calls:
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
if verbose:
display_tool_call(f"Agent {agent_name} is calling function '{function_name}' with arguments: {arguments}", console=console)
tool_result = await execute_tool_fn(function_name, arguments)
if tool_result:
if verbose:
display_tool_call(f"Function '{function_name}' returned: {tool_result}", console=console)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(tool_result)
})
else:
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": "Function returned an empty output"
})
# Get response after tool calls with streaming
response_text = ""
if verbose:
async for chunk in await litellm.acompletion(
model=self.model,
messages=messages,
temperature=temperature,
stream=True,
tools=formatted_tools,
**kwargs
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
response_text += content
print("\033[K", end="\r")
print(f"Reflecting... {time.time() - start_time:.1f}s", end="\r")
else:
response_text = ""
for chunk in litellm.completion(
model=self.model,
messages=messages,
temperature=temperature,
stream=True,
**kwargs
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
response_text += chunk.choices[0].delta.content
response_text = response_text.strip()
# Handle output formatting
if output_json or output_pydantic:
self.chat_history.append({"role": "user", "content": original_prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
if verbose:
display_interaction(original_prompt, response_text, markdown=markdown,
generation_time=time.time() - start_time, console=console)
return response_text
if not self_reflect:
if verbose:
display_interaction(original_prompt, response_text, markdown=markdown,
generation_time=time.time() - start_time, console=console)
return response_text
# Handle self-reflection
reflection_prompt = f"""
Reflect on your previous response: '{response_text}'.
Identify any flaws, improvements, or actions.
Provide a "satisfactory" status ('yes' or 'no').
Output MUST be JSON with 'reflection' and 'satisfactory'.
"""
reflection_messages = messages + [
{"role": "assistant", "content": response_text},
{"role": "user", "content": reflection_prompt}
]
# Get reflection response
reflection_text = ""
if verbose:
async for chunk in await litellm.acompletion(
model=self.model,
messages=reflection_messages,
temperature=temperature,
stream=True,
response_format={"type": "json_object"},
**kwargs
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
reflection_text += content
print("\033[K", end="\r")
print(f"Reflecting... {time.time() - start_time:.1f}s", end="\r")
else:
async for chunk in await litellm.acompletion(
model=self.model,
messages=reflection_messages,
temperature=temperature,
stream=True,
response_format={"type": "json_object"},
**kwargs
):
if chunk and chunk.choices and chunk.choices[0].delta.content:
reflection_text += chunk.choices[0].delta.content
while True: # Add loop for reflection handling
try:
reflection_data = json.loads(reflection_text)
satisfactory = reflection_data.get("satisfactory", "no").lower() == "yes"
if verbose:
display_self_reflection(
f"Agent {agent_name} self reflection: reflection='{reflection_data['reflection']}' satisfactory='{reflection_data['satisfactory']}'",
console=console
)
if satisfactory and reflection_count >= min_reflect - 1:
if verbose:
display_interaction(prompt, response_text, markdown=markdown,
generation_time=time.time() - start_time, console=console)
return response_text
if reflection_count >= max_reflect - 1:
if verbose:
display_interaction(prompt, response_text, markdown=markdown,
generation_time=time.time() - start_time, console=console)
return response_text
reflection_count += 1
messages.extend([
{"role": "assistant", "content": response_text},
{"role": "user", "content": reflection_prompt},
{"role": "assistant", "content": reflection_text},
{"role": "user", "content": "Now regenerate your response using the reflection you made"}
])
continue # Now properly in a loop
except json.JSONDecodeError:
reflection_count += 1
if reflection_count >= max_reflect:
return response_text
continue # Now properly in a loop
except Exception as error:
if LLMContextLengthExceededException(str(error))._is_context_limit_error(str(error)):
raise LLMContextLengthExceededException(str(error))
display_error(f"Error in get_response_async: {str(error)}")
raise
def can_use_tools(self) -> bool:
"""Check if this model can use tool functions"""
try:
import litellm
allowed_params = litellm.get_supported_openai_params(model=self.model)
return "response_format" in allowed_params
except ImportError:
raise ImportError(
"LiteLLM is required but not installed. "
"Please install it with: pip install 'praisonaiagents[llm]'"
)
except:
return False
def can_use_stop_words(self) -> bool:
"""Check if this model supports stop words"""
try:
import litellm
allowed_params = litellm.get_supported_openai_params(model=self.model)
return "stop" in allowed_params
except ImportError:
raise ImportError(
"LiteLLM is required but not installed. "
"Please install it with: pip install 'praisonaiagents[llm]'"
)
except:
return False
def get_context_size(self) -> int:
"""Get safe input size limit for this model"""
for model_prefix, size in self.MODEL_WINDOWS.items():
if self.model.startswith(model_prefix):
return size
return 4000 # Safe default
def _setup_event_tracking(self, events: List[Any]) -> None:
"""Setup callback functions for tracking model usage"""
try:
import litellm
except ImportError:
raise ImportError(
"LiteLLM is required but not installed. "
"Please install it with: pip install 'praisonaiagents[llm]'"
)
event_types = [type(event) for event in events]
# Remove old events of same type
for event in litellm.success_callback[:]:
if type(event) in event_types:
litellm.success_callback.remove(event)
for event in litellm._async_success_callback[:]:
if type(event) in event_types:
litellm._async_success_callback.remove(event)
litellm.callbacks = events
-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.2.16 gunicorn markdown
EXPOSE 8080
CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]
+1 -1
View File
@@ -13,7 +13,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
RUN pip install --no-cache-dir \
praisonaiagents>=0.0.4 \
praisonai_tools \
"praisonai==2.0.18" \
"praisonai==2.2.16" \
"praisonai[chat]" \
"embedchain[github,youtube]"
+1 -1
View File
@@ -15,7 +15,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
RUN pip install --no-cache-dir \
praisonaiagents>=0.0.4 \
praisonai_tools \
"praisonai==2.0.18" \
"praisonai==2.2.16" \
"praisonai[ui]" \
"praisonai[chat]" \
"praisonai[realtime]" \
+1 -1
View File
@@ -13,7 +13,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
RUN pip install --no-cache-dir \
praisonaiagents>=0.0.4 \
praisonai_tools \
"praisonai==2.0.18" \
"praisonai==2.2.16" \
"praisonai[ui]" \
"praisonai[crewai]"
+1 -1
View File
@@ -30,7 +30,7 @@ Features:
- Built-in tools
- Structured workflows
### AutoGen Integration
### AG2 (Formerly AutoGen) Integration
Requires installation with:
```bash
pip install "praisonai[autogen]"
+4 -4
View File
@@ -23,7 +23,7 @@ from praisonai.auto import AutoGenerator
### praisonai.agents_generator
Framework-specific agent generation and orchestration:
- CrewAI support (requires `praisonai[crewai]`)
- AutoGen support (requires `praisonai[autogen]`)
- AG2 (Formerly AutoGen) support (requires `praisonai[autogen]`)
```python
from praisonai.agents_generator import AgentsGenerator
@@ -51,7 +51,7 @@ pip install praisonai
# Framework-specific installations
pip install "praisonai[crewai]" # Install with CrewAI support
pip install "praisonai[autogen]" # Install with AutoGen support
pip install "praisonai[autogen]" # Install with AG2 support
pip install "praisonai[crewai,autogen]" # Install both frameworks
# Additional features
@@ -71,9 +71,9 @@ When installing with `pip install "praisonai[crewai]"`, you get:
- Task delegation capabilities
- Sequential and parallel task execution
### AutoGen
### AG2 (Formerly AutoGen)
When installing with `pip install "praisonai[autogen]"`, you get:
- AutoGen framework support
- AG2 framework support
- PraisonAI tools integration
- Multi-agent conversation capabilities
- Code execution environment
+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.2.16 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>
+71
View File
@@ -0,0 +1,71 @@
---
title: "Introduction to AI Agents"
description: "Welcome to the beginner's course on AI Agents"
icon: "book-open"
---
# Introduction to AI Agents
Welcome to the beginners' course on AI Agents! This course is designed to help you understand and build your own AI agents, even if you have little to no programming experience.
## What Are AI Agents?
An AI agent is a software program that can:
- Understand information from its environment
- Make decisions based on that information
- Take actions to achieve specific goals
Think of an AI agent like a helpful assistant that can perform tasks for you automatically.
```mermaid
graph TD
A[Perceive Information] --> B[Make Decisions]
B --> C[Take Actions]
C --> A
```
## Examples in Daily Life
You might already be using AI agents without realizing it:
- **Virtual Assistants**: Siri, Alexa, and Google Assistant are AI agents that respond to your voice commands
- **Recommendation Systems**: Netflix, YouTube, and Amazon use AI agents to suggest content you might like
- **Smart Home Devices**: Devices that adjust temperature or lighting based on your preferences
## What You'll Learn in This Course
Throughout this course, you will:
1. Understand the basic concepts of AI agents
2. Learn about different types of AI agents
3. Explore how AI agents make decisions
4. Discover how to build simple AI agents without complex programming
5. Create your own functional AI agents
## Who This Course Is For
This course is perfect for:
- Complete beginners with no prior knowledge of AI
- Non-technical professionals interested in how AI can solve problems
- Students curious about artificial intelligence
- Anyone who wants to understand and use AI agents in practical ways
Let's begin our journey into the fascinating world of AI agents!
<iframe
id="codeExecutionFrame"
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
width="100%"
height="600px"
frameborder="0"
allow="clipboard-read; clipboard-write"
scrolling="yes"
onload="resizeIframe(this)"
></iframe>
<IframeWithAutoHeight />
<CardGroup cols={1}>
<Card title="Ready to Start?" icon="rocket">
Continue to the next lesson to learn about the different types of AI agents.
</Card>
</CardGroup>
+113
View File
@@ -0,0 +1,113 @@
---
title: "Types of AI Agents"
description: "Understanding the different categories of AI agents"
icon: "sitemap"
---
# Types of AI Agents
AI agents come in different forms, each designed for specific purposes and with varying levels of complexity. Understanding these types will help you choose the right approach for your needs.
## Simple Reflex Agents
These are the most basic type of AI agents that operate using simple if-then rules.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="lightbulb">
- React directly to current input only
- No memory of past events
- No prediction of future states
- Use predefined rules to determine actions
</Card>
</CardGroup>
**Real-world example**: A basic thermostat that turns heating on when temperature drops below a set point.
```mermaid
graph LR
A[Sensor Input] --> B{If-Then Rules}
B --> C[Action]
```
## Model-Based Agents
These agents maintain an internal model of their environment to make better decisions.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="brain">
- Build and maintain an internal representation of the world
- Can work with partial information
- Can consider "what if" scenarios
- Make decisions based on their understanding of how the world works
</Card>
</CardGroup>
**Real-world example**: A GPS navigation system that models roads and traffic conditions.
## Goal-Based Agents
These agents make decisions based on how their actions will help achieve specific goals.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="bullseye">
- Consider future consequences of actions
- Evaluate which actions will lead toward goals
- Can plan sequences of actions
- Choose actions that maximize goal attainment
</Card>
</CardGroup>
**Real-world example**: A chess-playing AI that plans moves to achieve checkmate.
## Utility-Based Agents
These agents choose actions that maximize a specific utility (or happiness) function.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="chart-line">
- Assign a utility value to different possible outcomes
- Consider probability and risk
- Choose actions that maximize expected utility
- Can balance competing objectives
</Card>
</CardGroup>
**Real-world example**: An investment robo-advisor that balances risk and return.
## Learning Agents
These agents improve their performance over time through experience.
<CardGroup cols={1}>
<Card title="Key Characteristics" icon="graduation-cap">
- Learn from past experiences
- Adapt to changing environments
- Improve decision-making over time
- Can discover new strategies
</Card>
</CardGroup>
**Real-world example**: Recommendation systems that learn your preferences over time.
## Understanding Agent Complexity
<Tip>
As you move from Simple Reflex Agents toward Learning Agents, both capability and complexity increase. For beginners, starting with simpler agent types is often best.
</Tip>
## Which Agent Type Should You Build?
The best type of agent for your project depends on:
1. **The problem complexity**: Simple problems may only need reflex agents
2. **Available data**: Learning agents need training data
3. **Required adaptability**: Will your agent need to adapt to new situations?
4. **Available resources**: More complex agents require more computational power
In this course, we'll focus primarily on goal-based and simple learning agents as they provide a good balance of capability and complexity for beginners.
<CardGroup cols={1}>
<Card title="Next Steps" icon="arrow-right">
In the next lesson, we'll explore how agents process information and make decisions.
</Card>
</CardGroup>
@@ -0,0 +1,157 @@
---
title: "Agent Architecture"
description: "Understanding how AI agents are structured"
icon: "layer-group"
---
# Agent Architecture
Understanding how AI agents are structured will help you build more effective agents. This lesson covers the fundamental components of an agent's architecture.
## Basic Components of an AI Agent
Every AI agent, regardless of complexity, has these basic components:
```mermaid
graph TD
A[Sensors/Input] --> B[Processing Unit]
B --> C[Decision-Making]
C --> D[Actions/Output]
```
### 1. Input (Sensors)
This is how agents receive information from their environment.
<CardGroup cols={1}>
<Card title="Examples of Input" icon="eye">
- Text input from users
- Data from databases
- Image or audio input
- API responses
- Sensor readings (in physical agents)
</Card>
</CardGroup>
### 2. Processing Unit
This component processes information and converts it into a format the agent can understand.
<CardGroup cols={1}>
<Card title="Processing Functions" icon="gears">
- Data cleaning and transformation
- Feature extraction
- Context building
- Information retrieval
- Pattern recognition
</Card>
</CardGroup>
### 3. Decision-Making Core
The "brain" of the agent that determines what actions to take.
<CardGroup cols={1}>
<Card title="Decision Components" icon="brain">
- Language models (like GPT-4)
- Rule systems
- Planning algorithms
- Knowledge base
- Memory systems
</Card>
</CardGroup>
### 4. Output (Actions)
The actions the agent can perform to achieve its goals.
<CardGroup cols={1}>
<Card title="Action Examples" icon="hand">
- Generating text responses
- Creating visual content
- Making API calls
- Controlling other systems
- Updating databases
</Card>
</CardGroup>
## The Agent Loop
Agents operate in a continuous loop:
```mermaid
graph LR
A[Perceive] --> B[Process]
B --> C[Decide]
C --> D[Act]
D --> A
```
This cycle allows agents to continuously:
1. Gather information
2. Update their understanding
3. Make new decisions
4. Take appropriate actions
## PraisonAI Agent Architecture
In the PraisonAI framework, agents follow a specific architecture:
<CardGroup cols={1}>
<Card title="PraisonAI Agent Components" icon="puzzle-piece">
- **Instructions**: Defines the agent's purpose and behavior
- **Language Model**: Powers the agent's intelligence (e.g., GPT-4)
- **Memory**: Stores context and previous interactions
- **Tools**: Specialized capabilities an agent can use
</Card>
</CardGroup>
### Simple Agent Structure
```python
from praisonaiagents import Agent
# Create a simple agent
research_agent = Agent(
instructions="Research the latest developments in renewable energy",
name="ResearchAgent"
)
# Start the agent
research_agent.start()
```
## Understanding Agent Communication
Multi-agent systems allow agents to communicate with each other:
```mermaid
graph LR
A[Agent 1] --> B[Agent 2]
B --> C[Agent 3]
C --> A
```
Each agent can:
- Pass information to other agents
- Request assistance from specialized agents
- Collaborate on complex tasks
## Key Takeaways
<CardGroup cols={2}>
<Card title="Component Importance" icon="check">
Each component plays a vital role in the agent's functionality
</Card>
<Card title="Agent Customization" icon="gear">
You can customize each component based on your specific needs
</Card>
<Card title="Component Balance" icon="scale-balanced">
A well-designed agent balances all components effectively
</Card>
<Card title="Continuous Improvement" icon="arrow-trend-up">
Agents can be improved by enhancing individual components
</Card>
</CardGroup>
In the next lesson, we'll explore how to define effective instructions for your AI agents.
@@ -0,0 +1,187 @@
---
title: "Creating Effective Agent Instructions"
description: "How to write clear instructions for your AI agents"
icon: "file-lines"
---
# Creating Effective Agent Instructions
The instructions you give to your AI agent are crucial to its performance. Well-crafted instructions lead to agents that understand their purpose and execute tasks effectively.
## Why Instructions Matter
Instructions serve as the agent's "job description" and guide its behavior:
<CardGroup cols={2}>
<Card title="Clarity" icon="glasses">
Clear instructions reduce confusion and misinterpretation
</Card>
<Card title="Focus" icon="bullseye">
Specific instructions keep the agent on task
</Card>
<Card title="Boundaries" icon="border-all">
Good instructions define what an agent should and shouldn't do
</Card>
<Card title="Personality" icon="face-smile">
Instructions can shape how an agent communicates
</Card>
</CardGroup>
## Elements of Effective Instructions
### 1. Role Definition
Tell the agent who it is and what its expertise should be.
<CodeGroup>
```text Good Example
You are a financial analyst with expertise in market trends and investment strategies.
```
```text Weak Example
You are a helper.
```
</CodeGroup>
### 2. Purpose and Goals
Clearly state what the agent should accomplish.
<CodeGroup>
```text Good Example
Your goal is to analyze company quarterly reports and provide actionable investment insights.
```
```text Weak Example
Help with finance stuff.
```
</CodeGroup>
### 3. Process Guidelines
Explain how the agent should approach tasks.
<CodeGroup>
```text Good Example
First analyze the data trends, then identify key risk factors, and finally make recommendations based on the client's risk tolerance.
```
```text Weak Example
Just do a good analysis.
```
</CodeGroup>
### 4. Response Format
Specify how you want information presented.
<CodeGroup>
```text Good Example
Present your analysis in a structured format with: Summary, Key Findings, Risk Assessment, and Recommendations.
```
```text Weak Example
Tell me what you find.
```
</CodeGroup>
## Instructions Template
Here's a template you can use to create effective agent instructions:
```
You are a [ROLE] specializing in [EXPERTISE AREAS].
Your goal is to [MAIN OBJECTIVE].
When approaching tasks:
1. [FIRST STEP/APPROACH]
2. [SECOND STEP/APPROACH]
3. [THIRD STEP/APPROACH]
Present your results in [FORMAT PREFERENCES].
Additional guidelines:
- [SPECIFIC BEHAVIOR 1]
- [SPECIFIC BEHAVIOR 2]
- [SPECIFIC BEHAVIOR 3]
```
## Examples in PraisonAI
Let's look at how instructions are implemented in PraisonAI:
<CodeGroup>
```python Simple Example
from praisonaiagents import Agent
research_agent = Agent(
instructions="You are a research assistant specializing in climate science. Your goal is to find the latest research on rising sea levels and summarize key findings in bullet points."
)
research_agent.start()
```
```python Detailed Example
from praisonaiagents import Agent
content_agent = Agent(
name="ContentCreator",
instructions="""
You are a content creation specialist with expertise in digital marketing.
Your goal is to create engaging blog content that drives traffic and conversions.
When creating content:
1. Research the target keyword thoroughly
2. Create an attention-grabbing headline
3. Develop well-structured content with clear sections
4. Include actionable takeaways for readers
Present content in markdown format with proper headings, bullet points, and emphasis where appropriate.
Additional guidelines:
- Maintain a conversational but professional tone
- Include 2-3 relevant statistics to support key points
- Add a call-to-action at the end of each piece
"""
)
content_agent.start("Create a blog post about sustainable living tips")
```
</CodeGroup>
## Common Instruction Mistakes
<CardGroup cols={2}>
<Card title="Being Too Vague" icon="cloud">
Vague instructions lead to unpredictable outputs
</Card>
<Card title="Information Overload" icon="bomb">
Too many details can confuse the agent's priorities
</Card>
<Card title="Contradictory Guidelines" icon="arrows-split-up-and-left">
Conflicting instructions create confusion
</Card>
<Card title="Missing Context" icon="puzzle-piece-missing">
Insufficient background information leads to generic outputs
</Card>
</CardGroup>
## Refining Your Instructions
<Tip>
Good instructions often require iteration. Start with basic instructions, review the agent's performance, and refine as needed.
</Tip>
Effective instruction improvement follows this cycle:
```mermaid
graph TD
A[Write Initial Instructions] --> B[Test Agent Performance]
B --> C[Identify Issues/Gaps]
C --> D[Refine Instructions]
D --> B
```
In the next lesson, we'll explore how agents use tools to extend their capabilities.
+183
View File
@@ -0,0 +1,183 @@
---
title: "Agent Tools"
description: "Understanding how tools extend agent capabilities"
icon: "screwdriver-wrench"
---
# Agent Tools
Tools allow AI agents to interact with the world and perform specific actions. Think of tools as the "hands" of your agent that let it accomplish tasks beyond just generating text.
## What Are Agent Tools?
<CardGroup cols={1}>
<Card title="Definition" icon="toolbox">
Tools are functions or capabilities that agents can access to perform specific actions, retrieve information, or interact with external systems.
</Card>
</CardGroup>
Just as humans use tools to extend their physical abilities, AI agents use digital tools to extend their capabilities.
## Why Tools Matter
Tools transform agents from simple chat interfaces into powerful assistants that can:
<CardGroup cols={2}>
<Card title="Access Information" icon="database">
Retrieve data from various sources
</Card>
<Card title="Perform Calculations" icon="calculator">
Analyze numbers and data accurately
</Card>
<Card title="Create Content" icon="pen-to-square">
Generate images, code, or other media
</Card>
<Card title="Control Systems" icon="gears">
Interact with other software or hardware
</Card>
</CardGroup>
## Common Types of Tools
### 1. Information Retrieval Tools
These tools help agents access information beyond their training data.
**Examples:**
- Web search tools
- Database query tools
- Document retrieval tools
```python
# Example of a simple web search tool
from praisonaiagents import Agent
def web_search(query):
# Simplified example
return f"Results for: {query}"
agent = Agent(
instructions="Research assistant",
tools=[web_search]
)
```
### 2. Computation Tools
These tools perform calculations or data processing.
**Examples:**
- Calculator tools
- Data analysis tools
- Conversion tools
### 3. Content Creation Tools
These tools help generate or modify various types of content.
**Examples:**
- Image generation tools
- Code writing tools
- Document formatting tools
### 4. External API Tools
These tools connect to third-party services.
**Examples:**
- Weather API tools
- Translation API tools
- E-commerce API tools
## How Tools Work in PraisonAI
In the PraisonAI framework, tools follow a simple pattern:
1. Tools are defined as functions
2. Tools are registered with an agent
3. The agent decides when to use appropriate tools
4. Tool results are incorporated into the agent's reasoning
```mermaid
graph TD
A[Agent Receives Task] --> B{Needs a Tool?}
B -->|Yes| C[Select Appropriate Tool]
C --> D[Execute Tool]
D --> E[Process Tool Results]
E --> F[Continue Task]
B -->|No| F
```
## Creating Basic Tools
Here's a simple example of creating and using tools in PraisonAI:
```python
from praisonaiagents import Agent
# Define a simple calculator tool
def calculator(expression):
try:
return str(eval(expression))
except:
return "Error: Could not calculate"
# Create an agent with the tool
math_agent = Agent(
instructions="You are a math tutor helping students solve problems",
tools=[calculator]
)
# Use the agent
math_agent.start("Calculate 24 * 17 and explain the steps")
```
## Tool Best Practices
<CardGroup cols={2}>
<Card title="Clear Descriptions" icon="comment">
Provide detailed descriptions so the agent knows when to use each tool
</Card>
<Card title="Error Handling" icon="shield">
Make tools robust with proper error handling
</Card>
<Card title="Focused Purpose" icon="bullseye">
Each tool should do one thing well
</Card>
<Card title="Input Validation" icon="check-double">
Validate inputs to prevent misuse
</Card>
</CardGroup>
## Building a Toolbox
As you advance, you'll want to create a collection of tools your agent can use:
```python
from praisonaiagents import Agent, Tool
# Define multiple tools
def weather(location):
return f"Weather in {location}: Sunny, 75°F"
def translator(text, target_language):
return f"Translated to {target_language}: {text} (placeholder)"
def reminder(message, time):
return f"Reminder set for {time}: {message}"
# Create tool collection
tools = [
Tool(name="weather", function=weather, description="Get weather for a location"),
Tool(name="translator", function=translator, description="Translate text"),
Tool(name="reminder", function=reminder, description="Set a reminder")
]
# Create agent with multiple tools
assistant = Agent(
instructions="You are a helpful personal assistant",
tools=tools
)
```
In the next lesson, we'll explore how agents use memory to maintain context across interactions.
+167
View File
@@ -0,0 +1,167 @@
---
title: "Agent Memory"
description: "Understanding how agents maintain context and learn"
icon: "brain"
---
# Agent Memory
Memory enables AI agents to remember past interactions, maintain context, and provide more coherent responses over time. Without memory, agents would treat each interaction as if it was their first.
## Why Memory Matters
<CardGroup cols={2}>
<Card title="Context Awareness" icon="comments">
Remembers previous parts of a conversation
</Card>
<Card title="Personalization" icon="user-gear">
Recalls user preferences and history
</Card>
<Card title="Continuous Learning" icon="graduation-cap">
Builds on past experiences
</Card>
<Card title="Task Persistence" icon="list-check">
Maintains progress on long-running tasks
</Card>
</CardGroup>
## Types of Agent Memory
### 1. Short-Term Memory (Conversation Memory)
This type of memory stores recent interactions within a session.
```mermaid
graph LR
A[User Input 1] --> B[Agent Response 1]
B --> C[User Input 2]
C --> D[Agent Response 2]
D --> E[User Input 3]
```
The agent can refer back to earlier messages in the same conversation.
### 2. Long-Term Memory
This allows agents to remember information across different sessions.
<CardGroup cols={1}>
<Card title="Use Cases" icon="clock">
- Remembering user preferences
- Recalling previous tasks completed
- Storing learned information
- Maintaining relationship history
</Card>
</CardGroup>
### 3. Working Memory
This is where agents process current information and combine it with retrieved memories.
```mermaid
graph TD
A[Current Input] --> D[Working Memory]
B[Short-Term Memory] --> D
C[Long-Term Memory] --> D
D --> E[Agent Response]
```
## How Memory Works in PraisonAI
In the PraisonAI framework, memory is handled automatically for basic cases and can be customized for more advanced needs:
```python
from praisonaiagents import Agent
# Basic agent with default memory handling
agent = Agent(
instructions="You are a helpful assistant that remembers our conversations"
)
# The conversation history is maintained automatically
agent.start("My name is Alex")
agent.continue("What's my name?")# Note: TODO: This Feature yet to be developed # Agent will remember "Alex"
```
## Memory Limitations
<Tip>
All AI memories have limitations. They aren't perfect and may occasionally forget or misremember information.
</Tip>
Common limitations include:
<CardGroup cols={2}>
<Card title="Memory Capacity" icon="database">
Limit to how much information can be stored
</Card>
<Card title="Context Window" icon="window">
Only a portion of memory fits in the active context
</Card>
<Card title="Memory Decay" icon="hourglass-half">
Older memories may become less accessible
</Card>
<Card title="Memory Retrieval" icon="magnifying-glass">
Finding the right memory at the right time
</Card>
</CardGroup>
## Implementing Persistent Memory
For more advanced applications, you can implement custom memory systems:
```python
# Note: TODO: This Feature yet to be tested
from praisonaiagents import Agent, Memory
# Create a simple memory store
memory = Memory()
# Add information to memory
memory.add("user_name", "Alex")
memory.add("favorite_color", "blue")
# Create agent with this memory
agent = Agent(
instructions="You are a personal assistant",
memory=memory
)
# The agent can now access these memories
agent.start("What's my favorite color?") # Agent should respond "blue"
```
## Memory Best Practices
<CardGroup cols={2}>
<Card title="Prioritize Important Info" icon="star">
Not everything needs to be remembered
</Card>
<Card title="Verify When Uncertain" icon="question">
Have agents confirm uncertain memories
</Card>
<Card title="Structured Storage" icon="folder-tree">
Organize memories by categories
</Card>
<Card title="Regular Updates" icon="arrows-rotate">
Update memories when information changes
</Card>
</CardGroup>
## Memory in Multi-Agent Systems
In systems with multiple agents, memory can be:
1. **Private**: Each agent has its own memories
2. **Shared**: Agents have access to a common memory store
3. **Hybrid**: Some memories are private, others are shared
```mermaid
graph TD
A[Agent 1] --> B[Private Memory 1]
C[Agent 2] --> D[Private Memory 2]
A -.-> E[Shared Memory]
C -.-> E
```
In the next lesson, we'll learn about how to set up multiple agents to work together effectively.
@@ -0,0 +1,171 @@
---
title: "Multi-Agent Systems"
description: "How multiple agents can work together"
icon: "users"
---
# Multi-Agent Systems
Multi-agent systems allow multiple AI agents to work together, each handling different parts of a complex task. This approach mirrors how human teams collaborate, with each member contributing their specialized skills.
## Why Use Multiple Agents?
<CardGroup cols={2}>
<Card title="Specialization" icon="star">
Each agent can focus on its area of expertise
</Card>
<Card title="Complex Tasks" icon="puzzle-piece">
Break down difficult problems into manageable pieces
</Card>
<Card title="Scalability" icon="arrows-up-down">
Add more agents as tasks become more complex
</Card>
<Card title="Diverse Perspectives" icon="lightbulb">
Different agents can approach problems differently
</Card>
</CardGroup>
## Basic Multi-Agent Architecture
```mermaid
graph LR
A[Research Agent] --> B[Analysis Agent]
B --> C[Writing Agent]
C --> D[Final Output]
```
In this example:
1. The Research Agent gathers information
2. The Analysis Agent processes and interprets the data
3. The Writing Agent creates the final content
## Multi-Agent Patterns
### 1. Pipeline Pattern
Agents work in sequence, with each agent handling a specific stage of the process.
```mermaid
graph LR
A[Agent 1] --> B[Agent 2]
B --> C[Agent 3]
```
**Example Use Case**: Content creation where one agent researches, another drafts, and a third edits.
### 2. Expert Panel Pattern
Multiple specialist agents work in parallel on the same problem, then their outputs are combined.
```mermaid
graph TD
Task --> A[Expert Agent 1]
Task --> B[Expert Agent 2]
Task --> C[Expert Agent 3]
A --> D[Coordination Agent]
B --> D
C --> D
D --> Result
```
**Example Use Case**: Financial analysis where different experts analyze market trends, economic indicators, and company performance.
### 3. Hierarchical Pattern
A manager agent delegates tasks to worker agents and coordinates their efforts.
```mermaid
graph TD
A[Manager Agent] --> B[Worker Agent 1]
A --> C[Worker Agent 2]
A --> D[Worker Agent 3]
B --> A
C --> A
D --> A
```
**Example Use Case**: Project management where a coordinator assigns tasks and integrates results.
## Implementing Multi-Agent Systems in PraisonAI
Here's a simple example of creating a multi-agent system:
```python
from praisonaiagents import Agent, PraisonAIAgents
# Create individual agents
research_agent = Agent(
name="Researcher",
instructions="Research the latest trends in renewable energy"
)
analysis_agent = Agent(
name="Analyst",
instructions="Analyze the research findings and identify key insights"
)
writing_agent = Agent(
name="Writer",
instructions="Create a clear, engaging report based on the analysis"
)
# Create a multi-agent system
agents = PraisonAIAgents(
agents=[research_agent, analysis_agent, writing_agent]
)
# Start the agents
agents.start()
```
## Agent Communication
For agents to work together effectively, they need to communicate. This happens through:
<CardGroup cols={2}>
<Card title="Output Passing" icon="arrow-right">
One agent's output becomes another's input
</Card>
<Card title="Shared Memory" icon="database">
Agents can access common information
</Card>
<Card title="Message Exchange" icon="comments">
Agents can send specific messages to each other
</Card>
<Card title="Coordination Protocols" icon="traffic-light">
Rules that determine how agents interact
</Card>
</CardGroup>
## Challenges in Multi-Agent Systems
<CardGroup cols={2}>
<Card title="Coordination" icon="shuffle">
Ensuring agents work together smoothly
</Card>
<Card title="Conflicting Goals" icon="arrows-split-up-and-left">
Managing agents with different objectives
</Card>
<Card title="Information Transfer" icon="exchange">
Passing information effectively between agents
</Card>
<Card title="Resource Management" icon="microchip">
Allocating computational resources efficiently
</Card>
</CardGroup>
## Designing Effective Multi-Agent Systems
<Tip>
Start simple with just 2-3 agents and a clear workflow before scaling to more complex systems.
</Tip>
Key principles for effective design:
1. **Clear Role Definition**: Each agent should have a specific and well-defined role
2. **Minimized Dependencies**: Reduce complex interdependencies between agents
3. **Standardized Communication**: Use consistent formats for information exchange
4. **Failure Handling**: Plan for cases where an agent fails to complete its task
5. **Performance Monitoring**: Track how well each agent and the overall system performs
In the next lesson, we'll explore how to create effective agent workflows using the Process component.
+152
View File
@@ -0,0 +1,152 @@
---
title: "Agent Process"
description: "Understanding agent workflows and processes"
icon: "diagram-project"
---
# Agent Process
The Process component in AI agent systems defines how agents work together and the flow of information between them. Think of it as the "playbook" that coordinates how agents complete tasks.
## What is an Agent Process?
<CardGroup cols={1}>
<Card title="Definition" icon="route">
A process is a structured workflow that defines the sequence of steps, decision points, and information flow between agents to complete a task.
</Card>
</CardGroup>
## Process Flow Basics
A simple process flow might look like this:
```mermaid
graph LR
A[Start] --> B[Gather Information]
B --> C[Process Information]
C --> D[Make Decision]
D --> E[Take Action]
E --> F[Report Results]
```
Each step could be handled by a different agent or by the same agent in different stages.
## Types of Process Flows
### 1. Sequential Process
Agents work in a straight line, one after another.
```mermaid
graph LR
A[Agent 1] --> B[Agent 2]
B --> C[Agent 3]
C --> D[Complete]
```
**Best for**: Tasks with clear, linear stages
### 2. Parallel Process
Multiple agents work simultaneously on different parts of a task.
```mermaid
graph TD
A[Start] --> B[Agent 1]
A --> C[Agent 2]
A --> D[Agent 3]
B --> E[Combine Results]
C --> E
D --> E
E --> F[Complete]
```
**Best for**: Tasks that can be broken into independent pieces
### 3. Conditional Process
The workflow changes based on decisions or conditions.
```mermaid
graph TD
A[Start] --> B{Decision Point}
B -->|Condition A| C[Agent 1]
B -->|Condition B| D[Agent 2]
C --> E[Complete]
D --> E
```
**Best for**: Tasks requiring different approaches based on circumstances
## Implementing Process in PraisonAI
Here's a simple example of creating a process in PraisonAI:
```python
from praisonaiagents import Agent, Process, PraisonAIAgents
# Create agents
research_agent = Agent(
name="Researcher",
instructions="Research the topic and gather key information about AI"
)
writing_agent = Agent(
name="Writer",
instructions="Create content based on the research"
)
editing_agent = Agent(
name="Editor",
instructions="Review and improve the content"
)
# Create the multi-agent system with the process
agents = PraisonAIAgents(
agents=[research_agent, writing_agent, editing_agent],
process="hierarchical"
)
# Start the process
agents.start()
```
## Process Best Practices
<CardGroup cols={2}>
<Card title="Clear Step Definitions" icon="list-check">
Define exactly what each step should accomplish
</Card>
<Card title="Error Handling" icon="bug">
Include steps for handling unexpected situations
</Card>
<Card title="Feedback Loops" icon="repeat">
Allow agents to request clarification when needed
</Card>
<Card title="Modular Design" icon="cubes">
Create reusable process components
</Card>
</CardGroup>
<Tip>
Start with simple processes and gradually add complexity as you become more comfortable with the system.
</Tip>
## Monitoring Process Execution
It's important to track how your processes are running:
```python
agents = PraisonAIAgents(
agents=[research_agent, writing_agent, editing_agent],
process=content_process,
verbose=True # Enables detailed logging
)
```
This will provide information about:
- Which step is currently running
- The inputs and outputs of each step
- Any errors or issues encountered
In the next lesson, we'll explore how to use knowledge bases to enhance agent capabilities.
+190
View File
@@ -0,0 +1,190 @@
---
title: "Knowledge Bases"
description: "Enhancing agents with specialized knowledge"
icon: "book"
---
# Knowledge Bases
Knowledge bases provide agents with specialized information beyond their training data. They help agents answer specific questions, follow guidelines, or work within defined domains.
## What is a Knowledge Base?
<CardGroup cols={1}>
<Card title="Definition" icon="database">
A knowledge base is a structured collection of information that an agent can access to answer questions or make decisions.
</Card>
</CardGroup>
Think of a knowledge base as a specialized reference library for your agent.
## Why Use Knowledge Bases?
<CardGroup cols={2}>
<Card title="Domain Expertise" icon="user-graduate">
Provide specialized information for specific fields
</Card>
<Card title="Current Information" icon="clock">
Include data beyond the agent's training cutoff
</Card>
<Card title="Custom Guidelines" icon="list">
Define rules and policies for the agent to follow
</Card>
<Card title="Consistent Responses" icon="equals">
Ensure agents provide standardized answers
</Card>
</CardGroup>
## Types of Knowledge Bases
### 1. Document Collections
Text documents, articles, guides, or manuals that agents can reference.
```mermaid
graph TD
A[Query] --> B[Search Documents]
B --> C[Find Relevant Content]
C --> D[Generate Response]
```
### 2. Structured Data
Databases, tables, or other structured formats that organize information systematically.
<CardGroup cols={1}>
<Card title="Examples" icon="table">
- Product catalogs with specifications
- Customer information databases
- Statistical data collections
- Reference tables for compliance information
</Card>
</CardGroup>
### 3. Vector Databases
Special databases that store information as numerical representations (vectors) for semantic search.
```mermaid
graph TD
A[User Question] --> B[Convert to Vector]
B --> C[Find Similar Vectors]
C --> D[Retrieve Related Information]
D --> E[Generate Answer]
```
## Implementing Knowledge Bases in PraisonAI
Here's an example of how to use a knowledge base with an agent:
```python
from praisonaiagents import Agent
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"]
)
agent.start("What is KAG in one line?")
```
## Advanced Configuration
For more control over the knowledge base, you can specify a configuration:
```python
from praisonaiagents import Agent
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "custom_knowledge",
"path": ".praison",
}
}
}
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"],
knowledge_config=config
)
agent.start("What is KAG in one line?")
```
## Knowledge Retrieval Process
When an agent uses a knowledge base, this typical process occurs:
```mermaid
graph LR
A[User Question] --> B[Query Processing]
B --> C[Search Knowledge Base]
C --> D[Rank Results]
D --> E[Synthesize Answer]
```
1. **Query Processing**: The user's question is analyzed
2. **Search**: The system searches the knowledge base for relevant information
3. **Ranking**: Results are ranked by relevance
4. **Synthesis**: The agent creates an answer using the retrieved information
## Best Practices for Knowledge Bases
<CardGroup cols={2}>
<Card title="Keep Information Current" icon="arrows-rotate">
Regularly update your knowledge base
</Card>
<Card title="Organize Logically" icon="folder-tree">
Structure information in intuitive categories
</Card>
<Card title="Prioritize Quality" icon="star">
Focus on accurate, high-quality information
</Card>
<Card title="Include Examples" icon="list">
Add examples to illustrate complex concepts
</Card>
</CardGroup>
## When to Use Knowledge Bases
Knowledge bases are particularly valuable when:
1. Your agent needs to reference specific information that may change over time
2. You need to ensure consistent answers to common questions
3. Your agent needs to follow specific guidelines or protocols
4. You want to provide expertise in specialized domains
<Tip>
Start with a small knowledge base focusing on the most important information, then expand as needed.
</Tip>
## Creating a Simple Knowledge Base
For beginners, you can start with a simple text-based knowledge base:
```
# Company FAQ Knowledge Base
## Return Policy
Our return policy allows customers to return products within 30 days of purchase for a full refund.
## Shipping Information
Standard shipping takes 3-5 business days. Express shipping takes 1-2 business days.
## Product Warranty
All products come with a 1-year limited warranty covering manufacturing defects.
```
Save this as a text file and add it to your knowledge base:
```python
kb = KnowledgeBase()
kb.add_document("company_faq.txt")
```
In the next lesson, we'll explore how agents handle tasks and the task management process.
+274
View File
@@ -0,0 +1,274 @@
---
title: "Agent Tasks"
description: "Understanding how agents handle and manage tasks"
icon: "clipboard-list"
---
# Agent Tasks
Tasks are the specific units of work that AI agents perform. Understanding how to define and manage tasks is essential for creating effective agent systems.
## What is an Agent Task?
<CardGroup cols={1}>
<Card title="Definition" icon="list-check">
A task is a specific, well-defined piece of work assigned to an agent with clear inputs, expected outputs, and success criteria.
</Card>
</CardGroup>
Just as human jobs are broken into specific responsibilities, agent systems work best when complex goals are divided into manageable tasks.
## Anatomy of a Task
A well-defined task includes:
<CardGroup cols={2}>
<Card title="Objective" icon="bullseye">
What the task should accomplish
</Card>
<Card title="Inputs" icon="arrow-right-to-bracket">
Information provided to complete the task
</Card>
<Card title="Process" icon="gears">
Steps to follow or approach to take
</Card>
<Card title="Outputs" icon="arrow-right-from-bracket">
Expected results or deliverables
</Card>
</CardGroup>
## Task Types
### 1. Information Tasks
These tasks involve finding, analyzing, or summarizing information.
**Examples:**
- Research a topic
- Summarize a document
- Extract data from text
- Answer questions
### 2. Creation Tasks
These tasks involve generating new content.
**Examples:**
- Write an article
- Create a marketing plan
- Generate images (with appropriate tools)
- Design a workflow
### 3. Analysis Tasks
These tasks involve evaluating information and drawing conclusions.
**Examples:**
- Analyze data trends
- Review content for quality
- Evaluate options
- Identify patterns
### 4. Interaction Tasks
These tasks involve communicating or working with users or other systems.
**Examples:**
- Answer customer questions
- Guide users through processes
- Collect information from users
- Notify about events
## Creating Tasks in PraisonAI
### Task Flow
The typical lifecycle of a task follows this pattern:
```mermaid
graph LR
A[Define Task] --> B[Assign to Agent]
B --> C[Execute Task]
C --> D[Return Results]
D --> E[Evaluate Success]
```
### Task Configuration
<CodeGroup>
```python Basic
task = Task(
description="Research AI trends",
expected_output="Summary report",
agent=research_agent
)
```
```python Advanced
task = Task(
description="Analyze market data",
expected_output="Detailed analysis",
agent=analyst_agent,
tools=[AnalysisTool()],
output_file="analysis.md",
async_execution=True
)
```
</CodeGroup>
# Understanding Tasks
<br />
```mermaid
graph LR
%% Task Flow Steps
Start([▶ Start]) --> TaskDef
TaskDef --> AgentAssign
AgentAssign --> Exec
Exec --> Output([✓ Output])
%% Define subgraphs for each step
subgraph TaskDef[" "]
TD_Icon[📋 Task Definition]
TD_Desc[Description & Requirements]
TD_Icon --- TD_Desc
style TD_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
style TD_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
end
subgraph AgentAssign[" "]
AA_Icon[🤖 Agent Assignment]
AA_Desc[Matching & Delegation]
AA_Icon --- AA_Desc
style AA_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
style AA_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
end
subgraph Exec[" "]
E_Icon[⚙️ Execution]
E_Desc[Processing & Tools]
E_Icon --- E_Desc
style E_Icon fill:#2D3047,stroke:#7C90A0,color:#fff
style E_Desc fill:#5C80BC,stroke:#7C90A0,color:#fff
end
%% Styling for main elements
style Start fill:#2D3047,stroke:#7C90A0,color:#fff
style Output fill:#2D3047,stroke:#7C90A0,color:#fff
%% Style for containers
style TaskDef fill:#1B1F3B,stroke:#7C90A0,color:#fff
style AgentAssign fill:#1B1F3B,stroke:#7C90A0,color:#fff
style Exec fill:#1B1F3B,stroke:#7C90A0,color:#fff
%% Global styles
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
linkStyle default stroke:#7C90A0,stroke-width:2px
```
<br /><br />
```mermaid
graph LR
%% Task States
Pending([📥 Pending]) --> InProgress([⚡ In Progress])
InProgress --> Completed([✅ Completed])
InProgress --> Failed([❌ Failed])
%% Styling
style Pending fill:#2D3047,stroke:#7C90A0,color:#fff
style InProgress fill:#5C80BC,stroke:#7C90A0,color:#fff
style Completed fill:#2D3047,stroke:#7C90A0,color:#fff
style Failed fill:#2D3047,stroke:#7C90A0,color:#fff
%% Global styles
classDef default fill:#2D3047,stroke:#7C90A0,color:#fff
linkStyle default stroke:#7C90A0,stroke-width:2px
```
## Task Types
<Steps>
<Step title="Basic Task">
Simple, single-operation tasks with clear inputs and outputs
</Step>
<Step title="Decision Task">
Tasks involving choices and conditional paths
```python
decision_task = Task(
type="decision",
conditions={
"success": ["next_task"],
"failure": ["error_task"]
}
)
```
</Step>
<Step title="Loop Task">
Repetitive operations over collections
```python
loop_task = Task(
type="loop",
items=data_list,
operation="process_item"
)
```
</Step>
</Steps>
## Task Relationships
<Warning>
Properly managing task dependencies is crucial for complex workflows. Always ensure proper context sharing and error handling.
</Warning>
### Context Sharing
```python
task_a = Task(name="research")
task_b = Task(
name="analyze",
context=[task_a] # Uses task_a's output
)
```
## Task Best Practices
<CardGroup cols={2}>
<Card title="Be Specific" icon="magnifying-glass">
Clearly define what the task should accomplish
</Card>
<Card title="One Goal Per Task" icon="check-double">
Each task should focus on a single objective
</Card>
<Card title="Provide Context" icon="circle-info">
Include necessary background information
</Card>
<Card title="Define Success" icon="trophy">
Specify what a successful outcome looks like
</Card>
</CardGroup>
<Tip>
Break complex goals into multiple smaller tasks rather than creating one large, complex task.
</Tip>
## Common Task Mistakes
<CardGroup cols={2}>
<Card title="Vague Instructions" icon="question">
Unclear about what the agent should do
</Card>
<Card title="Too Many Objectives" icon="list-ol">
Asking for too many things in one task
</Card>
<Card title="Missing Context" icon="puzzle-piece-missing">
Not providing necessary background information
</Card>
<Card title="Unrealistic Expectations" icon="mountain-sun">
Asking for tasks beyond agent capabilities
</Card>
</CardGroup>
In the next lesson, we'll learn about creating your first complete agent application.
@@ -0,0 +1,172 @@
---
title: "Creating Your First Agent"
description: "A step-by-step guide to building your first AI agent"
icon: "robot"
---
# Creating Your First Agent
In this lesson, we'll walk through the process of building a simple AI agent. We'll focus on practical implementation without complex programming.
## What We'll Build
We'll create a basic research assistant agent that can:
- Understand simple instructions
- Respond to questions
- Provide helpful information
## Prerequisites
Before you begin, make sure you have:
1. A basic understanding of the concepts from previous lessons
2. Python installed on your computer (if following the code examples)
3. An OpenAI API key (or access to another supported language model)
## Step 1: Installation
First, install the PraisonAI package:
```bash
pip install praisonaiagents
```
## Step 2: Setup Your Environment
Create a file called `first_agent.py` and set up your API key:
```python
import os
from praisonaiagents import Agent
# Set your API key
# Option 1: Set it in your environment (recommended)
# export OPENAI_API_KEY=your_key_here
# Option 2: Set it in your code (not recommended for production)
# os.environ["OPENAI_API_KEY"] = "your_key_here"
```
## Step 3: Define Your Agent
Now, let's create a simple agent:
```python
# Create a research assistant agent
research_assistant = Agent(
name="ResearchAssistant",
instructions="""
You are a helpful research assistant that provides clear,
accurate information on various topics. When answering:
1. Be concise and to the point
2. Explain complex concepts in simple terms
3. When appropriate, organize information with bullet points
4. If you don't know something, admit it instead of guessing
"""
)
```
## Step 4: Start Your Agent
Now let's use our agent to answer a question:
```python
# Start the agent with a specific query
response = research_assistant.start("Explain how solar panels work in simple terms")
# Print the response
print(response)
```
## Step 5: Run Your Agent
Save the file and run it from your terminal:
```bash
python first_agent.py
```
You should see the agent's response explaining how solar panels work in simple terms.
## Experimenting with Your Agent
Try changing the question to see how your agent responds to different topics:
```python
# Try different questions
response = research_assistant.start("What are the benefits of exercise?")
# or
response = research_assistant.start("How does artificial intelligence work?")
```
## Modifying Agent Behavior
You can change how your agent behaves by adjusting its instructions:
```python
# Create an agent with different instructions
creative_writer = Agent(
name="CreativeWriter",
instructions="""
You are a creative writer that specializes in short, engaging stories.
Your writing should:
1. Include vivid descriptions
2. Have interesting characters
3. Include some dialogue
4. Have a clear beginning, middle, and end
"""
)
# Ask for a story
story = creative_writer.start("Write a short story about a lost dog finding its way home")
print(story)
```
## Examining How It Works
What's happening behind the scenes:
1. The agent receives your instructions and query
2. The language model (like GPT-4) processes the information
3. The model generates a response based on the instructions and query
4. The response is returned to you
```mermaid
graph TD
A[Your Instructions] --> B[Agent]
C[Your Query] --> B
B --> D[Language Model]
D --> E[Generated Response]
E --> F[Output to You]
```
## Common Challenges
If you encounter issues, check these common problems:
<CardGroup cols={2}>
<Card title="API Key Issues" icon="key">
Make sure your API key is set correctly
</Card>
<Card title="Connection Problems" icon="wifi">
Check your internet connection
</Card>
<Card title="Unclear Instructions" icon="circle-question">
Try making your instructions more specific
</Card>
<Card title="Rate Limits" icon="hand">
You might be making too many API calls
</Card>
</CardGroup>
## Next Steps
Now that you've created your first agent, you can:
- Experiment with different instructions
- Try more complex queries
- Add specialized capabilities (we'll cover this in upcoming lessons)
- Create agents for specific use cases
Congratulations on creating your first AI agent! In the next lesson, we'll explore how to add tools to enhance your agent's capabilities.
@@ -0,0 +1,275 @@
---
title: "Adding Tools to Agents"
description: "Enhancing your agents with specialized capabilities"
icon: "screwdriver-wrench"
---
# Adding Tools to Agents
In this lesson, we'll learn how to enhance your agents by adding tools. Tools allow agents to perform specific actions beyond just generating text, making them much more useful for real-world tasks.
## What You'll Learn
By the end of this lesson, you'll understand:
- What agent tools are and why they're useful
- How to create simple tools for your agents
- How to integrate tools with your agents
- Best practices for tool design
## Understanding Agent Tools
Tools give your agents the ability to:
- Perform calculations
- Access specific information
- Interact with external systems
- Generate different types of content
<Tabs>
<Tab title="Code">
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents duckduckgo-search
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Create Agent with Tool">
Create `app.py`
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent
from duckduckgo_search import DDGS
# 1. Define the tool
def internet_search_tool(query: str):
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
# 2. Assign the tool to an agent
search_agent = Agent(
instructions="Perform internet searches to collect relevant information.",
tools=[internet_search_tool] # <--- Tool Assignment
)
# 3. Start Agent
search_agent.start("Search about AI job trends in 2025")
```
```python Multiple Agents
from praisonaiagents import Agent, PraisonAIAgents
from duckduckgo_search import DDGS
# 1. Define the tool
def internet_search_tool(query: str):
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
# 2. Assign the tool to an agent
search_agent = Agent(
instructions="Search about AI job trends in 2025",
tools=[internet_search_tool] # <--- Tool Assignment
)
blog_agent = Agent(
instructions="Write a blog article based on the previous agent's search results."
)
# 3. Start Agents
agents = PraisonAIAgents(agents=[search_agent, blog_agent])
agents.start()
```
</CodeGroup>
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
python app.py
```
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install PraisonAI">
Install the core package and duckduckgo_search package:
```bash Terminal
pip install praisonai duckduckgo_search
```
</Step>
<Step title="Create Custom Tool">
<Info>
To add additional tools/features you need some coding which can be generated using ChatGPT or any LLM
</Info>
Create a new file `tools.py` with the following content:
```python
from duckduckgo_search import DDGS
from typing import List, Dict
# 1. Tool
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search
"""
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
```
</Step>
<Step title="Create Agent">
Create a new file `agents.yaml` with the following content:
```yaml
framework: praisonai
topic: create movie script about cat in mars
roles:
scriptwriter:
backstory: Expert in dialogue and script structure, translating concepts into
scripts.
goal: Write a movie script about a cat in Mars
role: Scriptwriter
tools:
- internet_search_tool # <-- Tool assigned to Agent here
tasks:
scriptwriting_task:
description: Turn the story concept into a production-ready movie script,
including dialogue and scene details.
expected_output: Final movie script with dialogue and scene details.
```
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
praisonai agents.yaml
```
</Step>
</Steps>
</Tab>
</Tabs>
## Creating Custom Tool
<Steps>
<Step>
Create any function that you want to use as a tool, that performs a specific task.
```python
from duckduckgo_search import DDGS
def internet_search_tool(query: str):
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
```
</Step>
<Step>
Assign the tool to an agent
```python
data_agent = Agent(
instructions="Search about AI job trends in 2025",
tools=[internet_search_tool], # <-- Tool Assignment
)
```
</Step>
</Steps>
<Card title="That's it!">
<Check>You have created a custom tool and assigned it to an agent.</Check>
</Card>
## When Does the Agent Use Tools?
The agent decides when to use tools based on:
1. The nature of the user's request
2. The tools available to it
3. The instructions you've provided
If your agent isn't using tools when expected, you might need to:
- Make your instructions more explicit about when to use tools
- Provide more descriptive tool definitions
- Ensure the tools are appropriate for the task
## Tool Best Practices
<CardGroup cols={2}>
<Card title="Specific Purpose" icon="bullseye">
Each tool should have a clear, specific purpose
</Card>
<Card title="Error Handling" icon="shield-check">
Tools should handle errors gracefully
</Card>
<Card title="Descriptive Names" icon="tag">
Use clear names that indicate functionality
</Card>
<Card title="Clear Documentation" icon="file-lines">
Include detailed descriptions and examples
</Card>
</CardGroup>
## Real-World Tool Examples
In production systems, you might create tools for:
<CardGroup cols={2}>
<Card title="Database Access" icon="database">
Retrieve or store information in databases
</Card>
<Card title="API Integration" icon="link">
Connect to external services
</Card>
<Card title="File Operations" icon="folder">
Read from or write to files
</Card>
<Card title="Image Generation" icon="image">
Create images based on descriptions
</Card>
</CardGroup>
## Advanced Tool Concepts
As you become more comfortable with tools, you can explore:
- Tools that call other tools
- Tools with complex parameters
- Tools that maintain state
- Dynamically generated tools
In the next lesson, we'll explore how to create a multi-agent system for more complex tasks.
@@ -0,0 +1,218 @@
---
title: "Building a Multi-Agent System"
description: "Creating a system with multiple cooperative agents"
icon: "users"
---
# Building a Multi-Agent System
In this lesson, we'll create a simple multi-agent system where several agents work together to accomplish a task. This approach allows you to divide complex problems into smaller, more manageable pieces.
## What We'll Build
We'll create a content creation system with three specialized agents:
1. A research agent to gather information
2. A writing agent to create content
3. An editing agent to improve and refine the content
## Step 1: Setting Up
First, let's import the necessary modules and set up our environment:
```python
from praisonaiagents import Agent, PraisonAIAgents
# Make sure your API key is set in your environment:
# export OPENAI_API_KEY=your_openai_key
```
## Step 2: Creating Specialized Agents
Now, let's create our three specialized agents:
```python
# Research Agent
research_agent = Agent(
name="Researcher",
instructions="""
You are a research specialist who excels at finding relevant information.
Your job is to:
1. Thoroughly research the given topic
2. Identify key facts, statistics, and insights
3. Organize the information in a clear, structured format
4. Provide accurate information with no fabrications
5. Focus on the most relevant and current information
"""
)
# Writing Agent
writing_agent = Agent(
name="Writer",
instructions="""
You are a content writer who creates engaging, reader-friendly content.
Your job is to:
1. Use the research provided to create well-structured content
2. Write in a clear, engaging style
3. Include an attention-grabbing introduction
4. Organize the content with appropriate headings
5. Conclude with a summary and call-to-action when appropriate
"""
)
# Editing Agent
editing_agent = Agent(
name="Editor",
instructions="""
You are an editor who refines and improves content.
Your job is to:
1. Correct any grammatical or spelling errors
2. Improve clarity and flow
3. Ensure consistency in tone and style
4. Check for logical structure and organization
5. Enhance readability for the target audience
"""
)
```
## Step 3: Creating the Multi-Agent System
Now, let's combine these agents into a multi-agent system:
```python
# Create a multi-agent system
content_team = PraisonAIAgents(
agents=[research_agent, writing_agent, editing_agent]
)
```
## Step 4: Setting Up the Workflow
Next, we need to define how our agents will work together:
```python
# Define a topic
topic = "The Benefits of Regular Exercise"
# Start the multi-agent process
results = content_team.start(
f"""
Task: Create a comprehensive blog post about {topic}
Process:
1. Researcher: Research {topic} and provide key information including:
- Main benefits of exercise (physical and mental)
- Recommended exercise guidelines
- Scientific studies supporting the benefits
- Common misconceptions
2. Writer: Use the research to create a 500-word blog post about {topic} with:
- An engaging introduction
- Clear sections with headings
- Practical advice for readers
- A compelling conclusion
3. Editor: Review and improve the blog post by:
- Correcting any errors
- Enhancing clarity and flow
- Ensuring a consistent tone
- Making the content more engaging
"""
)
# Print the final result
print(results)
```
## Understanding the Workflow
Let's examine how the multi-agent system works:
```mermaid
graph TD
A[Start] --> B[Research Agent]
B --> C[Writing Agent]
C --> D[Editing Agent]
D --> E[Final Output]
```
1. The research agent gathers and organizes relevant information
2. The writing agent uses that research to create the initial content
3. The editing agent refines and improves the content
4. The final polished content is returned
## Customizing Agent Interactions
You can customize how agents interact by modifying the process instructions. For example, you could add feedback loops:
```python
process_with_feedback = """
Task: Create a comprehensive blog post about {topic}
Process:
1. Researcher: Research {topic} and provide key information
2. Writer: Use the research to create a blog post
3. Editor: Review the blog post and provide feedback
4. Writer: Revise the blog post based on the editor's feedback
5. Editor: Make final improvements to the revised blog post
"""
```
## Alternative Agent Configurations
You can organize multi-agent systems in different ways:
### Parallel Processing
```python
parallel_process = """
Task: Create a marketing campaign for a new product
Process:
1. Market Researcher: Research the target market and competitors
Content Researcher: Research the product features and benefits
[These tasks happen in parallel]
2. Strategy Agent: Use both research results to create a marketing strategy
3. Content Creator: Create the marketing materials based on the strategy
"""
```
### Expert Panel
```python
expert_panel = """
Task: Evaluate a business idea
Process:
1. Financial Expert: Analyze financial viability
Market Expert: Analyze market potential
Technical Expert: Analyze technical feasibility
[These assessments happen in parallel]
2. Coordinator: Compile all expert opinions into a final recommendation
"""
```
## Best Practices for Multi-Agent Systems
<CardGroup cols={2}>
<Card title="Clear Role Definition" icon="user-tag">
Define exactly what each agent is responsible for
</Card>
<Card title="Explicit Handoffs" icon="arrow-right-arrow-left">
Specify how information passes between agents
</Card>
<Card title="Avoid Redundancy" icon="copy">
Don't have multiple agents do the same work
</Card>
<Card title="Include Error Handling" icon="triangle-exclamation">
Plan for cases where an agent might fail
</Card>
</CardGroup>
In the next lesson, we'll learn how to create a conversational agent that can maintain context across multiple interactions.
@@ -0,0 +1,193 @@
---
title: "Building Conversational Agents"
description: "Creating agents that maintain context in conversations"
icon: "comments"
---
# Building Conversational Agents
In this lesson, we'll learn how to create conversational agents that can maintain context across multiple interactions. This is essential for creating assistants that feel natural to interact with.
## What Makes a Good Conversational Agent?
A good conversational agent should:
- Remember previous parts of the conversation
- Understand context and references
- Provide coherent, relevant responses
- Maintain a consistent personality
## Creating a Simple Conversational Agent
Let's build a basic conversational agent:
```python
# Note: TODO: This Feature yet to be developed
from praisonaiagents import Agent
# Create a conversational agent
chat_agent = Agent(
name="Conversational Assistant",
instructions="""
You are a friendly, helpful conversational assistant.
When chatting with users:
1. Maintain a warm, friendly tone
2. Remember information shared earlier in the conversation
3. Ask clarifying questions when needed
4. Keep responses concise but informative
5. Be helpful while respecting boundaries
"""
)
# Start a conversation
response = chat_agent.start("Hi there! My name is Jamie.")
print(response)
# Continue the conversation
response = chat_agent.continue("What can you help me with today?")
print(response)
# The agent should remember the user's name
response = chat_agent.continue("Can you remember my name?")
print(response)
```
## How Context Works
PraisonAI automatically manages conversation context for you:
```mermaid
graph TD
A[User Message 1] --> B[Agent]
B --> C[Response 1]
D[User Message 2] --> E[Agent + Context]
E --> F[Response 2]
G[User Message 3] --> H[Agent + More Context]
H --> I[Response 3]
```
The agent maintains a memory of the conversation, allowing it to refer back to previous messages.
## Conversation Settings
You can customize how your conversational agent behaves:
```python
# Create an agent with specific conversation settings
custom_chat_agent = Agent(
name="Custom Chat Assistant",
instructions="You are a helpful assistant",
memory_size=10, # Remember the last 10 messages
temperature=0.7 # Slightly more creative in responses
)
```
## Handling Different Types of Conversations
Different use cases require different conversation styles:
<CardGroup cols={2}>
<Card title="Customer Support" icon="headset">
- Professional and helpful tone
- Focus on problem resolution
- Remember customer details
</Card>
<Card title="Educational Tutor" icon="graduation-cap">
- Patient and explanatory
- Builds on previous lessons
- Adjusts to learning pace
</Card>
<Card title="Personal Assistant" icon="calendar">
- Remembers preferences
- Provides reminders
- Handles scheduling
</Card>
<Card title="Companion Chat" icon="user-group">
- More casual tone
- Focuses on engagement
- Shows personality
</Card>
</CardGroup>
## Example: Customer Support Agent
Let's create a specialized customer support agent:
```python
support_agent = Agent(
name="Support Agent",
instructions="""
You are a customer support specialist for a tech company.
When helping customers:
1. Greet them professionally
2. Show empathy for their issues
3. Ask for necessary information to troubleshoot
4. Provide clear step-by-step solutions
5. Confirm if the issue is resolved
6. End with an offer for additional help
Remember product details and customer information throughout the conversation.
"""
)
# Example conversation
print(support_agent.start("Hi, I'm having trouble logging into my account."))
print(support_agent.continue("My username is user123."))
print(support_agent.continue("I've tried resetting my password but I'm not receiving the email."))
```
## Building Multi-Turn Conversations
To create engaging multi-turn conversations, consider:
1. **Appropriate follow-up questions**: Keep the conversation flowing
2. **Acknowledgment**: Reference what the user has said
3. **Progressive disclosure**: Don't overwhelm with information at once
4. **Conversation repair**: Gracefully handle misunderstandings
## Example: Multi-Turn Educational Conversation
```python
tutor_agent = Agent(
name="Math Tutor",
instructions="""
You are a patient, encouraging math tutor.
When teaching:
1. Gauge the student's current understanding
2. Explain concepts using clear, simple language
3. Provide examples to illustrate points
4. Ask questions to check understanding
5. Give positive reinforcement for progress
Adapt your explanations based on the student's responses.
"""
)
# Example tutoring session
print(tutor_agent.start("Can you help me understand algebra?"))
print(tutor_agent.continue("I'm struggling with equations like 2x + 5 = 13"))
print(tutor_agent.continue("So I subtract 5 from both sides first?"))
print(tutor_agent.continue("Then I divide by 2 to get x = 4?"))
print(tutor_agent.continue("Could you give me another example to practice?"))
```
## Conversation Best Practices
<CardGroup cols={2}>
<Card title="Clear Transitions" icon="arrow-right">
Signal when changing topics
</Card>
<Card title="Manageable Chunks" icon="layer-group">
Break complex information into smaller pieces
</Card>
<Card title="Engagement Checks" icon="hand">
Periodically confirm understanding
</Card>
<Card title="Personality Consistency" icon="masks-theater">
Maintain a consistent tone and style
</Card>
</CardGroup>
In the next lesson, we'll explore how to build agents that can search and retrieve information from external sources.
+216
View File
@@ -0,0 +1,216 @@
---
title: "Building Research Agents"
description: "Creating agents that can gather and analyze information"
icon: "magnifying-glass"
---
# Building Research Agents
In this lesson, we'll build agents specialized in gathering, analyzing, and summarizing information. Research agents are valuable for quickly obtaining insights on various topics.
## What is a Research Agent?
A research agent is designed to:
- Find relevant information on specific topics
- Analyze and synthesize data
- Present findings in a clear, structured format
- Answer questions based on gathered information
## Creating a Basic Research Agent
Let's start by building a simple research agent:
```python
from praisonaiagents import Agent
# Create a basic research agent
research_agent = Agent(
name="ResearchAgent",
instructions="""
You are a research specialist who finds and summarizes information.
When researching topics:
1. Focus on finding accurate, current information
2. Organize findings in a logical structure
3. Identify key points and insights
4. Cite sources when available
5. Present information in a clear, concise format
"""
)
# Use the research agent
research_results = research_agent.start("Research the impact of renewable energy on reducing carbon emissions")
print(research_results)
```
## Adding Web Search Capability
To make our research agent more powerful, let's add web search capability:
```python
from praisonaiagents import Agent, Tool
# Define a web search function (simulated for this example)
def web_search(query):
"""
Simulated web search function.
In a real application, this would connect to a search API.
Args:
query (str): The search query
Returns:
str: Search results
"""
# This is just a simulation - in a real application, you'd call a search API
if "renewable energy" in query.lower():
return """
Search results for 'renewable energy carbon emissions':
1. According to the IEA, renewable energy prevented 2.1 billion tonnes of CO2 emissions in 2022.
2. Solar and wind power generate electricity with 95-98% lower carbon emissions than coal-based electricity.
3. The IPCC reports that renewable energy could deliver more than half of the emission reductions needed by 2030.
"""
else:
return f"Search results for '{query}' (simulated data)"
# Create the web search tool
search_tool = Tool(
name="web_search",
function=web_search,
description="Search the web for current information on a topic"
)
# Create a research agent with web search capability
enhanced_research_agent = Agent(
name="EnhancedResearchAgent",
instructions="""
You are a research specialist who finds and summarizes information.
When researching topics:
1. Use the web_search tool to find current information
2. Analyze and synthesize the search results
3. Organize findings in a logical structure
4. Identify key points and insights
5. Present information in a clear, concise format
""",
tools=[search_tool]
)
# Use the enhanced research agent
enhanced_results = enhanced_research_agent.start("What is the impact of renewable energy on carbon emissions?")
print(enhanced_results)
```
## Research Agent with Structured Output
For more organized research results, we can instruct the agent to provide structured output:
```python
structured_research_agent = Agent(
name="StructuredResearchAgent",
instructions="""
You are a research specialist who finds and organizes information.
When researching topics:
1. Use available tools to find current information
2. Analyze and synthesize the findings
Always structure your response in this format:
## Summary
[Brief 2-3 sentence overview of the topic]
## Key Facts
- [Important fact 1]
- [Important fact 2]
- [Important fact 3]
## Analysis
[Deeper analysis of the information, including implications]
## Sources
[List of sources if available]
""",
tools=[search_tool]
)
# Use the structured research agent
structured_results = structured_research_agent.start("Research the latest advancements in quantum computing")
print(structured_results)
```
## Specialized Research Agents
Different research tasks require different approaches. Here are some specialized research agents:
### Comparison Research Agent
```python
comparison_agent = Agent(
name="ComparisonAgent",
instructions="""
You are a research specialist who compares different options or topics.
When comparing items:
1. Identify the key criteria for comparison
2. Research each option thoroughly
3. Create a clear side-by-side comparison
4. Highlight advantages and disadvantages of each option
5. Provide a balanced conclusion
Present your findings in a structured table format when appropriate.
""",
tools=[search_tool]
)
# Use the comparison agent
comparison_results = comparison_agent.start("Compare solar and wind energy for residential use")
print(comparison_results)
```
### Literature Review Agent
```python
literature_agent = Agent(
name="LiteratureAgent",
instructions="""
You are a research specialist who reviews academic and professional literature.
When reviewing literature:
1. Identify key papers, articles, and studies on the topic
2. Summarize the main findings and methodologies
3. Identify trends, agreements, and contradictions
4. Evaluate the strength of evidence
5. Highlight gaps in current research
Structure your review in a clear, academic format.
""",
tools=[search_tool]
)
# Use the literature review agent
literature_results = literature_agent.start("Review recent research on artificial intelligence in healthcare")
print(literature_results)
```
## Research Process Best Practices
<CardGroup cols={2}>
<Card title="Define Scope" icon="bullseye">
Set clear boundaries for the research
</Card>
<Card title="Verify Information" icon="check-double">
Cross-check facts from multiple sources
</Card>
<Card title="Consider Bias" icon="scale-balanced">
Be aware of potential biases in sources
</Card>
<Card title="Prioritize Relevance" icon="filter">
Focus on information most relevant to the query
</Card>
</CardGroup>
In the next lesson, we'll explore how to build agents that can assist with creative tasks like content creation.
@@ -0,0 +1,252 @@
---
title: "Content Creation Agents"
description: "Building agents that generate various types of content"
icon: "pen-to-square"
---
# Content Creation Agents
Content creation agents can help generate various types of content, from blog posts to marketing materials. In this lesson, we'll learn how to build effective content creation agents.
## What is a Content Creation Agent?
A content creation agent is designed to:
- Generate written content based on specific requirements
- Structure content in appropriate formats
- Adapt tone and style to match the target audience
- Create content that achieves specific goals (inform, persuade, entertain)
## Creating a Basic Content Creation Agent
Let's start with a simple content creation agent:
```python
from praisonaiagents import Agent
# Create a basic content creation agent
content_agent = Agent(
name="ContentCreator",
instructions="""
You are a versatile content creator who specializes in writing engaging material.
When creating content:
1. Understand the purpose and target audience
2. Create a logical structure with clear sections
3. Use an engaging, appropriate writing style
4. Include a strong introduction and conclusion
5. Format content for easy readability
"""
)
# Use the content creation agent
blog_post = content_agent.start(
"""
Create a blog post about the benefits of meditation.
Target audience: Busy professionals
Length: Approximately 500 words
Tone: Informative but conversational
"""
)
print(blog_post)
```
## Specialized Content Creation Agents
Different types of content require different approaches. Let's create specialized agents for various content needs:
### Blog Post Agent
```python
blog_agent = Agent(
name="BlogWriter",
instructions="""
You are a blog post writer who creates engaging, informative articles.
When writing blog posts:
1. Create attention-grabbing headlines
2. Start with a compelling introduction
3. Use subheadings to organize content
4. Include relevant examples and evidence
5. Incorporate a clear call-to-action at the end
Format your content with proper Markdown formatting including:
- Headings (## for main sections, ### for subsections)
- Bullet points for lists
- *Italic* for emphasis
- **Bold** for important points
- > Blockquotes for notable quotes
"""
)
# Use the blog agent
blog_content = blog_agent.start(
"""
Topic: 5 Ways to Improve Your Productivity
Target audience: Remote workers
Style: Practical, actionable advice
Length: 800 words
Include: Tips, examples, and research-backed information
"""
)
print(blog_content)
```
### Social Media Content Agent
```python
social_media_agent = Agent(
name="SocialMediaCreator",
instructions="""
You are a social media content creator who crafts engaging posts.
When creating social media content:
1. Create attention-grabbing, concise content
2. Adapt to the specific platform requirements
3. Include relevant hashtags when appropriate
4. Craft content that encourages engagement
5. Consider visual elements that would pair well with the text
For each platform, follow these guidelines:
- Twitter/X: 280 characters max, punchy, relevant hashtags
- LinkedIn: Professional tone, industry insights, 1-3 paragraphs
- Instagram: Visual-focused descriptions, emoji-friendly, hashtags
- Facebook: Conversational, can be longer, question-based engagement
"""
)
# Use the social media agent
social_content = social_media_agent.start(
"""
Create posts for Twitter, LinkedIn, and Facebook announcing:
Event: Free Webinar on "Future of AI in Business"
Date: March 15, 2025
Time: 2:00 PM EST
Registration link: example.com/webinar
Key speakers: Dr. Jane Smith, AI Ethics Expert & Tom Johnson, Business AI Implementation Specialist
"""
)
print(social_content)
```
### Email Campaign Agent
```python
email_agent = Agent(
name="EmailWriter",
instructions="""
You are an email marketing specialist who creates effective email campaigns.
When writing marketing emails:
1. Create compelling subject lines that increase open rates
2. Write engaging opening lines that hook the reader
3. Keep content concise and focused on a single main message
4. Include clear calls-to-action
5. Use a tone appropriate for the brand and audience
Structure your emails with:
- Subject line
- Greeting
- Opening hook
- Main content (2-3 paragraphs maximum)
- Call-to-action
- Sign-off
"""
)
# Use the email agent
email_content = email_agent.start(
"""
Create a promotional email for:
Product: Premium Fitness Subscription
Key benefit: Personalized workout plans and nutrition advice
Special offer: 30% off first 3 months
Target audience: Health-conscious professionals aged 25-45
CTA: Sign up for the discounted offer
Tone: Motivational but not aggressive
"""
)
print(email_content)
```
## Content Creation with Templates
Templates can help create more consistent content. Let's build an agent that works with templates:
```python
template_agent = Agent(
name="TemplateWriter",
instructions="""
You are a content creator who works with templates to create consistent content.
When filling a template:
1. Maintain the overall structure of the template
2. Replace placeholder text with appropriate content
3. Ensure consistency in tone and style
4. Adapt content to the specific requirements
5. Review for coherence and flow
Always preserve formatting elements like headings, lists, and emphasis.
"""
)
# Example template
product_review_template = """
# {Product Name} Review: {Brief Opinion}
## Quick Summary
**Rating:** {Rating}/10
**Price:** {Price Range}
**Recommended For:** {Target User}
## What We Liked
- {Positive Point 1}
- {Positive Point 2}
- {Positive Point 3}
## What Could Be Better
- {Negative Point 1}
- {Negative Point 2}
## Bottom Line
{Conclusion Paragraph}
"""
# Use the template agent
filled_template = template_agent.start(
f"""
Fill the following template for a product review:
{product_review_template}
Product: Wireless Noise-Cancelling Headphones XZ200
Key features: 30-hour battery life, active noise cancellation, voice assistant integration
Price: $249.99
Target audience: Commuters and office workers
Notable pros: Sound quality, comfort, battery life
Notable cons: Price, occasional Bluetooth connectivity issues
"""
)
print(filled_template)
```
## Content Creation Best Practices
<CardGroup cols={2}>
<Card title="Know Your Audience" icon="users">
Understand who will consume the content
</Card>
<Card title="Clear Purpose" icon="bullseye">
Define what the content should achieve
</Card>
<Card title="Consistent Voice" icon="comment">
Maintain a consistent tone and style
</Card>
<Card title="Readability" icon="eye">
Make content easy to scan and understand
</Card>
</CardGroup>
In the next lesson, we'll explore how to build AI agents that can analyze and work with data.
@@ -0,0 +1,333 @@
---
title: "Data Analysis Agents"
description: "Creating agents that analyze and interpret data"
icon: "chart-line"
---
# Data Analysis Agents
Data analysis agents can help process, analyze, and extract insights from data. In this lesson, we'll learn how to build agents that can work with data effectively.
## What is a Data Analysis Agent?
A data analysis agent is designed to:
- Process and interpret data
- Identify patterns and trends
- Generate insights and recommendations
- Present findings in an understandable format
## Creating a Basic Data Analysis Agent
Let's start by building a simple data analysis agent:
```python
from praisonaiagents import Agent
# Create a basic data analysis agent
data_analysis_agent = Agent(
name="DataAnalyst",
instructions="""
You are a data analysis specialist who interprets and explains data.
When analyzing data:
1. First understand what the data represents
2. Identify key patterns, trends, or anomalies
3. Generate meaningful insights
4. Explain findings in simple, clear language
5. Provide actionable recommendations when appropriate
"""
)
# Use the data analysis agent with sample data
sample_data = """
Monthly Sales Data (2024):
January: $12,500
February: $13,200
March: $15,800
April: $14,300
May: $16,700
June: $18,900
"""
analysis = data_analysis_agent.start(
f"""
Analyze the following sales data and provide insights:
{sample_data}
Questions to answer:
1. What is the overall sales trend?
2. Which month had the highest sales?
3. What is the average monthly sales?
4. What recommendations would you make based on this data?
"""
)
print(analysis)
```
## Adding Data Processing Tools
Let's enhance our agent with basic data processing capabilities:
```python
from praisonaiagents import Agent, Tool
# Define a simple calculation tool
def calculate_statistics(data_string):
"""
Calculate basic statistics from a string of numbers.
Args:
data_string (str): A string with numbers separated by commas
Returns:
str: Statistical summary
"""
try:
# Convert string to list of numbers
data = [float(x.strip()) for x in data_string.split(',')]
# Calculate statistics
total = sum(data)
average = total / len(data)
minimum = min(data)
maximum = max(data)
return f"""
Statistical summary:
- Count: {len(data)}
- Sum: {total}
- Average: {average:.2f}
- Minimum: {minimum}
- Maximum: {maximum}
- Range: {maximum - minimum}
"""
except Exception as e:
return f"Error processing data: {str(e)}"
# Create the tool
stats_tool = Tool(
name="calculate_statistics",
function=calculate_statistics,
description="Calculate basic statistics from a list of numbers (comma-separated)"
)
# Create an agent with the statistics tool
enhanced_data_agent = Agent(
name="EnhancedDataAnalyst",
instructions="""
You are a data analysis specialist who interprets and explains data.
When analyzing data:
1. First understand what the data represents
2. Use the calculate_statistics tool for numerical data
3. Identify key patterns, trends, or anomalies
4. Generate meaningful insights
5. Explain findings in simple, clear language
6. Provide actionable recommendations when appropriate
""",
tools=[stats_tool]
)
# Use the enhanced data agent
numerical_data = "12500, 13200, 15800, 14300, 16700, 18900"
enhanced_analysis = enhanced_data_agent.start(
f"""
Analyze the following monthly sales data for the first half of 2024:
{numerical_data}
Provide a complete analysis with trends and recommendations.
"""
)
print(enhanced_analysis)
```
## Specialized Data Analysis Agents
Different analysis tasks require specialized approaches. Let's create some specialized agents:
### Market Trend Analysis Agent
```python
market_analysis_agent = Agent(
name="MarketAnalyst",
instructions="""
You are a market trend analyst who specializes in identifying patterns and making predictions.
When analyzing market data:
1. Identify long-term trends and short-term patterns
2. Compare data points to industry benchmarks
3. Identify potential causes for changes
4. Assess future implications
5. Provide strategic recommendations
Present your analysis with clear sections for:
- Overall Market Assessment
- Key Trends Identified
- Growth Opportunities
- Risk Factors
- Strategic Recommendations
""",
tools=[stats_tool]
)
# Use the market analysis agent
market_data = """
Industry Growth Rates (2021-2024):
2021: 3.2%
2022: 2.8%
2023: 4.5%
2024: 5.1%
Our Company Growth:
2021: 2.9%
2022: 3.1%
2023: 4.8%
2024: 6.3%
Competitor A Growth:
2021: 3.5%
2022: 3.7%
2023: 4.2%
2024: 4.5%
Competitor B Growth:
2021: 3.0%
2022: 2.5%
2023: 5.0%
2024: 5.8%
"""
market_analysis = market_analysis_agent.start(
f"""
Analyze the following market and company growth data:
{market_data}
Provide a comprehensive market analysis and strategic recommendations.
"""
)
print(market_analysis)
```
### Customer Data Analysis Agent
```python
customer_analysis_agent = Agent(
name="CustomerAnalyst",
instructions="""
You are a customer data analyst who specializes in understanding customer behavior.
When analyzing customer data:
1. Identify customer segments and patterns
2. Analyze purchasing behavior
3. Evaluate customer satisfaction metrics
4. Identify opportunities to improve customer experience
5. Recommend strategies for customer retention and growth
Present your analysis with sections for:
- Customer Segmentation
- Behavior Patterns
- Key Insights
- Recommended Actions
""",
tools=[stats_tool]
)
# Use the customer analysis agent
customer_data = """
Customer Segments by Age:
18-24: 15% of customers (Avg. Purchase: $45)
25-34: 32% of customers (Avg. Purchase: $78)
35-44: 28% of customers (Avg. Purchase: $92)
45-54: 18% of customers (Avg. Purchase: $85)
55+: 7% of customers (Avg. Purchase: $65)
Customer Satisfaction:
Very Satisfied: 42%
Satisfied: 35%
Neutral: 15%
Dissatisfied: 6%
Very Dissatisfied: 2%
Repeat Purchase Rate:
One-time: 40%
2-5 purchases: 35%
6-10 purchases: 15%
10+ purchases: 10%
"""
customer_analysis = customer_analysis_agent.start(
f"""
Analyze the following customer data:
{customer_data}
Provide insights on customer segments, behavior patterns, and recommendations to improve customer retention.
"""
)
print(customer_analysis)
```
## Data Visualization Recommendations
While our agents can't directly create visualizations, they can recommend appropriate visualization types:
```python
visualization_agent = Agent(
name="VisualizationAdvisor",
instructions="""
You are a data visualization specialist who helps select the best ways to visually represent data.
When recommending visualizations:
1. Understand the nature of the data (categorical, numerical, time-series, etc.)
2. Consider the key relationships or patterns to highlight
3. Recommend the most appropriate chart or graph type
4. Explain why your recommendation is effective
5. Provide suggestions for layout, color scheme, and labeling
Common visualization types to consider:
- Line charts (for trends over time)
- Bar charts (for comparing categories)
- Pie charts (for showing composition, use sparingly)
- Scatter plots (for showing relationships between variables)
- Heatmaps (for showing patterns in complex data)
- Box plots (for showing distributions)
"""
)
# Use the visualization agent
viz_recommendations = visualization_agent.start(
"""
I have the following data and need visualization recommendations:
1. Monthly sales data for the past year
2. Customer satisfaction ratings across 5 product categories
3. Market share compared to 3 competitors
4. Customer age distribution
What visualizations would you recommend for each of these datasets and why?
"""
)
print(viz_recommendations)
```
## Data Analysis Best Practices
<CardGroup cols={2}>
<Card title="Data Quality" icon="shield-check">
Ensure data is accurate and complete
</Card>
<Card title="Context Matters" icon="circle-info">
Consider external factors affecting data
</Card>
<Card title="Clear Communication" icon="comments">
Present findings in understandable terms
</Card>
<Card title="Actionable Insights" icon="bolt">
Focus on insights that lead to action
</Card>
</CardGroup>
In the next lesson, we'll explore how to build AI agents that can assist with customer support tasks.
@@ -0,0 +1,260 @@
---
title: "Customer Support Agents"
description: "Building agents that handle customer inquiries and issues"
icon: "headset"
---
# Customer Support Agents
Customer support agents can handle inquiries, resolve issues, and provide assistance to users. In this lesson, we'll learn how to build effective customer support agents.
## What is a Customer Support Agent?
A customer support agent is designed to:
- Answer frequently asked questions
- Troubleshoot common problems
- Provide information about products or services
- Collect information for support tickets
- Guide users through processes or procedures
## Creating a Basic Customer Support Agent
Let's start by building a simple customer support agent:
```python
from praisonaiagents import Agent
# Create a basic customer support agent
support_agent = Agent(
name="SupportAgent",
instructions="""
You are a helpful customer support representative for a software company.
When helping customers:
1. Greet them professionally and warmly
2. Understand their issue completely before attempting to solve it
3. Provide clear, step-by-step solutions when possible
4. Maintain a friendly, patient tone throughout
5. If you cannot solve the issue, explain how to escalate it
Our software product is a productivity app with features for:
- Task management
- Calendar scheduling
- Note-taking
- Team collaboration
"""
)
# Use the support agent
response = support_agent.start("I'm having trouble syncing my calendar with my phone. Can you help?")
print(response)
```
## Adding a Knowledge Base
Let's enhance our agent with a simple knowledge base to answer common questions:
```python
from praisonaiagents import Agent, KnowledgeBase
# Create a simple knowledge base
faq_kb = KnowledgeBase()
# Add FAQ content (in a real scenario, you would load this from files)
faq_kb.add_text("""
# Frequently Asked Questions
## Account Issues
### How do I reset my password?
To reset your password:
1. Go to the login page
2. Click on "Forgot Password"
3. Enter your email address
4. Follow the instructions sent to your email
### How do I change my email address?
To change your email address:
1. Log in to your account
2. Go to Settings > Account
3. Click on "Change Email"
4. Enter your new email and confirm with your password
## Subscription and Billing
### What subscription plans do you offer?
We offer three plans:
- Basic: $9.99/month - Includes core features for individuals
- Pro: $19.99/month - Includes advanced features and team capabilities for up to 5 users
- Enterprise: Custom pricing - Full feature set with advanced security and support
### How do I cancel my subscription?
To cancel your subscription:
1. Log in to your account
2. Go to Settings > Billing
3. Click "Cancel Subscription"
4. Follow the confirmation steps
## Technical Issues
### Why isn't my calendar syncing?
Common reasons for calendar sync issues:
1. Outdated app version - Try updating the app
2. Account permission issues - Check sync permissions in Settings > Integrations
3. Internet connectivity problems - Ensure you have a stable connection
### How do I export my data?
To export your data:
1. Go to Settings > Data
2. Click "Export Data"
3. Choose the data types you want to export
4. Select your preferred format (CSV or JSON)
5. Click "Export" and save the file
""")
# Create an agent with the knowledge base
kb_support_agent = Agent(
name="KnowledgeBaseAgent",
instructions="""
You are a helpful customer support representative with access to our FAQ knowledge base.
When helping customers:
1. Greet them professionally and warmly
2. Search the knowledge base for relevant information
3. Provide clear, accurate answers based on the knowledge base
4. If the knowledge base doesn't cover the question, provide general helpful guidance
5. Maintain a friendly, supportive tone throughout
""",
knowledge_base=faq_kb
)
# Use the knowledge base support agent
kb_response = kb_support_agent.start("How do I cancel my subscription?")
print(kb_response)
```
## Creating a Troubleshooting Agent
Let's create an agent specialized in technical troubleshooting:
```python
troubleshooting_agent = Agent(
name="TroubleshootingAgent",
instructions="""
You are a technical support specialist who helps users troubleshoot problems.
When troubleshooting:
1. Ask clarifying questions to understand the exact issue
2. Identify the most likely causes of the problem
3. Provide step-by-step solutions, starting with the simplest fixes
4. Explain what each step does and why it might help
5. Confirm if the issue is resolved or suggest next steps
Common troubleshooting areas:
- Login and account access issues
- App installation and updates
- Feature functionality problems
- Data synchronization
- Performance issues
"""
)
# Use the troubleshooting agent
troubleshooting_response = troubleshooting_agent.start("The app keeps crashing when I try to open it on my iPhone")
print(troubleshooting_response)
```
## Building a Conversational Support Agent
Let's create a support agent that can handle multi-turn conversations:
```python
conversational_support = Agent(
name="ConversationalSupport",
instructions="""
You are a customer support representative who handles support conversations.
When handling support conversations:
1. Maintain context throughout the conversation
2. Ask follow-up questions when needed
3. Verify understanding before providing solutions
4. Be patient with users who may be frustrated
5. Summarize the conversation and next steps at the end
Our product is a mobile banking app with features for:
- Account balance checking
- Money transfers
- Bill payments
- Mobile check deposits
- Budget tracking
"""
)
# Start a support conversation
initial_response = conversational_support.start("I can't find where to deposit checks in the app")
print("Initial Response:", initial_response)
# Continue the conversation
follow_up_response = conversational_support.continue("I'm using version 2.5 of the app on Android")
print("Follow-up Response:", follow_up_response)
# Further continuation
resolution_response = conversational_support.continue("I found the deposit button now, but it's giving me an error when I try to take a photo")
print("Resolution Response:", resolution_response)
```
## Support Ticket Creation Agent
Let's create an agent that can gather information for support tickets:
```python
ticket_agent = Agent(
name="TicketCreationAgent",
instructions="""
You are a support ticket creation specialist who gathers the necessary information to create support tickets.
When creating a ticket:
1. Collect the customer's name and contact information
2. Identify the category of the issue
3. Gather a detailed description of the problem
4. Determine the severity level
5. Collect relevant technical details (device, software version, etc.)
6. Organize all information in a structured ticket format
Present the final ticket in a clearly formatted structure.
"""
)
# Use the ticket creation agent
ticket = ticket_agent.start(
"""
Create a support ticket for the following issue:
Customer: Jane Smith
Email: [email protected]
Issue: Cannot access premium features after payment
Details: Completed payment yesterday, received confirmation email, but premium features are still locked in the app
Using: iPhone 13, app version 3.2.1
"""
)
print(ticket)
```
## Customer Support Best Practices
<CardGroup cols={2}>
<Card title="Empathy First" icon="heart">
Show understanding before offering solutions
</Card>
<Card title="Clear Communication" icon="comment">
Use simple language, avoid jargon
</Card>
<Card title="Consistent Responses" icon="equals">
Provide consistent answers to similar questions
</Card>
<Card title="Know Escalation Paths" icon="arrow-up-right">
Have clear processes for escalating complex issues
</Card>
</CardGroup>
In the next lesson, we'll explore how to build AI agents that can assist with personal productivity tasks.
@@ -0,0 +1,270 @@
---
title: "Personal Assistant Agents"
description: "Building agents that help with personal tasks and productivity"
icon: "calendar-check"
---
# Personal Assistant Agents
Personal assistant agents can help users manage tasks, organize information, and increase productivity. In this lesson, we'll learn how to build effective personal assistant agents.
## What is a Personal Assistant Agent?
A personal assistant agent is designed to:
- Manage tasks and reminders
- Organize information
- Answer questions
- Provide recommendations
- Help with personal productivity
## Creating a Basic Personal Assistant Agent
Let's start by building a simple personal assistant agent:
```python
from praisonaiagents import Agent
# Create a basic personal assistant agent
assistant_agent = Agent(
name="PersonalAssistant",
instructions="""
You are a helpful personal assistant who helps users manage tasks and information.
When assisting users:
1. Be concise and efficient in your responses
2. Prioritize user requests based on importance and urgency
3. Maintain a helpful, friendly tone
4. Remember important information the user shares
5. Proactively suggest relevant information when appropriate
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the personal assistant agent
response = assistant_agent.start("I need to plan a meeting with my team next Tuesday at 2 PM")
print(response)
```
## Task Management Assistant
Let's create an agent specialized in task management:
```python
task_agent = Agent(
name="TaskManager",
instructions="""
You are a task management assistant who helps users organize and prioritize tasks.
When managing tasks:
1. Help identify and clarify tasks
2. Assist with prioritization
3. Break down complex tasks into manageable steps
4. Track deadlines and progress
5. Provide reminders and follow-ups
For each task, collect:
- Task description
- Priority (High, Medium, Low)
- Deadline (if applicable)
- Dependencies (other tasks that must be completed first)
- Estimated time required
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the task management agent
task_response = task_agent.start(
"""
I need help organizing these tasks for the week:
- Prepare quarterly report (due Friday)
- Meet with client about new project (Wednesday, 2 PM)
- Review team's project proposals
- Finish budget planning for next quarter
- Send feedback on marketing materials
"""
)
print(task_response)
```
## Information Organization Assistant
Let's create an agent that helps organize information:
```python
info_agent = Agent(
name="InformationOrganizer",
instructions="""
You are an information organization assistant who helps users structure and categorize information.
When organizing information:
1. Identify the main categories and topics
2. Create logical groupings
3. Suggest clear labels and headers
4. Establish relationships between different pieces of information
5. Present information in a structured, easily navigable format
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the information organization agent
info_response = info_agent.start(
"""
Help me organize my research notes on climate change:
- Rising sea levels affecting coastal cities
- Carbon dioxide levels increasing annually
- Renewable energy adoption statistics by country
- Impact of deforestation on carbon sequestration
- Climate policy differences between EU and US
- Economic impacts of extreme weather events
- Public opinion polls on climate action
- Arctic ice sheet measurements over 50 years
- Agricultural adaptations to changing climate
"""
)
print(info_response)
```
## Daily Planning Assistant
Let's create an agent that helps with daily planning:
```python
planning_agent = Agent(
name="DailyPlanner",
instructions="""
You are a daily planning assistant who helps users organize their day efficiently.
When helping with daily planning:
1. Prioritize tasks based on importance and deadlines
2. Consider time constraints and commitments
3. Suggest efficient scheduling
4. Allow for breaks and transitions
5. Balance work tasks with personal needs
Create a structured daily plan with time blocks and priorities.
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the daily planning agent
planning_response = planning_agent.start(
"""
Help me plan my day tomorrow. I have:
- A team meeting from 9:30-10:30 AM
- A report due by end of day
- Emails to catch up on (about 1 hour's worth)
- Lunch with a colleague at 12:30 PM
- A dentist appointment at 3:00 PM (will take about 1 hour including travel)
- Need to prepare a presentation for Friday
I typically work from 8:30 AM to 5:30 PM and prefer to have short breaks between tasks.
"""
)
print(planning_response)
```
## Decision Support Assistant
Let's create an agent that helps with decision-making:
```python
decision_agent = Agent(
name="DecisionSupport",
instructions="""
You are a decision support assistant who helps users make informed choices.
When supporting decisions:
1. Help clarify the decision to be made
2. Identify relevant criteria and factors
3. Present pros and cons for each option
4. Ask questions to understand preferences and priorities
5. Provide a structured analysis without making the final decision
Present options with balanced information to help the user make their own informed choice.
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the decision support agent
decision_response = decision_agent.start(
"""
I'm trying to decide whether to buy a new laptop now or wait 3 months.
Current situation:
- My current laptop is 4 years old and running slow
- It still works but has battery issues
- I use it daily for work (programming and video calls)
- I've heard new models are coming out in 3 months
- My budget is around $1,500
What should I consider in making this decision?
"""
)
print(decision_response)
```
## Recommendation Assistant
Let's create an agent that provides personalized recommendations:
```python
recommendation_agent = Agent(
name="RecommendationAssistant",
instructions="""
You are a recommendation assistant who provides personalized suggestions.
When making recommendations:
1. Understand the user's preferences and requirements
2. Consider constraints (budget, time, location, etc.)
3. Provide diverse options that match the criteria
4. Explain why each recommendation might be suitable
5. Give enough detail for the user to evaluate options
For each recommendation, include:
- A brief description
- Key features or highlights
- Why it matches the user's needs
""",
llm="gpt-4o-mini" # Using the specified model
)
# Use the recommendation agent
recommendation_response = recommendation_agent.start(
"""
Can you recommend some books for me? I enjoy:
- Science fiction and fantasy
- Books with complex, morally gray characters
- Intricate world-building
- Books that explore philosophical themes
I've recently read and enjoyed:
- "The Fifth Season" by N.K. Jemisin
- "Dune" by Frank Herbert
- "The Lies of Locke Lamora" by Scott Lynch
"""
)
print(recommendation_response)
```
## Personal Assistant Best Practices
<CardGroup cols={2}>
<Card title="Respect Privacy" icon="lock">
Be careful with personal information
</Card>
<Card title="Customize Interactions" icon="sliders">
Adapt to the user's preferences
</Card>
<Card title="Clear Communication" icon="comment">
Keep responses direct and easy to understand
</Card>
<Card title="Contextual Awareness" icon="puzzle-piece">
Remember relevant context from previous interactions
</Card>
</CardGroup>
In the next lesson, we'll explore how to deploy and share your AI agents with others.
+342
View File
@@ -0,0 +1,342 @@
---
title: "Deploying Agents"
description: "How to deploy and share your AI agents with others"
icon: "rocket"
---
# Deploying Agents
After creating your AI agents, the next step is deploying them for use by yourself or others. In this final lesson, we'll explore different deployment options and best practices.
## Deployment Options
There are several ways to deploy your AI agents:
### 1. Local Deployment
Running your agents locally is the simplest approach:
```python
from praisonaiagents import Agent
def run_local_agent():
agent = Agent(
name="SimpleAgent",
instructions="You are a helpful assistant that answers questions concisely.",
llm="gpt-4o-mini" # Using the specified model
)
while True:
user_input = input("Ask a question (type 'exit' to quit): ")
if user_input.lower() == 'exit':
break
response = agent.start(user_input)
print("\nAgent response:")
print(response)
print("\n" + "-"*50 + "\n")
if __name__ == "__main__":
run_local_agent()
```
### 2. Web Application Deployment
You can deploy your agents as part of a web application:
```python
from flask import Flask, request, jsonify
from praisonaiagents import Agent
import os
app = Flask(__name__)
# Create agent once at startup
support_agent = Agent(
name="SupportAgent",
instructions="You are a customer support agent that helps users with product questions.",
llm="gpt-4o-mini" # Using the specified model
)
@app.route('/api/support', methods=['POST'])
def get_support():
data = request.json
user_query = data.get('query', '')
if not user_query:
return jsonify({"error": "No query provided"}), 400
try:
response = support_agent.start(user_query)
return jsonify({"response": response})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
app.run(debug=True, port=5000)
```
### 3. Serverless Function Deployment
For scalable, event-driven deployments, serverless functions work well:
```python
# Example AWS Lambda function
import json
from praisonaiagents import Agent
# Initialize agent outside the handler for reuse across invocations
agent = Agent(
name="ServerlessAgent",
instructions="You provide concise, helpful responses to user questions.",
llm="gpt-4o-mini" # Using the specified model
)
def lambda_handler(event, context):
try:
# Get the user query from the event
body = json.loads(event.get('body', '{}'))
user_query = body.get('query', '')
if not user_query:
return {
'statusCode': 400,
'body': json.dumps({'error': 'No query provided'})
}
# Process with the agent
response = agent.start(user_query)
return {
'statusCode': 200,
'body': json.dumps({'response': response})
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({'error': str(e)})
}
```
## Environment Variables and Security
When deploying agents, it's crucial to handle API keys and secrets securely:
```python
import os
from dotenv import load_dotenv
from praisonaiagents import Agent
# Load environment variables from .env file
load_dotenv()
# Access API key from environment variable
api_key = os.getenv("OPENAI_API_KEY")
# Create agent with API key
agent = Agent(
name="SecureAgent",
instructions="You are a helpful assistant.",
llm="gpt-4o-mini", # Using the specified model
api_key=api_key # Pass API key securely
)
```
## Creating a Simple Chat Interface
Here's a simple command-line chat interface for your agent:
```python
import os
from praisonaiagents import Agent
def create_chat_interface():
# Initialize agent
agent = Agent(
name="ChatAgent",
instructions="""
You are a conversational assistant that maintains context throughout the conversation.
Respond in a helpful, concise manner.
""",
llm="gpt-4o-mini" # Using the specified model
)
print("Chat with AI Assistant (type 'exit' to quit)")
print("-" * 50)
# Start conversation
conversation_active = True
first_message = True
while conversation_active:
# Get user input
user_message = input("You: ")
# Check if user wants to exit
if user_message.lower() == 'exit':
print("Goodbye!")
conversation_active = False
continue
# Get agent response
try:
if first_message:
response = agent.start(user_message)
first_message = False
else:
response = agent.continue(user_message)
print("\nAssistant:", response)
print("\n" + "-" * 50)
except Exception as e:
print(f"Error: {str(e)}")
if __name__ == "__main__":
create_chat_interface()
```
## Scaling Considerations
As you deploy agents for wider use, consider these scaling factors:
<CardGroup cols={2}>
<Card title="Rate Limiting" icon="gauge-high">
Implement rate limiting to manage API usage and costs
</Card>
<Card title="Caching" icon="database">
Cache common responses to improve performance and reduce API calls
</Card>
<Card title="Error Handling" icon="triangle-exclamation">
Implement robust error handling for API failures
</Card>
<Card title="Monitoring" icon="chart-line">
Set up monitoring for usage patterns and performance issues
</Card>
</CardGroup>
## Best Practices for Deployment
### 1. Testing Before Deployment
Always test your agents thoroughly before deployment:
```python
def test_agent_functionality():
"""Test basic agent functionality with various inputs"""
agent = Agent(
name="TestAgent",
instructions="You are a helpful assistant for testing.",
llm="gpt-4o-mini" # Using the specified model
)
test_cases = [
"What is artificial intelligence?",
"How do I reset my password?",
"Tell me about machine learning"
]
for test_case in test_cases:
print(f"\nTesting: {test_case}")
response = agent.start(test_case)
print(f"Response: {response[:100]}...") # Print first 100 chars
# Add assertions or validation logic here
assert len(response) > 0, "Response should not be empty"
```
### 2. Documentation
Create clear documentation for users of your agent:
```python
"""
# Customer Support Agent API
This API provides access to an AI customer support agent
that can answer questions about our products.
## Authentication
Include your API key in the request header:
```
Authorization: Bearer YOUR_API_KEY
```
## Endpoints
POST /api/support
- Request body: {"query": "Your question here"}
- Response: {"response": "Agent's answer"}
## Example
```python
import requests
response = requests.post(
"https://api.example.com/api/support",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={"query": "How do I reset my password?"}
)
print(response.json())
```
"""
```
### 3. Version Control
Implement version control for your agents to track changes:
```python
class VersionedAgent:
def __init__(self, name, version, instructions):
self.name = name
self.version = version
self.agent = Agent(
name=f"{name}_v{version}",
instructions=instructions,
llm="gpt-4o-mini" # Using the specified model
)
def get_response(self, query):
response = self.agent.start(query)
return {
"agent_name": self.name,
"version": self.version,
"response": response,
"timestamp": datetime.now().isoformat()
}
```
## Conclusion
Congratulations on completing the AI Agents Course! You've learned how to:
1. Understand different types of AI agents and their architectures
2. Create effective agent instructions and tools
3. Implement memory and context for your agents
4. Build specialized agents for various tasks
5. Create multi-agent systems
6. Deploy your agents for real-world use
As AI agent technology continues to evolve, keep experimenting with new capabilities and use cases. Remember that the best agents are those that effectively solve real problems for users while being trustworthy, reliable, and helpful.
We hope this course has provided you with the knowledge and skills to build powerful AI agents that enhance productivity and creativity!
## Next Steps
<CardGroup cols={2}>
<Card title="Join the Community" icon="users">
Participate in discussions and share your agent projects
</Card>
<Card title="Stay Updated" icon="newspaper">
Follow updates in AI agent technology and new features
</Card>
<Card title="Share Your Feedback" icon="comment">
Let us know how you're using agents and what you'd like to learn next
</Card>
<Card title="Build Real Solutions" icon="lightbulb">
Apply your knowledge to build solutions for real-world problems
</Card>
</CardGroup>
Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

+416
View File
@@ -0,0 +1,416 @@
---
title: "Deploying to AWS"
sidebarTitle: "AWS"
description: "Deploy PraisonAI agents to Amazon Web Services for scalable production environments"
icon: "aws"
---
# Deploying PraisonAI Agents to AWS
This guide provides step-by-step instructions for deploying PraisonAI agents to Amazon Web Services (AWS), offering multiple deployment options to suit different requirements.
## Prerequisites
- AWS account with appropriate permissions
- AWS CLI installed and configured
- Docker installed on your local machine (for container-based deployments)
- Basic knowledge of AWS services and cloud deployment
## Deployment Options
There are several ways to deploy PraisonAI agents to AWS:
1. **AWS Lambda with API Gateway** (for serverless deployments)
2. **Amazon ECS/Fargate** (for containerized deployments)
3. **Amazon EC2** (for traditional VM-based deployments)
4. **AWS App Runner** (for simplified container deployments)
## Option 1: Deploying to EC2 (Traditional VM)
<Steps>
<Step title="Launch an EC2 Instance">
1. Go to the AWS Management Console
2. Navigate to EC2 and click "Launch Instance"
3. Choose Amazon Linux 2 or Ubuntu Server
4. Select an instance type (t2.micro for testing, t2.medium or larger for production)
5. Configure security groups to allow HTTP/HTTPS traffic
6. Launch the instance and connect to it via SSH
</Step>
<Step title="Set Up the Environment">
```bash
# Update system packages
sudo apt update && sudo apt upgrade -y
# Install Python and pip
sudo apt install -y python3 python3-pip
# Install required packages
pip3 install "praisonaiagents[api]>=0.0.79"
```
</Step>
<Step title="Create the API Application">
Create a file named `api.py`:
```python
from praisonaiagents import Agent
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
agent.launch(path="/ask", port=8080, host="0.0.0.0")
```
</Step>
<Step title="Set Up a Systemd Service">
Create a systemd service file to run your application as a background service:
```bash
sudo nano /etc/systemd/system/praisonai-agent.service
```
Add the following content:
```ini
[Unit]
Description=PraisonAI Agent API Service
After=network.target
[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu
Environment="OPENAI_API_KEY=your_api_key"
ExecStart=/usr/bin/python3 /home/ubuntu/api.py
Restart=always
[Install]
WantedBy=multi-user.target
```
Enable and start the service:
```bash
sudo systemctl daemon-reload
sudo systemctl enable praisonai-agent
sudo systemctl start praisonai-agent
```
</Step>
<Step title="Set Up Nginx as a Reverse Proxy">
```bash
# Install Nginx
sudo apt install -y nginx
# Create a configuration file
sudo nano /etc/nginx/sites-available/praisonai-agent
```
Add the following configuration:
```nginx
server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Enable the site and restart Nginx:
```bash
sudo ln -s /etc/nginx/sites-available/praisonai-agent /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```
</Step>
</Steps>
## Option 2: Deploying with Docker and ECS/Fargate
<Steps>
<Step title="Create a Dockerfile">
```dockerfile
FROM python:3.11-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Run the application
CMD ["python", "api.py"]
```
Create a `requirements.txt` file:
```
praisonaiagents[api]>=0.0.79
```
Create your `api.py` file:
```python
from praisonaiagents import Agent
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
agent.launch(path="/ask", port=8080, host="0.0.0.0")
```
</Step>
<Step title="Build and Push the Docker Image to ECR">
```bash
# Create an ECR repository
aws ecr create-repository --repository-name praisonai-agent
# Get the login command
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com
# Build the Docker image
docker build -t praisonai-agent .
# Tag the image
docker tag praisonai-agent:latest YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/praisonai-agent:latest
# Push the image to ECR
docker push YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/praisonai-agent:latest
```
</Step>
<Step title="Create an ECS Cluster and Task Definition">
```bash
# Create an ECS cluster
aws ecs create-cluster --cluster-name praisonai-cluster
# Create a task definition (JSON file)
cat > task-definition.json << EOF
{
"family": "praisonai-agent",
"networkMode": "awsvpc",
"executionRoleArn": "arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "praisonai-agent",
"image": "YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/praisonai-agent:latest",
"essential": true,
"portMappings": [
{
"containerPort": 8080,
"hostPort": 8080,
"protocol": "tcp"
}
],
"environment": [
{
"name": "OPENAI_API_KEY",
"value": "your_api_key"
}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/praisonai-agent",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs"
}
}
}
],
"requiresCompatibilities": [
"FARGATE"
],
"cpu": "256",
"memory": "512"
}
EOF
# Register the task definition
aws ecs register-task-definition --cli-input-json file://task-definition.json
```
</Step>
<Step title="Create a Fargate Service">
```bash
# Create a service
aws ecs create-service \
--cluster praisonai-cluster \
--service-name praisonai-service \
--task-definition praisonai-agent:1 \
--desired-count 1 \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[subnet-12345678],securityGroups=[sg-12345678],assignPublicIp=ENABLED}" \
--load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/praisonai-tg/1234567890abcdef,containerName=praisonai-agent,containerPort=8080"
```
Note: You'll need to create an Application Load Balancer and target group before running this command.
</Step>
</Steps>
## Multi-Agent Deployment
For deploying multiple agents, you can use a single service with different endpoints:
```python
# multi-agent-api.py
from praisonaiagents import Agent
weather_agent = Agent(
instructions="""You are a weather agent that can provide weather information for a given city.""",
llm="gpt-4o-mini"
)
stock_agent = Agent(
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
llm="gpt-4o-mini"
)
travel_agent = Agent(
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
llm="gpt-4o-mini"
)
weather_agent.launch(path="/weather", port=8080, host="0.0.0.0")
stock_agent.launch(path="/stock", port=8080, host="0.0.0.0")
travel_agent.launch(path="/travel", port=8080, host="0.0.0.0")
```
## Option 3: Serverless Deployment with AWS Lambda
For lightweight agents that don't require long-running processes, you can use AWS Lambda with API Gateway:
```python
# lambda_function.py
from praisonaiagents import Agent
import json
# Initialize the agent outside the handler for better cold start performance
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
def lambda_handler(event, context):
try:
# Extract the message from the event
body = json.loads(event.get('body', '{}'))
message = body.get('message', '')
# Process the message with the agent
response = agent.process(message)
# Return the response
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'response': response
})
}
except Exception as e:
return {
'statusCode': 500,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'error': str(e)
})
}
```
## Scaling and Performance
### Auto Scaling
For EC2 deployments, set up an Auto Scaling group:
```bash
# Create a launch template
aws ec2 create-launch-template \
--launch-template-name praisonai-template \
--version-description "Initial version" \
--launch-template-data '{"ImageId":"ami-12345678","InstanceType":"t2.medium","UserData":"#!/bin/bash\ncd /home/ubuntu\npython3 api.py &"}'
# Create an Auto Scaling group
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name praisonai-asg \
--launch-template "LaunchTemplateName=praisonai-template,Version=1" \
--min-size 1 \
--max-size 5 \
--desired-capacity 2 \
--vpc-zone-identifier "subnet-12345678,subnet-87654321" \
--target-group-arns "arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/praisonai-tg/1234567890abcdef"
```
### Load Balancing
Set up an Application Load Balancer to distribute traffic:
```bash
# Create a load balancer
aws elbv2 create-load-balancer \
--name praisonai-alb \
--subnets subnet-12345678 subnet-87654321 \
--security-groups sg-12345678
# Create a target group
aws elbv2 create-target-group \
--name praisonai-tg \
--protocol HTTP \
--port 8080 \
--vpc-id vpc-12345678 \
--target-type instance
# Create a listener
aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:loadbalancer/app/praisonai-alb/1234567890abcdef \
--protocol HTTP \
--port 80 \
--default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/praisonai-tg/1234567890abcdef
```
## Security Best Practices
1. **Secret Management**: Use AWS Secrets Manager for API keys
```bash
# Store a secret
aws secretsmanager create-secret \
--name OPENAI_API_KEY \
--secret-string "your_api_key"
```
2. **IAM Roles**: Use the principle of least privilege
3. **VPC**: Deploy in a private subnet with controlled access
4. **WAF**: Set up AWS WAF to protect against common web exploits
5. **API Gateway**: Implement request validation and throttling
## Monitoring and Logging
1. **CloudWatch**: Set up dashboards and alarms
```bash
# Create a CloudWatch alarm for high CPU utilization
aws cloudwatch put-metric-alarm \
--alarm-name praisonai-high-cpu \
--alarm-description "Alarm when CPU exceeds 80%" \
--metric-name CPUUtilization \
--namespace AWS/EC2 \
--statistic Average \
--period 300 \
--threshold 80 \
--comparison-operator GreaterThanThreshold \
--dimensions Name=AutoScalingGroupName,Value=praisonai-asg \
--evaluation-periods 2 \
--alarm-actions arn:aws:sns:us-east-1:YOUR_AWS_ACCOUNT_ID:praisonai-alerts
```
2. **X-Ray**: Enable tracing for detailed request analysis
3. **CloudTrail**: Monitor API calls for security analysis
4. **Log Insights**: Query and analyze logs with CloudWatch Log Insights
+223
View File
@@ -0,0 +1,223 @@
---
title: "Deploying PraisonAI Agents as APIs"
sidebarTitle: "API Deployment"
description: "Learn how to deploy PraisonAI agents as RESTful APIs for production environments"
icon: "server"
---
PraisonAI agents can be easily deployed as RESTful APIs, allowing you to integrate them into various applications and services. This guide covers how to deploy both single and multiple agents as APIs.
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have the required packages installed:
```bash
pip install "praisonaiagents[api]"
```
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY="your_api_key"
```
</Step>
<Step title="Deploy a Simple Agent API">
Create a file named `simple-api.py` with the following code:
```python
from praisonaiagents import Agent
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
agent.launch(path="/ask", port=3030)
```
</Step>
<Step title="Run the API Server">
```bash
python simple-api.py
```
Your API will be available at `http://localhost:3030/ask`
</Step>
</Steps>
## Making API Requests
Once your agent is deployed, you can make POST requests to interact with it:
```bash
curl -X POST http://localhost:3030/ask \
-H "Content-Type: application/json" \
-d '{"message": "What is artificial intelligence?"}'
```
The response will be in JSON format:
```json
{
"response": "Artificial intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think and learn like humans. It encompasses various technologies including machine learning, natural language processing, computer vision, and robotics. AI systems can perform tasks that typically require human intelligence such as understanding natural language, recognizing patterns, solving problems, and making decisions."
}
```
## Multi-Agent API Deployment
You can deploy multiple agents on the same server, each with its own endpoint:
```python
from praisonaiagents import Agent
weather_agent = Agent(
instructions="""You are a weather agent that can provide weather information for a given city.""",
llm="gpt-4o-mini"
)
stock_agent = Agent(
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
llm="gpt-4o-mini"
)
travel_agent = Agent(
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
llm="gpt-4o-mini"
)
weather_agent.launch(path="/weather", port=3030)
stock_agent.launch(path="/stock", port=3030)
travel_agent.launch(path="/travel", port=3030)
```
With this setup, you can access:
- Weather agent at `http://localhost:3030/weather`
- Stock agent at `http://localhost:3030/stock`
- Travel agent at `http://localhost:3030/travel`
## Production Deployment Options
For production environments, consider the following deployment options:
### Docker Deployment
<Steps>
<Step title="Create a Dockerfile">
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 3030
CMD ["python", "api.py"]
```
</Step>
<Step title="Create requirements.txt">
```
praisonaiagents[api]>=0.0.79
```
</Step>
<Step title="Build and Run Docker Container">
```bash
docker build -t praisonai-api .
docker run -p 3030:3030 -e OPENAI_API_KEY=your_api_key praisonai-api
```
</Step>
</Steps>
### Cloud Deployment
#### Deploying to AWS
<Steps>
<Step title="Create an EC2 Instance">
Launch an EC2 instance with Ubuntu or Amazon Linux.
</Step>
<Step title="Install Dependencies">
```bash
sudo apt update
sudo apt install -y python3-pip
pip install "praisonaiagents[api]"
```
</Step>
<Step title="Configure Security Group">
Make sure to open port 3030 in your security group settings.
</Step>
<Step title="Run with Systemd">
Create a systemd service file for automatic startup and management.
</Step>
</Steps>
#### Deploying to Google Cloud Run
<Steps>
<Step title="Build Docker Image">
```bash
docker build -t gcr.io/your-project/praisonai-api .
```
</Step>
<Step title="Push to Container Registry">
```bash
docker push gcr.io/your-project/praisonai-api
```
</Step>
<Step title="Deploy to Cloud Run">
```bash
gcloud run deploy praisonai-api \
--image gcr.io/your-project/praisonai-api \
--platform managed \
--allow-unauthenticated \
--set-env-vars="OPENAI_API_KEY=your_api_key"
```
</Step>
</Steps>
## API Configuration Options
When launching your agent as an API, you can customize various parameters:
```python
agent.launch(
path="/custom-endpoint", # API endpoint path
port=8080, # Port number
host="0.0.0.0", # Host address (0.0.0.0 for external access)
debug=True, # Enable debug mode
cors_origins=["*"], # CORS configuration
api_key="your-api-key" # Optional API key for authentication
)
```
## Securing Your API
For production deployments, consider implementing:
1. **API Key Authentication**: Require API keys for all requests
2. **Rate Limiting**: Limit the number of requests per client
3. **HTTPS**: Use SSL/TLS certificates for encrypted communication
4. **Input Validation**: Validate all input data before processing
## Monitoring and Scaling
For production environments, consider:
1. **Load Balancing**: Distribute traffic across multiple instances
2. **Auto-Scaling**: Automatically adjust resources based on demand
3. **Logging**: Implement comprehensive logging for debugging
4. **Monitoring**: Set up alerts for errors and performance issues
## Features
<CardGroup cols={2}>
<Card title="RESTful API" icon="server">
Deploy your agents as standard RESTful APIs for easy integration.
</Card>
<Card title="Multi-Agent Support" icon="users">
Deploy multiple agents with different endpoints on the same server.
</Card>
<Card title="Customizable" icon="gear">
Configure ports, paths, CORS settings, and more.
</Card>
<Card title="Production-Ready" icon="rocket">
Easily deploy to Docker, AWS, Google Cloud, or other cloud platforms.
</Card>
</CardGroup>
+248
View File
@@ -0,0 +1,248 @@
---
title: "Deploying to Google Cloud"
sidebarTitle: "Google Cloud"
description: "Deploy PraisonAI agents to Google Cloud Platform for scalable production environments"
icon: "google"
---
# Deploying PraisonAI Agents to Google Cloud
This guide provides step-by-step instructions for deploying PraisonAI agents to Google Cloud Platform using Cloud Run, which offers a serverless environment for containerized applications.
## Prerequisites
- Google Cloud account with billing enabled
- Google Cloud SDK installed and configured
- Docker installed on your local machine
- Basic knowledge of containerization and cloud deployment
## Deployment Options
There are several ways to deploy PraisonAI agents to Google Cloud:
1. **Google Cloud Run** (recommended for most use cases)
2. **Google Compute Engine** (for custom VM requirements)
3. **Google Kubernetes Engine** (for complex, scalable deployments)
This guide focuses on Cloud Run as it's the simplest and most cost-effective option for most deployments.
## Deploying to Google Cloud Run
<Steps>
<Step title="Prepare Your Application">
Create a simple API file named `api.py`:
```python
from praisonaiagents import Agent
agent = Agent(instructions="""You are a helpful assistant.""", llm="gpt-4o-mini")
agent.launch(path="/ask", port=8080, host="0.0.0.0")
```
Note: Cloud Run expects your application to listen on the port defined by the `PORT` environment variable, which defaults to 8080.
</Step>
<Step title="Create a Dockerfile">
```dockerfile
FROM python:3.11-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Set environment variables
ENV PORT=8080
# Run the application
CMD exec python api.py
```
Create a `requirements.txt` file:
```
praisonaiagents[api]>=0.0.79
```
</Step>
<Step title="Build and Push the Docker Image">
```bash
# Build the Docker image
docker build -t gcr.io/YOUR_PROJECT_ID/praisonai-agent .
# Configure Docker to use Google Cloud credentials
gcloud auth configure-docker
# Push the image to Google Container Registry
docker push gcr.io/YOUR_PROJECT_ID/praisonai-agent
```
</Step>
<Step title="Deploy to Cloud Run">
```bash
gcloud run deploy praisonai-agent \
--image gcr.io/YOUR_PROJECT_ID/praisonai-agent \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars="OPENAI_API_KEY=your_api_key"
```
Note: For production deployments, it's recommended to use Secret Manager for API keys instead of environment variables.
</Step>
</Steps>
## Multi-Agent Deployment
For deploying multiple agents, you can use a single Cloud Run service with different endpoints:
```python
# multi-agent-api.py
from praisonaiagents import Agent
weather_agent = Agent(
instructions="""You are a weather agent that can provide weather information for a given city.""",
llm="gpt-4o-mini"
)
stock_agent = Agent(
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
llm="gpt-4o-mini"
)
travel_agent = Agent(
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
llm="gpt-4o-mini"
)
weather_agent.launch(path="/weather", port=8080, host="0.0.0.0")
stock_agent.launch(path="/stock", port=8080, host="0.0.0.0")
travel_agent.launch(path="/travel", port=8080, host="0.0.0.0")
```
## Scaling and Performance
Google Cloud Run automatically scales based on traffic, from zero to many instances. You can configure:
- **Minimum instances**: Keep a certain number of instances warm to avoid cold starts
- **Maximum instances**: Limit the number of instances to control costs
- **Memory allocation**: Allocate more memory for complex agents
- **CPU allocation**: Allocate dedicated CPUs for compute-intensive workloads
```bash
gcloud run services update praisonai-agent \
--min-instances=1 \
--max-instances=10 \
--memory=2Gi \
--cpu=1
```
## Continuous Deployment
Set up continuous deployment with Cloud Build:
```yaml
# cloudbuild.yaml
steps:
# Build the container image
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', 'gcr.io/$PROJECT_ID/praisonai-agent', '.']
# Push the container image to Container Registry
- name: 'gcr.io/cloud-builders/docker'
args: ['push', 'gcr.io/$PROJECT_ID/praisonai-agent']
# Deploy container image to Cloud Run
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
entrypoint: gcloud
args:
- 'run'
- 'deploy'
- 'praisonai-agent'
- '--image'
- 'gcr.io/$PROJECT_ID/praisonai-agent'
- '--region'
- 'us-central1'
- '--platform'
- 'managed'
- '--allow-unauthenticated'
substitutions:
_REGION: us-central1
images:
- 'gcr.io/$PROJECT_ID/praisonai-agent'
```
## Monitoring and Logging
Google Cloud provides comprehensive monitoring and logging capabilities:
- **Cloud Monitoring**: Set up dashboards and alerts for your deployed agents
- **Cloud Logging**: View and analyze logs from your applications
- **Error Reporting**: Automatically detect and group errors
Access logs through the Google Cloud Console or using the gcloud command:
```bash
gcloud logging read "resource.type=cloud_run_revision AND resource.labels.service_name=praisonai-agent" --limit=10
```
## Cost Optimization
Cloud Run charges based on the resources your service uses only when it's processing requests. To optimize costs:
1. Set appropriate memory and CPU allocations
2. Configure minimum instances based on traffic patterns
3. Use regional deployments closest to your users
4. Implement caching for frequent requests
## Security Best Practices
1. **Secret Management**: Store API keys and credentials in Secret Manager
```bash
# Create a secret
echo -n "your_api_key" | gcloud secrets create openai-api-key --data-file=-
# Grant access to the Cloud Run service
gcloud secrets add-iam-policy-binding openai-api-key \
--member=serviceAccount:YOUR_SERVICE_ACCOUNT \
--role=roles/secretmanager.secretAccessor
# Reference in deployment
gcloud run deploy praisonai-agent \
--image gcr.io/YOUR_PROJECT_ID/praisonai-agent \
--set-secrets=OPENAI_API_KEY=openai-api-key:latest
```
2. **Service Identity**: Use dedicated service accounts with minimal permissions
3. **Network Security**: Configure VPC Service Controls for sensitive deployments
4. **API Authentication**: Implement authentication for your API endpoints
## All in One
```bash
gcloud init
gcloud services enable run.googleapis.com
gcloud services enable containerregistry.googleapis.com
gcloud services enable cloudbuild.googleapis.com
export OPENAI_MODEL_NAME="gpt-4o"
export OPENAI_API_KEY="Enter your API key"
export OPENAI_API_BASE="https://api.openai.com/v1"
yes | gcloud auth configure-docker us-central1-docker.pkg.dev
gcloud artifacts repositories create praisonai-repository --repository-format=docker --location=us-central1
PROJECT_ID=$(gcloud config get-value project)
TAG="latest"
docker build --platform linux/amd64 -t gcr.io/${PROJECT_ID}/praisonai-app:${TAG} .
docker tag gcr.io/${PROJECT_ID}/praisonai-app:${TAG} us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG}
docker push us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG}
gcloud run deploy praisonai-service \
--image us-central1-docker.pkg.dev/${PROJECT_ID}/praisonai-repository/praisonai-app:${TAG} \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars OPENAI_MODEL_NAME=${OPENAI_MODEL_NAME},OPENAI_API_KEY=${OPENAI_API_KEY},OPENAI_API_BASE=${OPENAI_API_BASE}
```
+405
View File
@@ -0,0 +1,405 @@
---
title: "Deploying MCP Servers"
sidebarTitle: "MCP Servers"
description: "Learn how to deploy Model Context Protocol (MCP) servers for production environments"
icon: "server-rack"
---
# Deploying MCP Servers
This guide focuses on deploying Model Context Protocol (MCP) servers for production environments. MCP servers allow AI models to access tools and external systems through a standardized protocol.
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have the required packages installed:
```bash
pip install "praisonaiagents[mcp]"
```
For the multi-agent example with search capabilities:
```bash
pip install "praisonaiagents[mcp]" duckduckgo-search
```
</Step>
<Step title="Create MCP Server Files">
**Single Agent MCP Server**
Create a file named `simple-mcp-server.py`:
```python
from praisonaiagents import Agent
agent = Agent(instructions="Create a Tweet based on the topic provided")
agent.launch(port=8080, host="0.0.0.0", protocol="mcp")
```
**Multi-Agent MCP Server with Custom Tools**
Create a file named `simple-mcp-multi-agents-server.py`:
```python
from praisonaiagents import Agent, Agents
from duckduckgo_search import DDGS
def internet_search_tool(query: str):
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
agent = Agent(instructions="You Search the internet for information", tools=[internet_search_tool])
agent2 = Agent(instructions="You Summarise the information")
agents = Agents(agents=[agent, agent2])
agents.launch(port=8080, host="0.0.0.0", protocol="mcp")
```
**Simple Multi-Agent MCP Server**
Create a file named `simple-multi-agents-server.py`:
```python
from praisonaiagents import Agent, Agents
agent = Agent(instructions="You Search the internet for information")
agent2 = Agent(instructions="You Summarise the information")
agents = Agents(agents=[agent, agent2])
agents.launch(port=8080, host="0.0.0.0", protocol="mcp")
```
```python
from praisonaiagents import Agent, Agents
from duckduckgo_search import DDGS
def internet_search_tool(query: str):
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
agent = Agent(instructions="You Search the internet for information", tools=[internet_search_tool])
agent2 = Agent(instructions="You Summarise the information")
agents = Agents(agents=[agent, agent2])
agents.launch(port=8080, host="0.0.0.0", protocol="mcp")
```
</Step>
</Steps>
## Containerization with Docker
<Steps>
<Step title="Create a Dockerfile">
```dockerfile
FROM python:3.11-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Expose the port
EXPOSE 8080
# Run the MCP server
CMD ["python", "simple-mcp-server.py"]
```
Create a `requirements.txt` file:
```
praisonaiagents[mcp]
duckduckgo-search # Only needed for the multi-agent example
```
</Step>
<Step title="Build and Run the Docker Container">
```bash
# Build the Docker image
docker build -t mcp-server .
# Run the container
docker run -p 8080:8080 -e OPENAI_API_KEY=your_api_key mcp-server
```
</Step>
</Steps>
## Cloud Deployment
### AWS Elastic Container Service (ECS)
<Steps>
<Step title="Push Docker Image to ECR">
```bash
# Create an ECR repository
aws ecr create-repository --repository-name mcp-server
# Authenticate Docker to ECR
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com
# Tag and push the image
docker tag mcp-server:latest YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest
docker push YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest
```
</Step>
<Step title="Create ECS Task Definition">
```json
{
"family": "mcp-server",
"networkMode": "awsvpc",
"executionRoleArn": "arn:aws:iam::YOUR_AWS_ACCOUNT_ID:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "mcp-server",
"image": "YOUR_AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/mcp-server:latest",
"essential": true,
"portMappings": [
{
"containerPort": 8080,
"hostPort": 8080,
"protocol": "tcp"
}
],
"environment": [
{
"name": "OPENAI_API_KEY",
"value": "your_api_key"
}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/mcp-server",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs"
}
}
}
],
"requiresCompatibilities": [
"FARGATE"
],
"cpu": "256",
"memory": "512"
}
```
</Step>
<Step title="Deploy to ECS">
```bash
# Create a service
aws ecs create-service \
--cluster your-cluster \
--service-name mcp-server \
--task-definition mcp-server:1 \
--desired-count 1 \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[subnet-12345678],securityGroups=[sg-12345678],assignPublicIp=ENABLED}" \
--load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:us-east-1:YOUR_AWS_ACCOUNT_ID:targetgroup/mcp-server-tg/1234567890abcdef,containerName=mcp-server,containerPort=8080"
```
</Step>
</Steps>
### Google Cloud Run
<Steps>
<Step title="Push Docker Image to Google Container Registry">
```bash
# Configure Docker to use Google Cloud credentials
gcloud auth configure-docker
# Build and tag the image
docker build -t gcr.io/YOUR_PROJECT_ID/mcp-server .
# Push the image
docker push gcr.io/YOUR_PROJECT_ID/mcp-server
```
</Step>
<Step title="Deploy to Cloud Run">
```bash
gcloud run deploy mcp-server \
--image gcr.io/YOUR_PROJECT_ID/mcp-server \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars="OPENAI_API_KEY=your_api_key"
```
</Step>
</Steps>
## Production Configuration
### Security
For production deployments, implement these security measures:
1. **API Key Authentication**:
```python
agent.launch(port=8080, host="0.0.0.0", protocol="mcp", api_key="your-secret-key")
```
2. **HTTPS with SSL/TLS**:
Set up a reverse proxy like Nginx with SSL certificates:
```nginx
server {
listen 443 ssl;
server_name your-mcp-server.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
3. **Secret Management**:
Use environment variables or a secrets manager for API keys:
```bash
# AWS Secrets Manager
aws secretsmanager create-secret \
--name OPENAI_API_KEY \
--secret-string "your_api_key"
# Google Secret Manager
echo -n "your_api_key" | gcloud secrets create openai-api-key --data-file=-
```
### Scaling
For high-traffic MCP servers, consider these scaling strategies:
1. **Load Balancing**:
Deploy multiple instances behind a load balancer.
2. **Auto Scaling**:
Configure auto-scaling based on CPU/memory usage or request count.
3. **Resource Allocation**:
Allocate sufficient CPU and memory for your MCP servers:
```bash
# AWS ECS
aws ecs update-service \
--cluster your-cluster \
--service mcp-server \
--desired-count 3
# Google Cloud Run
gcloud run services update mcp-server \
--min-instances=2 \
--max-instances=10 \
--memory=2Gi \
--cpu=1
```
## Monitoring and Logging
Set up comprehensive monitoring for your MCP servers:
1. **Application Logging**:
```python
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("mcp-server.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger("mcp-server")
```
2. **Health Checks**:
Create a health check endpoint:
```python
from flask import Flask
app = Flask(__name__)
@app.route('/health')
def health_check():
return {"status": "healthy"}, 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8081)
```
3. **Metrics Collection**:
Use Prometheus or similar tools to collect metrics.
## Testing MCP Servers
Before deploying to production, thoroughly test your MCP server:
```python
import requests
import json
def test_mcp_server():
url = "http://localhost:8080/v1/chat/completions"
headers = {
"Content-Type": "application/json"
}
data = {
"messages": [
{"role": "user", "content": "Create a tweet about artificial intelligence"}
]
}
response = requests.post(url, headers=headers, data=json.dumps(data))
print(f"Status Code: {response.status_code}")
print(f"Response: {response.json()}")
if __name__ == "__main__":
test_mcp_server()
```
## Deployment Checklist
Before going live with your MCP server, ensure you've addressed these items:
- [ ] Implemented proper authentication
- [ ] Set up HTTPS with valid SSL certificates
- [ ] Configured proper logging and monitoring
- [ ] Tested the server under load
- [ ] Implemented rate limiting
- [ ] Secured all API keys and credentials
- [ ] Set up automated backups
- [ ] Created a disaster recovery plan
- [ ] Documented the deployment process
## Features
<CardGroup cols={2}>
<Card title="Containerized Deployment" icon="docker">
Package your MCP servers in Docker containers for consistent deployment.
</Card>
<Card title="Cloud-Ready" icon="cloud">
Deploy to AWS, Google Cloud, or other cloud providers with ease.
</Card>
<Card title="Scalable Architecture" icon="server">
Scale your MCP servers to handle production workloads.
</Card>
<Card title="Security-Focused" icon="shield">
Implement best practices for secure MCP server deployments.
</Card>
</CardGroup>
+210
View File
@@ -0,0 +1,210 @@
---
title: "Deploying Multi-Agent Systems as APIs"
sidebarTitle: "Multi-Agent Deployment"
description: "Learn how to deploy PraisonAI multi-agent systems as RESTful APIs for production environments"
icon: "network-wired"
---
# Deploying Multi-Agent Systems as APIs
PraisonAI allows you to deploy sophisticated multi-agent systems as RESTful APIs, enabling seamless integration with various applications and services. This guide covers different approaches to deploying multi-agent systems.
## Quick Start
<Steps>
<Step title="Install Dependencies">
Make sure you have the required packages installed:
```bash
pip install "praisonaiagents[api]>=0.0.81"
```
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY="your_api_key"
```
</Step>
<Step title="Deploy a Multi-Agent System">
Create a file named `multi-agents-api.py` with the following code:
```python
from praisonaiagents import Agent, Agents, Tools
research_agent = Agent(name="Research", instructions="You are a research agent to search internet about AI 2024", tools=[Tools.internet_search])
summarise_agent = Agent(name="Summarise", instructions="You are a summarize agent to summarise in points")
agents = Agents(agents=[research_agent, summarise_agent])
agents.launch(path="/agents", port=3030)
```
</Step>
<Step title="Run the API Server">
```bash
python multi-agents-api.py
```
Your multi-agent API will be available at `http://localhost:3030/agents`
</Step>
</Steps>
## Making API Requests
Once your multi-agent system is deployed, you can make POST requests to interact with it:
```bash
curl -X POST http://localhost:3030/agents \
-H "Content-Type: application/json" \
-d '{"message": "What are the latest developments in AI in 2024?"}'
```
The response will include the collaborative output from both the research and summarization agents:
```json
{
"response": "# Latest AI Developments in 2024\n\n- Multimodal AI models have become mainstream, combining text, image, audio, and video understanding\n- Significant advancements in AI reasoning capabilities with models like GPT-4o and Claude 3\n- Increased focus on AI alignment and safety research\n- Emergence of specialized AI agents for specific domains\n- Growth in open-source AI models and frameworks\n- Regulatory frameworks for AI being established globally"
}
```
## Multiple Agent Groups
You can deploy multiple agent groups on the same server, each with its own endpoint:
```python
from praisonaiagents import Agent, Agents, Tools
research_agent = Agent(name="Research", instructions="You are a research agent to search internet about AI 2024", tools=[Tools.internet_search])
summarise_agent = Agent(name="Summarise", instructions="You are a summarize agent to summarise in points")
agents = Agents(agents=[research_agent, summarise_agent])
agents2 = Agents(agents=[research_agent])
agents.launch(path="/agents", port=3030)
agents2.launch(path="/agents2", port=3030)
```
With this setup, you can access:
- The full agent group at `http://localhost:3030/agents`
- Just the research agent at `http://localhost:3030/agents2`
## Independent Multi-Agent Deployment
You can also deploy multiple independent agents on the same server:
```python
from praisonaiagents import Agent
weather_agent = Agent(
instructions="""You are a weather agent that can provide weather information for a given city.""",
llm="gpt-4o-mini"
)
stock_agent = Agent(
instructions="""You are a stock market agent that can provide information about stock prices and market trends.""",
llm="gpt-4o-mini"
)
travel_agent = Agent(
instructions="""You are a travel agent that can provide recommendations for destinations, hotels, and activities.""",
llm="gpt-4o-mini"
)
weather_agent.launch(path="/weather", port=3030)
stock_agent.launch(path="/stock", port=3030)
travel_agent.launch(path="/travel", port=3030)
```
## Production Deployment Options
For production environments, consider the following deployment options:
### Docker Deployment
<Steps>
<Step title="Create a Dockerfile">
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 3030
CMD ["python", "multi-agents-api.py"]
```
</Step>
<Step title="Create requirements.txt">
```
praisonaiagents[api]>=0.0.81
```
</Step>
<Step title="Build and Run Docker Container">
```bash
docker build -t praisonai-multi-agent .
docker run -p 3030:3030 -e OPENAI_API_KEY=your_api_key praisonai-multi-agent
```
</Step>
</Steps>
### Cloud Deployment
For detailed cloud deployment instructions, refer to:
- [AWS Deployment Guide](/deploy/aws)
- [Google Cloud Deployment Guide](/deploy/googlecloud)
## Scaling Multi-Agent Systems
When deploying multi-agent systems to production, consider these scaling strategies:
1. **Horizontal Scaling**: Deploy multiple instances behind a load balancer
2. **Vertical Scaling**: Allocate more CPU and memory resources for complex agent interactions
3. **Caching**: Implement response caching for frequently asked questions
4. **Asynchronous Processing**: Use message queues for handling long-running agent tasks
## API Configuration Options
When launching your multi-agent system as an API, you can customize various parameters:
```python
agents.launch(
path="/custom-endpoint", # API endpoint path
port=8080, # Port number
host="0.0.0.0", # Host address (0.0.0.0 for external access)
debug=True, # Enable debug mode
cors_origins=["*"], # CORS configuration
api_key="your-api-key" # Optional API key for authentication
)
```
## Securing Your Multi-Agent API
For production deployments, consider implementing:
1. **API Key Authentication**: Require API keys for all requests
2. **Rate Limiting**: Limit the number of requests per client
3. **HTTPS**: Use SSL/TLS certificates for encrypted communication
4. **Input Validation**: Validate all input data before processing
5. **Output Filtering**: Implement content filtering for agent responses
## Monitoring and Logging
For production environments, consider:
1. **Centralized Logging**: Collect logs from all agents in a central location
2. **Performance Metrics**: Track response times and resource usage
3. **Error Tracking**: Monitor and alert on agent failures
4. **Usage Analytics**: Track which agents are used most frequently
## Features
<CardGroup cols={2}>
<Card title="Collaborative Agents" icon="users-gear">
Deploy agent systems that collaborate to solve complex problems.
</Card>
<Card title="Specialized Endpoints" icon="sitemap">
Create dedicated endpoints for different agent groups or individual agents.
</Card>
<Card title="Tool Integration" icon="screwdriver-wrench">
Deploy agents with specialized tools like web search capabilities.
</Card>
<Card title="Scalable Architecture" icon="server">
Scale your multi-agent systems to handle production workloads.
</Card>
</CardGroup>
+1 -1
View File
@@ -27,7 +27,7 @@ WORKDIR /app
COPY . .
RUN pip install flask praisonai==2.0.18 watchdog
RUN pip install flask praisonai==2.2.16 watchdog
EXPOSE 5555
+2 -2
View File
@@ -65,14 +65,14 @@ def basic(): # Basic Mode
def advanced(): # Advanced Mode with options
praisonai = PraisonAI(
agent_file="agents.yaml",
framework="autogen",
framework="autogen", # use AG2 framework (Formerly AutoGen)
)
praisonai.run()
def auto(): # Full Automatic Mode
praisonai = PraisonAI(
auto="Create a movie script about car in mars",
framework="autogen"
framework="autogen" # use AG2 framework
)
print(praisonai.framework)
praisonai.run()
+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>
+7 -6
View File
@@ -1,12 +1,13 @@
---
title: "AutoGen with PraisonAI"
description: "Guide for using AutoGen framework with PraisonAI, including installation, setup, and multi-agent conversation capabilities"
title: "AG2 with PraisonAI"
description: "Guide for using AG2 framework with PraisonAI, including installation, setup, and multi-agent conversation capabilities"
icon: "robot"
---
# AutoGen with PraisonAI
# AG2 with PraisonAI
Low-code solution to run AutoGen with integrated tools and features.
Low-code solution to run AG2 with integrated tools and features.
AutoGen is being evolved into AG2, check the new look [here](https://docs.ag2.ai/docs/Home/)
## Installation
@@ -16,7 +17,7 @@ pip install "praisonai[autogen]"
```
This installation includes:
- AutoGen framework
- AG2 framework
- PraisonAI tools integration
- Multi-agent conversation capabilities
- Code execution environment
@@ -27,7 +28,7 @@ This installation includes:
# Set your OpenAI API key
export OPENAI_API_KEY=xxxxxxxxxx
# Initialize with AutoGen
# Initialize with AG2
praisonai --framework autogen --init "Create a Movie Script About Cat in Mars"
# Run the agents
+6 -6
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: "Comprehensive guide to PraisonAI - an AI Agents Framework with Self Reflection, combining PraisonAI Agents, AG2 (Formerly AutoGen), and CrewAI for building multi-agent LLM systems"
icon: "house"
openGraph:
url: "/"
@@ -46,7 +46,7 @@ seo:
</div>
<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.
PraisonAI combines PraisonAI Agents, AG2 (Formerly 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.
</Tip>
## Key Features
@@ -56,7 +56,7 @@ seo:
Automated creation and management of AI agents with self-reflection capabilities
</Card>
<Card title="Framework Integration" icon="puzzle-piece">
Seamless integration with CrewAI and AutoGen frameworks
Seamless integration with CrewAI and AG2 frameworks
</Card>
<Card title="LLM Support" icon="brain">
Support for 100+ Language Learning Models
@@ -301,8 +301,8 @@ seo:
<Card title="CrewAI Framework" icon="users-gear" href="/framework/crewai">
Build collaborative AI teams with CrewAI integration
</Card>
<Card title="AutoGen Framework" icon="robot" href="/framework/autogen">
Create autonomous agent networks using AutoGen
<Card title="AG2 Framework" icon="robot" href="/framework/autogen">
Create autonomous agent networks using AG2 (Formerly AutoGen)
</Card>
<Card title="Multimodal Agents" icon="icons" href="/framework/multimodalagents">
Work with agents that can process text, images, and other data types
@@ -316,7 +316,7 @@ seo:
<CardGroup cols={3}>
<Card title="Multi Agents UI" icon="users" href="/ui/ui">
Work with CrewAI or AutoGen multi-agent systems
Work with CrewAI or AG2 multi-agent systems
</Card>
<Card title="Chat Interface" icon="comments" href="/ui/chat">
Chat with 100+ LLMs using a single AI Agent
+567 -122
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, AG2 (Formerly 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: "/"
@@ -45,7 +45,7 @@ seo:
Automated creation and management of AI agents with self-reflection capabilities
</Card>
<Card title="Framework Integration" icon="puzzle-piece">
Seamless integration with CrewAI and AutoGen frameworks
Seamless integration with CrewAI and AG2 frameworks
</Card>
<Card title="LLM Support" icon="brain">
Support for 100+ Language Learning Models
@@ -66,49 +66,10 @@ 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="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.
</Tip>
<Steps>
<Step title="Install Package">
```bash
pip install praisonai
```
</Step>
<Step title="Set API Key">
```bash
export OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxx
```
</Step>
<Step title="Auto Mode">
```bash
praisonai --auto create a movie script about Robots in Mars
```
This will automatically create required agents and complete the task
</Step>
</Steps>
</Tab>
<Tab title="Code">
<Steps>
<Step title="Install Package">
@@ -127,86 +88,22 @@ seo:
## Code Example
<CodeGroup>
```python Basic
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 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()
```
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
agents.start()
```
</CodeGroup>
</Step>
<Step title="Run Script">
@@ -216,8 +113,529 @@ seo:
</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="Set API Key">
```bash
export OPENAI_API_KEY=your_openai_key
```
</Step>
<Step title="Create Config">
Create `agents.yaml`:
<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>
<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>
## Playground
<iframe
id="codeExecutionFrame"
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
width="100%"
height="600px"
frameborder="0"
allow="clipboard-read; clipboard-write"
scrolling="yes"
onload="resizeIframe(this)"
></iframe>
## 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>
@@ -293,8 +711,8 @@ seo:
<Card title="CrewAI Framework" icon="users-gear" href="/framework/crewai">
Build collaborative AI teams with CrewAI integration
</Card>
<Card title="AutoGen Framework" icon="robot" href="/framework/autogen">
Create autonomous agent networks using AutoGen
<Card title="AG2 Framework" icon="robot" href="/framework/autogen">
Create autonomous agent networks using AG2 (Formerly AutoGen)
</Card>
<Card title="Multimodal Agents" icon="icons" href="/framework/multimodalagents">
Work with agents that can process text, images, and other data types
@@ -308,7 +726,7 @@ seo:
<CardGroup cols={3}>
<Card title="Multi Agents UI" icon="users" href="/ui/ui">
Work with CrewAI or AutoGen multi-agent systems
Work with CrewAI or AG2 multi-agent systems
</Card>
<Card title="Chat Interface" icon="comments" href="/ui/chat">
Chat with 100+ LLMs using a single AI Agent
@@ -338,4 +756,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) |
+38
View File
@@ -11,6 +11,12 @@ pip install praisonaiagents
```bash No Code
pip install praisonai
```
```bash JavaScript
npm install praisonai
```
```bash TypeScript
npm install praisonai
```
</RequestExample>
<Note>
@@ -90,6 +96,38 @@ 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>
<Tab title="TypeScript">
<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)
+216 -121
View File
@@ -89,147 +89,242 @@ 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>
<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>
## Playground
<iframe
id="codeExecutionFrame"
src="https://code-execution-server-praisonai.replit.app/?code=import%20openai%0A%0Aclient%20%3D%20openai.OpenAI()%0Aresult%20%3D%20client.chat.completions.create(%0A%20%20%20%20model%3D%22gpt-3.5-turbo%22%2C%0A%20%20%20%20messages%3D%5B%0A%20%20%20%20%20%20%20%20%7B%22role%22%3A%20%22user%22%2C%20%22content%22%3A%20%22Hello%20World%22%7D%0A%20%20%20%20%5D%0A)%0A%0Aprint(result.choices%5B0%5D.message.content)"
width="100%"
height="600px"
frameborder="0"
allow="clipboard-read; clipboard-write"
scrolling="yes"
onload="resizeIframe(this)"
></iframe>
## Key Features
<CardGroup cols={3}>
Loaded 100 of 587 files, more files were not shown because too many files have changed in this diff. Show more