Compare commits

...
233 Commits
Author SHA1 Message Date
Mervin Praison a8b1948fc0 feat(ag2): add AG2 framework backend integration (#1143)
feat(ag2): add AG2 framework backend integration
2026-03-26 17:48:37 +00:00
Faridun Mirzoev 56f815c1b1 fix(ag2): address Qodo review issues - YAML config resolution, OPENAI_API_BASE, patch create=True
- Add _resolve() helper to read LLM config from YAML top-level, per-role,
  config_list, and env vars in priority order (fixes Bedrock YAML config ignored)
- Include OPENAI_API_BASE env var in base_url resolution chain
- Add create=True to all patch("autogen.*") calls so tests pass without ag2 installed
2026-03-26 09:48:14 -07:00
Faridun Mirzoev 6b30977d9e feat(ag2): add AG2 framework backend integration
Integrates AG2 (community fork of AutoGen, PyPI package: ag2) as a new
framework option alongside praisonai, crewai, and autogen.

Changes:
- pyproject.toml: add [ag2] optional dependency extra (ag2>=0.11.0)
- agents_generator.py: AG2 detection via importlib.metadata + _run_ag2()
  with LLMConfig dict pattern, GroupChat orchestration, Bedrock support,
  ChatResult.summary extraction, and TERMINATE cleanup
- auto.py: AG2_AVAILABLE flag + validation in AutoGenerator.__init__
- .env.example: add AG2 and AWS Bedrock environment variable templates
- examples/ag2/: basic, multi-agent, and Bedrock YAML examples
- tests: 16 unit tests + 9 mock integration tests (25/25 passing)

Detection uses importlib.metadata.distribution('ag2') + LLMConfig check.
All changes are purely additive — existing code paths unaffected.

E2E tested against OpenAI gpt-4o-mini: single-agent and multi-agent
GroupChat flows both produce correct output.
2026-03-24 16:47:46 -04:00
Mervin Praison 4966ec1ae1 Merge pull request #658 from MervinPraison/develop
Enhance Claude workflow by adding environment variable for GitHub tok…
2025-06-16 08:26:16 +02:00
MervinPraison c31870a991 Enhance Claude workflow by adding environment variable for GitHub token and implementing package visibility check and Docker authentication tests for improved reliability and security. 2025-06-16 07:25:57 +01:00
Mervin Praison 67f4a89062 Merge pull request #657 from MervinPraison/develop
Add debugging steps to Claude workflow for environment verification a…
2025-06-16 08:24:07 +02:00
MervinPraison a898bbb7d1 Add debugging steps to Claude workflow for environment verification and Docker testing 2025-06-16 07:23:50 +01:00
Mervin Praison 107d33deb7 Merge pull request #656 from MervinPraison/develop
Update Claude Code action to restrict package permissions and remove …
2025-06-16 08:21:21 +02:00
MervinPraison 9d963e4eeb Update Claude Code action to restrict package permissions and remove Docker image build step for streamlined workflow. 2025-06-16 07:21:02 +01:00
Mervin Praison 56b296b8d6 Merge pull request #655 from MervinPraison/develop
Update Claude Code action to enable package writing and add Docker im…
2025-06-16 08:18:07 +02:00
MervinPraison fddf999688 Update Claude Code action to enable package writing and add Docker image build and push step for enhanced deployment capabilities. 2025-06-16 07:14:29 +01:00
Mervin Praison 6374aba783 Merge pull request #654 from MervinPraison/develop
Update Claude Code action to use GitHub token for authentication, enh…
2025-06-16 08:13:03 +02:00
MervinPraison 9408d699e8 Update Claude Code action to use GitHub token for authentication, enhancing security and consistency in the workflow. 2025-06-16 07:12:10 +01:00
Mervin Praison 6358671ab9 Merge pull request #652 from MervinPraison/develop
Enhance Claude Code action by adding environment variable verificatio…
2025-06-15 07:43:51 +02:00
MervinPraison f5bd55bb9a Enhance Claude Code action by adding environment variable verification and updating Docker setup for improved reliability 2025-06-15 06:43:34 +01:00
Mervin Praison a93c571f33 Merge pull request #651 from MervinPraison/develop
Update Claude Code action reference to use local action for improved …
2025-06-15 07:42:13 +02:00
MervinPraison 8ea0e4c831 Update Claude Code action reference to use local action for improved maintainability 2025-06-15 06:41:42 +01:00
Mervin Praison 8a1dc24794 Merge pull request #650 from MervinPraison/develop
Update Claude Code action reference to use quotes for consistency
2025-06-15 07:39:30 +02:00
MervinPraison b331229578 Update Claude Code action reference to use quotes for consistency 2025-06-15 06:39:12 +01:00
Mervin Praison 7af52735cf Merge pull request #649 from MervinPraison/develop
Add GitHub Container Registry login step and update Claude Code actio…
2025-06-15 07:37:42 +02:00
MervinPraison 2902fec42e Add GitHub Container Registry login step and update Claude Code action reference 2025-06-15 06:37:28 +01:00
Mervin Praison 64f752a8e0 Merge pull request #648 from MervinPraison/develop
Update Docker image reference in Claude Code action for consistency
2025-06-15 07:35:30 +02:00
MervinPraison d994fb5047 Update Docker image reference in Claude Code action for consistency 2025-06-15 06:34:52 +01:00
Mervin Praison 760fb9530b Merge pull request #647 from MervinPraison/develop
Refactor Claude Code integration to use local action instead of Docke…
2025-06-15 07:33:04 +02:00
MervinPraison de165975b0 Refactor Claude Code integration to use local action instead of Docker image for improved maintainability 2025-06-15 06:32:43 +01:00
Mervin Praison dfd74a2fe7 Merge pull request #646 from MervinPraison/develop
Develop
2025-06-15 07:29:30 +02:00
MervinPraison 9265ca08a2 Update Claude Code integration to use Docker image and add GitHub token for authentication 2025-06-15 06:28:57 +01:00
MervinPraison 665df753fd Remove CLAUDE_CODE_INTEGRATION_PRAISONAI_AGENTS.md as it is no longer needed for the integration of Claude Code with PraisonAI Agents. This deletion simplifies the documentation and reflects the current state of the project. 2025-06-15 05:55:55 +01:00
Mervin Praison 94d991f4ec Merge pull request #643 from MervinPraison/develop
Update PraisonAI and dependencies to version 2.2.33
2025-06-14 08:45:31 +02:00
MervinPraison 632cf68423 Update PraisonAI and dependencies to version 2.2.33
- Updated PraisonAI version from 2.2.32 to 2.2.33 across multiple Dockerfiles and relevant files.
- Adjusted dependency versions in pyproject.toml and other files for consistency.
- Enhanced README documentation to reflect the updated version.

This change integrates the latest features and improvements from PraisonAI while ensuring compatibility with existing code.
2025-06-14 07:45:15 +01:00
Mervin Praison d956c605f7 Merge pull request #635 from MervinPraison/claude/issue-634-20250610_115418
feat: Refactor Claude Code integration to use PraisonAI Agents
2025-06-14 08:43:35 +02:00
Mervin Praison 7e3de10f32 Rename test_claude_code_integration.py to src/praisonai/tests/unit/test_claude_code_integration.py 2025-06-14 07:41:20 +01:00
Mervin Praison 79883f1af2 Merge pull request #642 from MervinPraison/develop
Update PraisonAI and dependencies to version 2.2.32
2025-06-14 08:39:04 +02:00
MervinPraison a098eb0150 Update PraisonAI and dependencies to version 2.2.32
- Updated PraisonAI version from 2.2.31 to 2.2.32 across multiple Dockerfiles and relevant files.
- Adjusted dependency versions in pyproject.toml and other files for consistency.
- Enhanced README documentation to reflect the updated version.

This change integrates the latest features and improvements from PraisonAI while ensuring compatibility with existing code.
2025-06-14 07:38:45 +01:00
Mervin Praison b9ce3b4ccb Merge pull request #641 from MervinPraison/develop
Allow to configure reflection prompt
2025-06-14 08:36:28 +02:00
claude[bot]andMervin Praison 58b44280df feat: add self-reflection support with configurable prompt to achat method
- Implement complete self-reflection logic in achat method to match chat method
- Support configurable reflect_prompt parameter in async operations  
- Add reflection loop with min/max limits and error handling
- Update method docstring to reflect new self-reflection capability
- Ensure consistent behavior between chat and achat methods

Co-authored-by: Mervin Praison <[email protected]>
2025-06-14 06:26:49 +00:00
MervinPraison 4dba09d6b1 Merge remote-tracking branch 'leo-origin/feature/add-reflection-prompt' into test-reflection-prompt 2025-06-14 07:20:09 +01:00
Mervin Praison a538513bec Merge pull request #640 from MervinPraison/develop
Develop
2025-06-14 08:17:26 +02:00
MervinPraison 4fb79207cf Merge branch 'main' of https://github.com/MervinPraison/PraisonAI into develop 2025-06-14 07:16:44 +01:00
MervinPraison 0b444fae34 Merge branch 'develop' of https://github.com/MervinPraison/PraisonAI into develop 2025-06-14 07:16:26 +01:00
MervinPraison bd34e45bbc Update PraisonAI and dependencies to version 2.2.31
- Updated PraisonAI version from 2.2.30 to 2.2.31 across multiple Dockerfiles and the Ruby formula.
- Adjusted dependency versions in pyproject.toml and other relevant files for consistency.
- Enhanced README documentation to reflect the updated version.

This change ensures that the latest features and improvements from PraisonAI are integrated while maintaining compatibility with existing code.
2025-06-14 07:16:25 +01:00
Mervin Praison f4f051e57e Merge pull request #638 from krkead/patch-2
Update chainlit_ui.py to work with newer chainlit versions
2025-06-14 08:13:56 +02:00
Mervin Praison 3c2610cc3c Merge pull request #639 from krkead/patch-1
Update agents.py to work with newer chainlit versions
2025-06-14 08:13:44 +02:00
krkead 9788454134 Update chainlit_ui.py to work with newer chainlit versions
The previous payload modification was incorrect
2025-06-13 18:04:52 -03:00
krkead e618004e60 Update agents.py to work with newer chainlit versions 2025-06-13 18:02:35 -03:00
Mervin Praison 384803ba8e Merge pull request #637 from DhivyaBharathy-web/add-mistral-agent
Add Mistral v0.3 Conversational Agent – Conceptual Workflow
2025-06-12 06:01:21 +02:00
DhivyaBharathy-web d3bb366a51 Add Mistral 7B Instruction Agent notebook 2025-06-11 10:49:16 +00:00
DhivyaBharathy e579e84b52 Add files via upload 2025-06-11 16:13:42 +05:30
leovs09 61440403f5 add agent constructor params description 2025-06-11 00:48:51 +02:00
leovs09 b615782175 Allow to configure reflection prompt 2025-06-11 00:24:59 +02:00
claude[bot]andMervinPraison 35199979f0 feat: Refactor Claude Code integration to use PraisonAI Agents
- Replace litellm direct usage with praisonaiagents framework
- Implement Claude Code as a custom tool that agents can decide to use
- Add --claudecode CLI flag support: `praisonai code --claudecode`
- Create intelligent agent that chooses when to use Claude Code vs regular responses
- Maintain full backward compatibility with litellm fallback
- Add UI toggle switch for enabling/disabling Claude Code
- Implement git operations with automatic branch creation and PR URLs
- Add comprehensive error handling and streaming support
- Include test script and detailed documentation

Key improvements:
- Agent-driven decision making instead of manual detection logic
- Better tool coordination and flexibility
- Minimal code changes with maintained compatibility
- Enhanced user experience with intelligent tool selection

Co-Authored-By: MervinPraison <[email protected]>
2025-06-10 12:02:19 +00:00
DhivyaBharathy eeb77cfd20 Add files via upload 2025-06-10 16:15:43 +05:30
Mervin Praison 00d7994601 Merge pull request #633 from DhivyaBharathy-web/add-nlp-asr-agent
Add NLP + ASR Agent (Official BERT Large + Whisper Large V3)
2025-06-10 08:55:08 +01:00
DhivyaBharathy 10aa49addc Merge branch 'main' into add-nlp-asr-agent 2025-06-10 12:05:50 +05:30
DhivyaBharathy-web 79c9cf8bf9 Add NLP + ASR Agent (Official BERT Large + Whisper Large V3) notebook 2025-06-10 06:32:31 +00:00
Mervin Praison a9416fb7fc Merge pull request #631 from MervinPraison/claude/issue-630-20250609_145612
feat: add remote agent connectivity with Google ADK-like API
2025-06-09 20:43:47 +01:00
Mervin Praison 547b40ee72 Rename test_remote_agent.py to src/praisonai/tests/unit/test_remote_agent.py 2025-06-09 20:43:32 +01:00
claude[bot]andMervinPraison 4fc35d1b10 feat: add remote agent connectivity with Google ADK-like API
- Enhanced Session class to support remote agent URLs
- Added agent_url parameter for direct agent connectivity  
- Implemented HTTP client for remote agent communication
- Added connection testing and validation
- Provided send_message() alias for Google ADK compatibility
- Created comprehensive examples and documentation
- Maintained full backward compatibility
- Added proper error handling for remote operations

Fixes #630

Co-authored-by: MervinPraison <[email protected]>
2025-06-09 15:02:42 +00:00
Mervin Praison c72d74987b Merge pull request #625 from DhivyaBharathy-web/add-mistral7b-agent
Add mistral7b agent
2025-06-08 00:14:37 +01:00
DhivyaBharathy 430ec6571a Update MistralTechAgent.ipynb 2025-06-07 14:22:57 +05:30
DhivyaBharathy e88288773a Add files via upload 2025-06-07 14:15:47 +05:30
DhivyaBharathy-web 9af03e3fef Add Mistral-7B-Instruct-v0.1 Instruction Agent notebook 2025-06-07 08:43:22 +00:00
Mervin Praison 7a7560621b Merge pull request #624 from MervinPraison/develop
Develop
2025-06-07 01:27:46 +01:00
MervinPraison 531c58ac70 Update PraisonAI and dependencies to version 2.2.31 and praisonaiagents to version 0.0.104
- Updated PraisonAI version in Dockerfiles and Ruby formula.
- Adjusted dependency versions in pyproject.toml and uv.lock for consistency.
- Enhanced README to reflect the new versioning.

This change ensures compatibility with the latest features and improvements while maintaining existing functionality.
2025-06-07 01:27:29 +01:00
MervinPraison 274ade8154 Disable litellm telemetry across multiple modules for improved performance and consistency
- Added environment variable to disable litellm telemetry in __init__.py, llm.py, and memory.py.
- Ensured telemetry is disabled after importing litellm to prevent unnecessary data collection.

This change enhances control over telemetry features while maintaining existing functionality.
2025-06-07 00:24:28 +01:00
Mervin Praison 83f4f874e9 Merge pull request #622 from DhivyaBharathy-web/add-groq-Llama3-agent
Add Groq Llama3-8b-8192 Agent notebook
2025-06-06 23:38:03 +01:00
MervinPraison 99cd88dd30 Enhance telemetry support and update dependencies
- Added 'posthog>=4.0.0' to dependencies and optional 'telemetry' section in pyproject.toml.
- Updated blog_agent to use llm_config for improved clarity.
- Disabled memory in PraisonAIAgents instantiation for better control.
- Introduced telemetry support with lazy loading and fallback functions in __init__.py.

This update improves the integration of telemetry features while maintaining existing functionality.
2025-06-06 17:52:43 +01:00
DhivyaBharathy 1d22818662 Add files via upload 2025-06-06 15:28:14 +05:30
DhivyaBharathy-web 4f38e7250a Add Groq Llama3-8b-8192 Agent notebook 2025-06-06 09:52:36 +00:00
Mervin Praison b736567375 Merge pull request #618 from MervinPraison/revert-617-claude/issue-612-20250606_060924
Revert "fix: prevent duplicate Task and Response display when using litellm with memory"
2025-06-06 07:28:27 +01:00
Mervin Praison d014ea8d18 Revert "fix: prevent duplicate Task and Response display when using litellm with memory" 2025-06-06 07:28:13 +01:00
Mervin Praison fd6db3ccfa Merge pull request #617 from MervinPraison/claude/issue-612-20250606_060924
fix: prevent duplicate Task and Response display when using litellm with memory
2025-06-06 07:24:32 +01:00
claude[bot]andMervinPraison 1f2f26c5cf fix: prevent duplicate Task and Response display when using litellm with memory
- Add suppress_display parameter to LLM.get_response() method (default: False)
- Update all display_interaction calls in LLM class to respect suppress_display flag
- Agent class now passes suppress_display=True to prevent LLM duplicate displays
- Agent handles display centrally to ensure single display per interaction
- Maintains full backward compatibility while fixing issue #612

Co-authored-by: MervinPraison <[email protected]>
2025-06-06 06:16:39 +00:00
Mervin Praison 1965f296b0 Merge pull request #614 from MervinPraison/revert-613-claude/issue-612-20250605_213542
Revert "fix: prevent duplicate Task and Response display when using litellm with memory"
2025-06-06 06:43:34 +01:00
Mervin Praison cc7036784b Revert "fix: prevent duplicate Task and Response display when using litellm with memory" 2025-06-06 06:43:21 +01:00
Mervin Praison 826a68c33e Merge pull request #613 from MervinPraison/claude/issue-612-20250605_213542
fix: prevent duplicate Task and Response display when using litellm with memory
2025-06-06 06:41:16 +01:00
claude[bot]andMervinPraison 88ceba804b fix: prevent duplicate Task and Response display when using litellm with memory
- Add display_interaction parameter to LLM.get_response() method (default: True)
- Update all internal display_interaction calls in LLM class to respect new parameter  
- Modify agent calls to pass display_interaction=False when using custom LLM instances
- Maintains backward compatibility while fixing duplicate displays (fixes #612)

Co-authored-by: MervinPraison <[email protected]>
2025-06-05 21:45:59 +00:00
Mervin Praison dc5b10fba8 Merge pull request #611 from MervinPraison/develop
Update PraisonAI version to 2.2.30 across Dockerfiles and related files
2025-06-05 18:18:04 +01:00
MervinPraison f0172e8339 Update PraisonAI version to 2.2.30 across Dockerfiles and related files
- Incremented the version of PraisonAI from 2.2.29 to 2.2.30 in Dockerfiles (Dockerfile, Dockerfile.chat, Dockerfile.dev, Dockerfile.ui).
- Updated the version in the README.md and pyproject.toml files to reflect the new version.
- Adjusted the deploy.py script to install the updated version of PraisonAI.
- Ensured consistency across all relevant files for seamless integration.
2025-06-05 18:17:47 +01:00
Mervin Praison 5c498a12de Merge pull request #610 from MervinPraison/claude/issue-605-20250605_165941
fix: resolve Memory import error with litellm compatibility
2025-06-05 18:16:11 +01:00
Mervin Praison 88410881e1 Rename test_session_import.py to src/praisonai/tests/unit/test_session_import.py 2025-06-05 18:10:43 +01:00
Mervin Praison 791d59f96e Rename test_memory_import.py to src/praisonai/tests/unit/test_memory_import.py 2025-06-05 18:10:25 +01:00
Mervin Praison cdbe1303ad Rename test_comprehensive_import.py to src/praisonai/tests/unit/test_comprehensive_import.py 2025-06-05 18:10:10 +01:00
claude[bot]andMervinPraison b63f931bea feat: add Memory to main package exports and comprehensive tests
- Export Memory class from main praisonaiagents package
- Add Memory to __all__ list for proper package API
- Create comprehensive test suite to verify all import scenarios
- Tests original failing import from GitHub issue
- Tests direct Memory imports and instantiation

Co-authored-by: MervinPraison <[email protected]>
2025-06-05 17:02:47 +00:00
claude[bot]andMervinPraison ff25b96f91 fix: resolve Memory import error by implementing litellm compatibility
- Add LITELLM_AVAILABLE flag for proper dependency detection
- Implement litellm → openai fallback pattern for all embedding operations
- Update search_short_term, store_long_term, search_long_term embedding calls
- Update calculate_quality_metrics to use litellm → openai fallback
- Add graceful degradation when neither litellm nor openai is available
- Fixes ImportError: cannot import name 'Memory' from 'praisonaiagents.memory'

Co-authored-by: MervinPraison <[email protected]>
2025-06-05 17:02:03 +00:00
Mervin Praison 603f0ea008 Merge pull request #609 from MervinPraison/develop
Develop
2025-06-05 17:55:15 +01:00
MervinPraison db38b55174 Update PraisonAI version to 2.2.29 across Dockerfiles and related files
- Incremented the version of PraisonAI from 2.2.28 to 2.2.29 in Dockerfiles (Dockerfile, Dockerfile.chat, Dockerfile.dev, Dockerfile.ui).
- Updated the version in the README.md and pyproject.toml files to reflect the new version.
- Adjusted the deploy.py script to install the updated version of PraisonAI.
- Ensured consistency across all relevant files for seamless integration.
2025-06-05 17:54:57 +01:00
MervinPraison cebd175d61 Update versioning and dependencies in project files
- Incremented version of PraisonAI from 0.0.99 to 0.0.101 in pyproject.toml and uv.lock.
- Added 'litellm' dependency to memory requirements for enhanced functionality.
- Updated .gitignore to include 'CopilotKit*' for better file management.
- Optimised TaskOutput instantiation in agent.py for clarity.
- Refined memory handling in memory.py to utilise LiteLLM for consistency.
- Improved model extraction logic in task.py for better fallback handling.
2025-06-05 17:53:38 +01:00
Mervin Praison 01ff75e573 Merge pull request #606 from DhivyaBharathy-web/add-qwen2-5-agent
Add Qwen2.5 Instruction Agent notebook using Hugging Face Transformers
2025-06-05 17:43:36 +01:00
Mervin Praison 28629f2203 Merge pull request #607 from DhivyaBharathy-web/add-gemma2b-instruction-agent
Add Gemma2B_Instruction_Agent to Cookbooks
2025-06-05 17:43:19 +01:00
Mervin Praison ac5c463362 Merge pull request #602 from DhivyaBharathy-web/add-predictive-maintenance-notebook
Add predictive maintenance notebook
2025-06-05 17:43:05 +01:00
Mervin Praison 84dc57583e Merge pull request #608 from DhivyaBharathy-web/add-tinyllama-model-agent
Add tinyllama model agent
2025-06-05 17:42:50 +01:00
DhivyaBharathy 460e8b45a7 Merge branch 'main' into add-tinyllama-model-agent 2025-06-05 19:30:02 +05:30
DhivyaBharathy f6bbbd7cd6 Update TinyLlama_1_1B_model_SimpleAIAgent.ipynb 2025-06-05 19:29:06 +05:30
DhivyaBharathy 8a435571f4 Add files via upload 2025-06-05 19:10:44 +05:30
DhivyaBharathy 204106daa8 Merge branch 'main' into add-gemma2b-instruction-agent 2025-06-05 16:47:50 +05:30
DhivyaBharathy 6a1e14f97a Merge branch 'main' into add-qwen2-5-agent 2025-06-05 16:47:02 +05:30
DhivyaBharathy 333777b991 Merge branch 'main' into add-predictive-maintenance-notebook 2025-06-05 16:46:13 +05:30
DhivyaBharathy b02cd85290 Update Gemma2B_Instruction_Agent.ipynb 2025-06-05 16:27:38 +05:30
DhivyaBharathy 3bc0c2b533 Update Gemma2B_Instruction_Agent.ipynb 2025-06-05 16:26:56 +05:30
DhivyaBharathy 68d4f34bb7 Update Gemma2B_Instruction_Agent.ipynb 2025-06-05 16:26:37 +05:30
DhivyaBharathy a24d900a8c Add files via upload 2025-06-05 16:22:33 +05:30
DhivyaBharathy-web 552a10df9e Add Qwen2.5 Instruction Agent notebook 2025-06-05 10:49:32 +00:00
DhivyaBharathy 9c57aa3165 Update Qwen2_5_InstructionAgent.ipynb 2025-06-05 15:16:04 +05:30
DhivyaBharathy 40fe92f1d0 Update Qwen2_5_InstructionAgent.ipynb 2025-06-05 15:14:56 +05:30
DhivyaBharathy 179cc9566d Update Qwen2_5_InstructionAgent.ipynb 2025-06-05 15:09:09 +05:30
DhivyaBharathy d9cf9ba534 Add files via upload 2025-06-05 15:07:47 +05:30
DhivyaBharathy-web 4ec0366e79 Add Qwen2.5 Instruction Agent notebook 2025-06-05 09:26:46 +00:00
Mervin Praison d6a3bd1240 Merge pull request #604 from MervinPraison/develop
Update PraisonAI version to 2.2.28 across Dockerfiles and related files
2025-06-04 22:59:48 +01:00
MervinPraison 0a18e27f54 Update PraisonAI version to 2.2.28 across Dockerfiles and related files
- Updated the version of PraisonAI from 2.2.27 to 2.2.28 in Dockerfiles (Dockerfile, Dockerfile.chat, Dockerfile.dev, Dockerfile.ui).
- Modified the version in the README.md and pyproject.toml files to reflect the new version.
- Adjusted the deploy.py script to install the updated version of PraisonAI.
- Ensured consistency across all relevant files for seamless integration.
2025-06-04 22:59:30 +01:00
DhivyaBharathy b824d950b5 Add files via upload 2025-06-04 20:32:10 +05:30
Mervin Praison a5b768c213 Merge pull request #601 from MervinPraison/develop
Develop
2025-06-04 15:50:06 +01:00
MervinPraison 068bdbebc5 Update PraisonAI version to 2.2.27 across Dockerfiles and related files
- Updated the version of PraisonAI from 2.2.26 to 2.2.27 in Dockerfiles (Dockerfile, Dockerfile.chat, Dockerfile.dev, Dockerfile.ui).
- Modified the version in the README.md and pyproject.toml files to reflect the new version.
- Adjusted the deploy.py script to install the updated version of PraisonAI.
- Ensured consistency across all relevant files for seamless integration.
2025-06-04 15:49:47 +01:00
MervinPraison 4d80d795f8 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI into develop 2025-06-04 15:48:15 +01:00
MervinPraison 2e3b5cd29b Merge branch 'develop' of https://github.com/MervinPraison/PraisonAI into develop 2025-06-04 15:48:08 +01:00
MervinPraison d948b6de2c Refactor agent guardrails and update versioning
- Removed the outdated agent_guardrails_example.py file.
- Introduced a new guardrail_agents_example.py file with improved structure and user-friendly naming.
- Updated version in pyproject.toml from 0.0.97 to 0.0.98.
- Added revision information in uv.lock for better dependency tracking.
- Imported asyncio in agent.py for enhanced functionality.
2025-06-04 15:47:14 +01:00
Mervin Praison 3adb06950c Merge pull request #599 from MervinPraison/develop
Update test workflow to use custom test runner for 'fast' pattern and…
2025-06-04 14:21:02 +01:00
claude[bot]andClaude e45e85975c feat: implement Agent-level guardrail support
- Add guardrail and max_guardrail_retries parameters to Agent constructor
- Implement _setup_guardrail() method supporting function and LLM-based guardrails  
- Add _process_guardrail() method for validation processing
- Create _apply_guardrail_with_retry() method with automatic retry logic
- Integrate guardrail processing into all major return points in chat() method
- Support both regular responses and reasoning content validation
- Update agent_guardrails_example.py with comprehensive demonstrations
- Enhance CLAUDE.md documentation with Agent-level guardrail usage
- Add test file for Agent guardrail functionality validation

Agent-level guardrails apply to ALL outputs from the agent, providing
consistent validation across all agent interactions with configurable
retry logic and support for both function-based and string-based 
LLM guardrails.

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

Co-Authored-By: Claude <[email protected]>
2025-06-04 11:57:22 +00:00
Mervin Praison 8a7935dc2c Merge pull request #600 from DhivyaBharathy-web/code-analysis-agent
Add code analysis agent notebook
2025-06-04 12:40:08 +01:00
DhivyaBharathy b31edc90d5 Update Code_Analysis_Agent.ipynb 2025-06-04 16:58:52 +05:30
DhivyaBharathy d2841ccb3a Merge branch 'MervinPraison:main' into main 2025-06-04 16:53:54 +05:30
DhivyaBharathy-web e22fda805f Add code analysis agent notebook 2025-06-04 11:20:39 +00:00
MervinPraison 2cde2fd731 Update test workflow to use custom test runner for 'fast' pattern and refine guardrail functionality in Task class
- Changed the test command in the GitHub Actions workflow to run a specific test runner script with a 'fast' pattern.
- Introduced guardrail functionality in the Task class to validate task outputs, including error handling and retry logic for guardrail validation failures.
- Enhanced the initialization of guardrail parameters and ensured proper type checking for guardrail functions.
2025-06-04 12:10:01 +01:00
Mervin Praison f7534681e5 Merge pull request #598 from MervinPraison/develop
Develop
2025-06-04 12:09:21 +01:00
MervinPraison 8c9e3e34cb agent sequential thinking 2025-06-04 11:52:53 +01:00
MervinPraison c470494d76 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI into develop 2025-06-04 10:32:57 +01:00
Mervin Praison fdf3cac3e7 Merge pull request #596 from MervinPraison/codex/add-mcp-tool-to-agent-creation
Add MCP SSE tooling example
2025-06-04 10:32:06 +01:00
Mervin Praison ec98cd12c8 Merge pull request #597 from DhivyaBharathy-web/add-hackathon-agent-notebook
Add Hackathon Agent Notebook
2025-06-04 10:29:50 +01:00
DhivyaBharathy-web f318ef02a9 Add Hackathon Agent Notebook 2025-06-04 09:19:01 +00:00
claude[bot]andMervinPraison f086566a2d feat: improve MCP SSE tooling with comprehensive error handling and type safety
- Add comprehensive error handling to MCP initialization and tool execution
- Implement resource cleanup mechanisms with close() method and connection state tracking
- Fix interface typo: MCPPToolInfo -> MCPToolInfo
- Add schemaProperties getter to improve type safety in example code
- Prevent re-initialization of MCP client with guard clause
- Add debug logging throughout MCP lifecycle
- Improve example code with proper error handling for network failures
- Add better parameter mapping with object/positional argument support
- Include validation warnings for missing tools and argument mismatches
- Remove unused MCPTool import from example
- Add proper resource cleanup in finally block

These changes address the ENETUNREACH error mentioned in PR description by providing
graceful error handling when the MCP SSE server is unavailable.

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

Co-authored-by: MervinPraison <[email protected]>
2025-06-04 08:23:07 +00:00
Mervin Praison 6de011b69e Add MCP SSE example and dependency 2025-06-04 09:05:08 +01:00
MervinPraison 89d7821bc9 Update test workflow to use custom test runner for 'all' pattern 2025-06-04 07:38:10 +01:00
MervinPraison 9bff7eddbd Update coverage workflow to include installation of duckduckgo_search and knowledge dependencies from praisonai-agents 2025-06-04 07:18:25 +01:00
MervinPraison 82e5f11acf Enhance test workflows by replacing test runner with pytest for improved coverage reporting and adding Codecov upload steps for comprehensive, core, and quick validation tests. 2025-06-04 07:14:18 +01:00
Mervin Praison 0a4aaeb80d Merge pull request #595 from MervinPraison/develop
Update PraisonAI version to 2.2.26 across Dockerfiles and related con…
2025-06-04 07:08:32 +01:00
MervinPraison 70915e2535 Update PraisonAI version to 2.2.26 across Dockerfiles and related configurations 2025-06-04 07:06:23 +01:00
Mervin Praison f35dd76623 Merge pull request #594 from MervinPraison/codex/find-and-fix-bug-in-codebase
Fix redundant tool invocation
2025-06-04 07:03:42 +01:00
Mervin Praison fccd1197a8 Merge pull request #593 from anupamme/fix-yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service-docker-docker-compose.dev.yml-349c
Updated docker/docker-compose.dev.yml to fix security vulnerability [yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service]
2025-06-04 07:00:41 +01:00
Mervin Praisonandcoderabbitai[bot] 9390da7099 Update docker/docker-compose.dev.yml
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-06-04 06:50:43 +01:00
Mervin Praison 8044fd7927 fix duplicate tool execution 2025-06-04 06:48:38 +01:00
anupamme cd5ba2017e fix: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service-docker-docker-compose.dev.yml 2025-06-04 04:56:10 +00:00
Mervin Praison 8c6773b86e Merge pull request #592 from anupamme/fix-yaml.docker-compose.security.no-new-privileges.no-new-privileges-docker-docker-compose.dev.yml-7eaa
Updated docker/docker-compose.dev.yml to fix security vulnerability [yaml.docker-compose.security.no-new-privileges.no-new-privileges]
2025-06-04 05:27:56 +01:00
Mervin Praison 01539581c9 Update docker-compose.dev.yml 2025-06-04 05:27:00 +01:00
Mervin Praison bef8713769 Update docker-compose.dev.yml 2025-06-04 05:26:25 +01:00
Mervin Praisonandcoderabbitai[bot] f84445949e Update docker/docker-compose.dev.yml
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-06-04 05:24:38 +01:00
anupamme 7c74df7cf9 fix: yaml.docker-compose.security.no-new-privileges.no-new-privileges-docker-docker-compose.dev.yml 2025-06-04 04:17:02 +00:00
Mervin Praison f576afa22c Merge pull request #590 from MervinPraison/claude/issue-588-20250603_160140
feat: enhance stateful agents with Session class and convenience methods
2025-06-04 05:04:54 +01:00
claude[bot]andMervinPraison 79c4ef1de3 fix: enhance stateful agents with SQLite compatibility and improved API
- Fix SQLite query compatibility in session state restoration
- Add type safety to increment_state and improve append_to_state
- Change API from session.create_agent() to session.Agent() (backward compatible)
- Clean up code style: remove unused imports, trailing whitespace, fix f-strings
- Fix missing limit parameter in search_knowledge method
- Update examples to use new API

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

Co-authored-by: MervinPraison <[email protected]>
2025-06-04 03:52:09 +00:00
Mervin Praison 47e7c5b272 Delete docs/mint.json 2025-06-03 19:14:08 +01:00
Mervin Praison ec9310b1d1 Delete docs/features/stateful-agents.mdx 2025-06-03 19:13:57 +01:00
Mervin Praison 359bfd3759 Merge pull request #589 from MervinPraison/develop
chore: remove deprecated documentation files
2025-06-03 19:10:18 +01:00
MervinPraison c57e4724c1 chore: remove deprecated documentation files
- Deleted various obsolete documentation files to streamline the codebase.
- Ensured minimal code changes while maintaining the integrity of the remaining documentation.
2025-06-03 19:09:57 +01:00
claude[bot]andClaude 0b4739a6f9 feat: enhance stateful agents with Session class and convenience methods
Add minimal enhancements to PraisonAI's existing stateful capabilities:

- Add Session helper class for unified session management
- Add 9 convenience methods to PraisonAIAgents for enhanced state management
- Add comprehensive stateful agents documentation with examples
- Add 3 practical examples demonstrating session, workflow, and memory capabilities
- Maintain backward compatibility - all existing code continues to work

The implementation leverages existing robust infrastructure (Memory, Agent, Process classes)
rather than duplicating functionality, providing better developer experience through
improved APIs and documentation.

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

Co-Authored-By: Claude <[email protected]>
2025-06-03 16:11:07 +00:00
Mervin Praison e90c78219d Merge pull request #586 from MervinPraison/develop
refactor: streamline test functions in test_scheduler.py
2025-06-03 16:28:49 +01:00
MervinPraison a640f0710d chore: add knowledge dependencies installation in python-package.yml
- Included installation of knowledge dependencies from praisonai-agents in the python-package workflow.
- Ensured minimal code changes while enhancing the functionality of the workflow.
2025-06-03 16:23:14 +01:00
MervinPraison 7216afbf13 chore: add knowledge dependencies installation in unittest.yml
- Included installation of knowledge dependencies from praisonai-agents in the unittest workflow.
- Ensured minimal code changes while enhancing the functionality of the testing process.
2025-06-03 16:15:34 +01:00
MervinPraison 3f7ea07fa2 chore: add knowledge dependencies installation in workflow files
- Included installation of knowledge dependencies from praisonai-agents in test-comprehensive.yml, test-extended.yml, and test-real.yml.
- Ensured minimal code changes while enhancing the functionality of the workflows.
2025-06-03 16:07:34 +01:00
MervinPraison 5d6792762c refactor: enhance test functions and error handling in approval tests
- Updated test functions to use `execute_command` and `write_file` for improved clarity and consistency.
- Added mock patches for auto-approval callbacks to streamline testing processes.
- Enhanced error handling to assert failures directly, ensuring better test reliability.
- Maintained adherence to minimal code change principles while improving overall test structure.
2025-06-03 16:05:22 +01:00
MervinPraison 092113cedd test update 2025-06-03 15:59:32 +01:00
MervinPraison 314eed51d5 refactor: standardise import paths and enhance error handling in test files
- Updated import paths in multiple test files for consistency and clarity.
- Improved error handling in approval tests to assert failures directly.
- Ensured minimal code changes while maintaining existing functionality and readability.
2025-06-03 14:54:41 +01:00
MervinPraison df26978b3c refactor: improve test structure and error handling in approval tests
- Enhanced readability by formatting command execution in `test_agent_with_auto_approval`.
- Updated import path handling in `test_approval_basic` for consistency.
- Simplified error handling in various test functions to assert failures directly.
- Ensured adherence to minimal code change principles while maintaining functionality.
2025-06-03 14:38:15 +01:00
MervinPraison 0ba0a6415c Merge branch 'main' of https://github.com/MervinPraison/PraisonAI into develop 2025-06-03 13:49:26 +01:00
MervinPraison 0bd8e9f535 fix: ensure newline at end of file in test_graph_memory.py
- Added a newline at the end of the file to comply with standard coding practices.
- Maintained existing functionality while adhering to the principle of minimal code change.
2025-06-03 12:43:55 +01:00
MervinPraison 2dc02ed5a6 refactor: enhance test structure in test_scheduler.py
- Simplified test function structure for improved clarity and maintainability.
- Removed redundant error handling to streamline code execution.
- Ensured adherence to minimal code change principles while maintaining functionality.
2025-06-03 12:26:11 +01:00
MervinPraison ea4a2f3b69 refactor: streamline test functions in test_scheduler.py
- Removed unnecessary try-except blocks in test functions for cleaner code.
- Optimised the structure of test cases for better readability and maintainability.
- Ensured consistent import statements and improved error handling in test execution.
- Maintained functionality while adhering to the principle of minimal code change.
2025-06-03 11:25:35 +01:00
Mervin Praison 4df08daf36 Merge pull request #585 from MervinPraison/claude/issue-142-20250603_084931
fix: add Windows compatibility for shell commands in AICoder
2025-06-03 10:17:48 +01:00
Mervin Praisonandcoderabbitai[bot] a156c2e4a2 Update src/praisonai/praisonai/ui/components/aicoder.py
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-06-03 09:59:17 +01:00
claude[bot]andMervinPraison d039c2395b fix: add Windows compatibility for shell commands in AICoder
- Add platform import for OS detection
- Implement get_shell_command() method that wraps commands with 'cmd /c' on Windows
- Update execute_command() to use cross-platform command wrapper
- Fixes issue #142 where Unix commands could fail on Windows systems

Co-authored-by: MervinPraison <[email protected]>
2025-06-03 08:51:16 +00:00
Mervin Praison e6bd8d73e4 Merge pull request #584 from MervinPraison/claude/issue-192-20250603_080328
feat: add Azure OpenAI realtime API support via OPENAI_BASE_URL
2025-06-03 09:46:36 +01:00
Mervin Praison e3e4de9f13 Merge pull request #583 from DhivyaBharathy-web/main
Add FunctionAgent Workflow Notebook to Cookbooks
2025-06-03 09:46:04 +01:00
DhivyaBharathy 25b06caa75 Merge branch 'main' into main 2025-06-03 13:48:09 +05:30
claude[bot]andMervinPraison 0a4470dd17 feat: add Azure OpenAI realtime API support via OPENAI_BASE_URL
Replace Azure-specific environment variables with generic OPENAI_* variables:
- OPENAI_BASE_URL: Custom base URL for Azure OpenAI or other providers
- OPENAI_MODEL_NAME: Model name configuration
- OPENAI_API_KEY: API key (already supported)

Features:
- Automatic WebSocket URL conversion for Azure OpenAI endpoints
- Backward compatibility with existing MODEL_NAME variable
- Enhanced OpenAI client configuration in tools
- Updated documentation with Azure configuration examples

Resolves #192

Co-authored-by: MervinPraison <[email protected]>
2025-06-03 08:06:17 +00:00
DhivyaBharathy b65fae4b38 Update FunctionAgent_Workflow.ipynb 2025-06-03 12:43:38 +05:30
DhivyaBharathy-web aa6ef5a94d Added FunctionAgent_Workflow notebook 2025-06-03 07:07:47 +00:00
Mervin Praison cb551debfe Merge pull request #582 from MervinPraison/develop
Develop
2025-06-03 07:55:41 +01:00
MervinPraison fabd852002 chore: update PraisonAI version to 2.2.25 across Dockerfiles and documentation
- Updated the version of PraisonAI from 2.2.24 to 2.2.25 in all relevant Dockerfiles.
- Adjusted version references in README.md and various documentation files.
- Ensured consistency in package versioning for improved stability and performance.
2025-06-03 07:55:27 +01:00
MervinPraison 99de9f4d4f refactor: replace AsyncAsyncWebCrawler with AsyncWebCrawler in chat.py and code.py
- Updated import statements in chat.py and code.py to use AsyncWebCrawler for consistency.
- Modified default model name in realtime.py to include a specific date for clarity.
- Enhanced connection handling in RealtimeAPI to improve websocket connection checks and error handling.
- Added ensure_connected method in RealtimeClient for better connection management.
- Removed outdated realtimedocs.txt file to streamline the codebase.
2025-06-03 07:53:44 +01:00
Mervin Praison daaf92cbeb Merge pull request #581 from MervinPraison/claude/issue-289-20250603_061712
feat: Add domain context solution using existing features
2025-06-03 07:27:29 +01:00
claude[bot]andMervinPraison d8375cb50b feat: Add domain context solution using existing PraisonAI features
Fixes #289 - Multi-agent context issue

This solution demonstrates how to solve the domain context problem where tools 
default to "example.com" instead of user-specified domains. Uses 4 existing 
PraisonAI features:

1. Custom tool wrappers with domain injection
2. Agent instructions with domain context
3. Task context parameter for domain info
4. Shared memory for context persistence

Key benefits:
- No core SDK changes required
- Uses only existing framework features  
- Multi-layer context reliability
- 100% backward compatible
- Works for hierarchical and other processes

Co-authored-by: MervinPraison <[email protected]>
2025-06-03 06:22:53 +00:00
Mervin Praison 36ea8d381e Merge pull request #577 from DhivyaBharathy-web/add-arxiv-agent-notebook
Add arxiv agent notebook example to cookbooks
2025-06-02 11:49:40 +01:00
DhivyaBharathy 8a8f96e5e5 Update arXiv_agent_notebook.ipynb 2025-06-02 15:53:11 +05:30
DhivyaBharathy 7234587829 Update arXiv_agent_notebook.ipynb 2025-06-02 15:28:47 +05:30
DhivyaBharathy d916d0926a Update arXiv_agent_notebook.ipynb 2025-06-02 15:25:56 +05:30
DhivyaBharathy cd09b2de96 Update arXiv_agent_notebook.ipynb 2025-06-02 15:24:29 +05:30
DhivyaBharathy 58b8ad1969 Add files via upload 2025-06-02 15:22:04 +05:30
DhivyaBharathy-web 5e5b6672eb Add arxiv agent notebook example to cookbooks 2025-06-02 09:16:15 +00:00
Mervin Praison f7ce10b92e Merge pull request #566 from MervinPraison/claude/issue-12-20250601_032826
feat: Add human-in-the-loop approval system for dangerous tool operations
2025-06-02 09:42:59 +01:00
Mervin Praison eead19802d Merge pull request #576 from DhivyaBharathy-web/main
Add DuckDuckGo PraisonAI Agent Notebook
2025-06-02 09:40:25 +01:00
MervinPraison 208c8aad3b feat: enhance approval system with context-aware auto-approval
This commit introduces a context-aware auto-approval mechanism for the approval system, allowing non-interactive execution in CI environments. It modifies the test files to include a skip condition for interactive approvals and updates the approval callback logic to support automatic approvals when user input is not required.

Files modified:
- Updated test_approval_agent_integration.py to include auto-approval logic
- Updated test_approval_basic.py to include skip condition for interactive tests
- Updated test_approval_interactive.py to include auto-approval logic
- Enhanced approval.py with context management for approval tracking
- Modified agent.py to prevent double approval in context

This change improves the usability of the approval system in automated workflows while maintaining security.
2025-06-02 09:35:09 +01:00
DhivyaBharathy fb2b086dd5 Update DuckDuckGo_PraisonAI_Agent_Notebook.ipynb 2025-06-02 13:44:41 +05:30
DhivyaBharathy 75972372a6 Update DuckDuckGo_PraisonAI_Agent_Notebook.ipynb 2025-06-02 12:29:34 +05:30
DhivyaBharathy-web 108053bb32 Add DuckDuckGo PraisonAI Agent Notebook 2025-06-02 06:37:45 +00:00
MervinPraison fbddda54ba fix: update import paths in approval agent test files
This commit modifies the import paths in the test files for the approval agent to ensure they correctly reference the local development path. The changes streamline the path structure for better integration with the existing codebase.

Files modified:
- Updated import paths in test_approval_agent_integration.py
- Updated import paths in test_approval_basic.py
- Updated import paths in test_approval_interactive.py
2025-06-01 07:16:28 +01:00
MervinPraison 83427ca929 chore: remove obsolete test_approval_basic.py file
This commit deletes the outdated test_approval_basic.py file, which contained basic tests for the human approval system. The tests are no longer necessary as the functionality has been integrated into other components.

Files modified:
- Deleted test_approval_basic.py
2025-06-01 07:15:18 +01:00
Mervin Praison 36e5047e53 Merge pull request #574 from MervinPraison/claude/issue-444-20250601_050501
fix: resolve Knowledge RAG errors with mem0 API compatibility
2025-06-01 06:23:50 +01:00
claude[bot]andMervinPraison 05d8136433 fix: resolve Knowledge RAG errors with mem0 API compatibility
- Fix CustomMemory._add_to_vector_store method signature to support optional parameters with defaults
- Add backward compatibility for different message formats  
- Update memory.add() call to use correct messages format for mem0 API
- Add fallback mechanism to support both new and legacy API formats
- Resolves "takes 4 positional arguments but 5 were given" error
- Resolves "missing 1 required positional argument: 'infer'" error

Fixes #444

Co-authored-by: MervinPraison <[email protected]>
2025-06-01 05:09:01 +00:00
Mervin Praison af9b251b59 Merge pull request #573 from MervinPraison/claude/issue-107-20250601_045023
feat: integrate Mem0 graph memory support
2025-06-01 06:02:44 +01:00
Mervin Praison c8a6744469 Rename test_graph_memory.py to src/praisonai/tests/unit/test_graph_memory.py 2025-06-01 06:01:31 +01:00
claude[bot]andMervinPraison 678fd462c3 feat: integrate Mem0 graph memory support
- Add graph memory configuration support to Memory class
- Enhanced Knowledge class with graph store support  
- Added optional graph dependency group in pyproject.toml
- Comprehensive examples demonstrating graph memory usage
- Maintained full backward compatibility
- Added test scripts to verify implementation

Supports Neo4j and Memgraph as graph store providers.
Install with: pip install "praisonaiagents[graph]"

Co-authored-by: MervinPraison <[email protected]>
2025-06-01 04:56:24 +00:00
Mervin Praison ba03a0d893 Merge pull request #572 from MervinPraison/claude/issue-421-20250531_210257
feat: support LiteLLM provider-specific parameters
2025-06-01 05:42:39 +01:00
Mervin Praison 3be4c4c70e Merge pull request #571 from MervinPraison/develop
chore: update PraisonAI version to 2.2.24 across Dockerfiles and docu…
2025-06-01 05:38:39 +01:00
MervinPraison 709640240f chore: update PraisonAI version to 2.2.24 across Dockerfiles and documentation
- Updated the version of PraisonAI from 2.2.23 to 2.2.24 in all relevant Dockerfiles.
- Adjusted version references in README.md and various documentation files.
- Ensured consistency in package versioning for improved stability and performance.
2025-06-01 05:36:48 +01:00
Mervin Praison 93d526eb7b Merge pull request #570 from MervinPraison/claude/issue-122-20250601_041558
feat: add --merge CLI parameter for merging agents.yaml files
2025-06-01 05:33:20 +01:00
Mervin Praison 624a2cfa17 Merge pull request #567 from MervinPraison/claude/issue-121-20250531_210355
fix: prevent CLI conflicts when PraisonAI is used as library
2025-06-01 05:30:06 +01:00
Mervin Praison 4d2a6a2e2e Merge pull request #569 from MervinPraison/claude/issue-466-20250601_041120
feat: Add Mem0 built-in reranker support to Knowledge Agent
2025-06-01 05:29:01 +01:00
claude[bot]andMervinPraison a1bdb056a0 refactor: use argparse.Namespace instead of custom DefaultArgs class
Replace the custom DefaultArgs class with argparse.Namespace for better 
maintainability and consistency with argparse conventions. This addresses
the code review suggestion to use idiomatic Python patterns and avoid
duplication of argument handling logic.

Co-authored-by: MervinPraison <[email protected]>
2025-06-01 04:27:44 +00:00
Mervin Praison b4a6401bae Merge pull request #568 from MervinPraison/claude/issue-460-20250601_040421
fix: resolve MCP function signature parameter ordering issue
2025-06-01 05:25:20 +01:00
claude[bot]andMervinPraison 772ce7d2e2 feat: add --merge CLI parameter for merging agents.yaml files
- Add --merge flag to CLI with description for merging behavior
- Default behavior remains overwrite (backwards compatible)
- When --merge is used, preserves existing agents and adds new ones
- Implements intelligent conflict resolution by renaming duplicates
- Combines topics when both existing and new topics are present
- Added comprehensive error handling for invalid YAML files

Usage:
- praisonai --init "topic" (overwrites existing agents.yaml)
- praisonai --init "topic" --merge (merges with existing agents.yaml)

Co-authored-by: MervinPraison <[email protected]>
2025-06-01 04:19:11 +00:00
claude[bot]andMervinPraison 20c2d28f35 feat: Add Mem0 built-in reranker support to Knowledge Agent
- Add rerank parameter to Knowledge.search() method with backward compatibility
- Update memory search methods to pass rerank parameter to Mem0
- Add reranker configuration options with enabled/default_rerank settings
- Support all Mem0 advanced retrieval options (keyword_search, filter_memories)
- Create comprehensive example demonstrating reranker usage and performance
- Maintains full backward compatibility - existing code works unchanged
- Addresses issue #466 for improved RAG relevance with minimal latency impact

Co-authored-by: MervinPraison <[email protected]>
2025-06-01 04:14:24 +00:00
claude[bot]andMervinPraison f8589e4363 fix: resolve MCP function signature parameter ordering issue
Fix ValueError "non-default argument follows default argument" in MCP tool 
wrapper creation by ensuring required parameters come before optional 
parameters in function signatures.

- Separate required and optional parameters during signature creation
- Maintain backward compatibility and preserve all functionality
- Resolves GitHub MCP server initialization failures

Fixes #460

Co-authored-by: MervinPraison <[email protected]>
2025-06-01 04:05:36 +00:00
claude[bot]andMervinPraison 97d368d2e2 feat: Add human-in-the-loop approval system for dangerous tool operations
Implements human approval framework for dangerous operations like shell commands,
code execution, and file operations to enhance security and user control.

Key features:
- @require_approval decorator for marking dangerous tools  
- Risk-based approval (critical, high, medium, low)
- Console approval interface with rich formatting
- Custom approval callbacks for automated policies
- Async/sync support for all workflows
- Runtime configuration of approval requirements

Protected operations:
- Critical: execute_command, kill_process, execute_code
- High: write_file, delete_file, move_file, copy_file
- Medium: evaluate, crawl, scrape_page

Files modified:
- New approval.py module with core framework
- Enhanced main.py with approval callback support
- Modified agent.py to check approvals before tool execution
- Added @require_approval decorators to dangerous tools
- Comprehensive example and test implementations

Resolves: #12

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

Co-Authored-By: MervinPraison <[email protected]>
2025-06-01 03:42:06 +00:00
Mervin Praison 49d9d40199 Merge pull request #565 from MervinPraison/claude/issue-97-20250531_205330
fix: implement litellm handling in code.py same as llm.py
2025-06-01 04:27:46 +01:00
claude[bot]andMervinPraison 445cc037ce fix: prevent CLI conflicts when PraisonAI is used as library
Adds minimal detection in parse_args() to skip CLI parsing when imported
as a library (e.g., by Fabric). Returns default args instead of trying
to parse external application's CLI arguments.

- Only 20 lines added to fix the specific Fabric compatibility issue
- Zero breaking changes - all existing CLI and library usage preserved
- Addresses the root cause from issue #121

Co-authored-by: MervinPraison <[email protected]>
2025-05-31 21:07:12 +00:00
claude[bot]andMervinPraison c4e7b7dc7f feat: support LiteLLM provider-specific parameters
- Add extra_settings to LLM completion parameters
- Enables passing Ollama num_ctx and other provider params
- Maintains backward compatibility
- Addresses issue #421

Co-authored-by: MervinPraison <[email protected]>
2025-05-31 21:05:41 +00:00
claude[bot]andMervinPraison 9e7c172f55 fix: implement litellm handling in code.py same as llm.py
Apply minimal changes to fix LiteLLM provider error:
- Add litellm configuration with drop_params and modify_params
- Add _build_completion_params() helper function
- Update acompletion calls to use proper parameter handling

This prevents "list index out of range" errors when using model names
like "gemini" without provider prefix by leveraging litellm's built-in
parameter validation and modification capabilities.

Fixes #97

Co-authored-by: MervinPraison <[email protected]>
2025-05-31 20:55:14 +00:00
Mervin Praison d89570b085 Merge pull request #564 from MervinPraison/develop
chore: update PraisonAI version to 2.2.23 across Dockerfiles and docu…
2025-05-31 17:09:32 +01:00
MervinPraison ee5dfddccd chore: update PraisonAI version to 2.2.23 across Dockerfiles and documentation
- Updated the PraisonAI version from 2.2.22 to 2.2.23 in all relevant Dockerfiles.
- Adjusted version references in README.md, local-development.mdx, and other documentation files.
- Ensured consistency in versioning for deployment scripts and project files.

This change maintains compatibility with the latest features and fixes in PraisonAI.
2025-05-31 17:08:37 +01:00
Mervin Praison a3bfc6f795 Merge pull request #563 from MervinPraison/claude/issue-459-20250531_155633
fix: resolve MCP tools not working in Streamlit applications (issue #459)
2025-05-31 17:05:57 +01:00
Mervin Praison ebc130854d Merge pull request #562 from MervinPraison/claude/issue-5-20250531_154718
feat: add deployment scheduling functionality
2025-05-31 17:04:49 +01:00
Mervin Praison f40a5c1359 Rename schedule_config.yaml.example to src/praisonai/schedule_config.yaml.example 2025-05-31 17:04:06 +01:00
Mervin Praison 3284f7bbc6 Rename test_scheduler.py to src/praisonai/tests/unit/test_scheduler.py 2025-05-31 17:03:34 +01:00
claude[bot]andMervinPraison 87928611f7 fix: resolve MCP tools not working in Streamlit applications (issue #459)
This commit provides working examples and comprehensive documentation for using MCP tools with Streamlit, without modifying core MCP implementation.

Key fixes:
- Proper session state management to prevent agent re-initialization
- Use standard LLM format instead of provider/model format
- Comprehensive error handling and user feedback
- Working examples with troubleshooting guidance

Files added:
- examples/python/ui/mcp-streamlit-airbnb.py - Complete working Streamlit app
- examples/python/ui/mcp-streamlit-simple.py - Simple fixed version of original code
- docs/ui/streamlit/mcp-streamlit.mdx - Comprehensive documentation and troubleshooting

The root issue was improper usage patterns in Streamlit, not the core MCP implementation.

Co-authored-by: MervinPraison <[email protected]>

🤖 Generated with [Claude Code](https://claude.ai/code)
2025-05-31 15:59:21 +00:00
Mervin Praison 2727bf5992 Merge pull request #561 from MervinPraison/claude/issue-170-20250531_154607
fix: resolve crawling NoneType concatenation error in realtime tools
2025-05-31 16:58:03 +01:00
claude[bot]andMervinPraison 45d04163c3 feat: add deployment scheduling functionality
- Add DeploymentScheduler with provider-agnostic design
- Support interval-based scheduling (daily, hourly, */6h, 3600s)
- CLI integration with --schedule and --schedule-config options
- Backward compatible with existing --deploy behavior
- Thread-safe scheduler with retry mechanism
- Example configuration file for scheduled deployments
- Test suite for validation

Addresses issue #5: --deploy schedule runs

Co-authored-by: MervinPraison <[email protected]>
2025-05-31 15:53:57 +00:00
claude[bot]andMervinPraison 477d0d2e26 fix: resolve crawling NoneType concatenation error in realtime tools
- Fix "can only concatenate str (not "NoneType") to str" error in web crawling
- Update process_tavily_results and fallback_to_duckduckgo to use proper async patterns
- Add null checks for crawl_result.markdown to prevent NoneType errors
- Use async context manager with AsyncWebCrawler and await crawler.arun()
- Match the working async pattern used in chat.py

Fixes #170

Co-authored-by: MervinPraison <[email protected]>
2025-05-31 15:48:02 +00:00
Mervin Praison 77394f5e5f Merge pull request #560 from MervinPraison/develop
Develop
2025-05-31 16:44:03 +01:00
MervinPraison 29e533c18c chore: remove unsloth training dependency from pyproject.toml
- Cleared the train dependencies list by removing unsloth[colab-new]>=2024.11.7.
- Commented out the unsloth dependency to maintain a record without affecting functionality.
2025-05-31 16:43:46 +01:00
MervinPraison 48dbea0566 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI into develop 2025-05-31 12:42:45 +01:00
Mervin Praison 969d6697e1 Merge pull request #559 from MervinPraison/claude/issue-232-20250531_060542
fix: add dependency check for train command to prevent confusing errors
2025-05-31 12:42:22 +01:00
Mervin Praisonandcoderabbitai[bot] 787d2508b1 Update src/praisonai/pyproject.toml
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2025-05-31 12:41:18 +01:00
claude[bot]andMervinPraison ec42dc92e4 feat: add unsloth training dependencies to pyproject.toml
- Add train optional dependencies with unsloth[colab-new]>=2024.11.7
- Update Poetry extras to include unsloth for train command
- Enables pip install "praisonai[train]" for training dependencies
- Maintains backward compatibility

Co-authored-by: MervinPraison <[email protected]>
2025-05-31 10:45:40 +00:00
claude[bot]andMervinPraison 5b7bae2f43 fix: add dependency check for train command to prevent confusing errors
- Add TRAIN_AVAILABLE flag to track unsloth dependency availability
- Add dependency validation in both parse_args() and main() methods
- Show clear error message with installation instructions when dependencies missing
- Follow same pattern as other commands (chat, code, call, realtime) for consistency
- Fixes issue where train command would show "train not available" without helpful context

Resolves #232

Co-authored-by: MervinPraison <[email protected]>
2025-05-31 06:07:31 +00:00
MervinPraison 69a1efac47 fix(tests): update expected name in tool call parsing test for malformed JSON
- Changed the expected function name in the test for malformed JSON from 'hello_world' to 'unknown_function' to reflect correct error handling behaviour.
- Adjusted the Python path in the test file to point to the correct source directory for the praisonai-agents module.
2025-05-31 06:51:09 +01:00
489 changed files with 42992 additions and 66356 deletions

No files matched your search

@@ -0,0 +1,9 @@
FROM node:20-alpine
RUN npm install -g @anthropic-ai/claude-code
WORKDIR /app
COPY entrypoint.sh .
RUN chmod +x entrypoint.sh
ENTRYPOINT ["/app/entrypoint.sh"]
@@ -0,0 +1,20 @@
name: "Claude Code Action"
description: "Custom Claude Code runner for PraisonAI"
inputs:
anthropic_api_key:
required: true
description: "Anthropic API key"
github_token:
required: true
description: "GitHub token for repo access"
runs:
using: "docker"
image: "ghcr.io/mervinpraison/praisonai-claudecode:latest"
env:
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
GITHUB_TOKEN: ${{ inputs.github_token }}
args:
- "--anthropic-api-key=${{ inputs.anthropic_api_key }}"
- "--github-token=${{ inputs.github_token }}"
@@ -0,0 +1,21 @@
#!/bin/sh
set -e
echo "Running Claude Code in CI mode..."
# Extract GitHub context and create a smart prompt
PROMPT="Analyse the GitHub issue or PR context and generate a smart response based on the repository context."
# Set environment variables from arguments
export ANTHROPIC_API_KEY="${1#--anthropic-api-key=}"
export GITHUB_TOKEN="${2#--github-token=}"
# Verify environment variables
if [ -z "$ANTHROPIC_API_KEY" ] || [ -z "$GITHUB_TOKEN" ]; then
echo "Error: Required environment variables are not set"
exit 1
fi
# Run Claude with the prompt
claude -p "$PROMPT"
+117
View File
@@ -0,0 +1,117 @@
name: "Claude Code Action"
description: "Run Claude Code in GitHub Actions workflows"
inputs:
github_token:
description: "GitHub token with repo and issues permissions"
required: true
anthropic_api_key:
description: "Anthropic API key"
required: true
prompt:
description: "The prompt to send to Claude Code"
required: false
default: ""
prompt_file:
description: "Path to a file containing the prompt to send to Claude Code"
required: false
default: ""
allowed_tools:
description: "Comma-separated list of allowed tools for Claude Code to use"
required: false
default: ""
output_file:
description: "File to save Claude Code output to (optional)"
required: false
default: ""
timeout_minutes:
description: "Timeout in minutes for Claude Code execution"
required: false
default: "10"
install_github_mcp:
description: "Whether to install the GitHub MCP server"
required: false
default: "false"
runs:
using: "composite"
steps:
- name: Install Claude Code
shell: bash
run: npm install -g @anthropic-ai/claude-code
- name: Install GitHub MCP Server
if: inputs.install_github_mcp == 'true'
shell: bash
run: |
claude mcp add-json github '{
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/github/github-mcp-server:sha-ff3036d"
],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ inputs.GITHUB_TOKEN }}"
}
}'
- name: Prepare Prompt File
shell: bash
id: prepare_prompt
run: |
if [ -z "${{ inputs.prompt }}" ] && [ -z "${{ inputs.prompt_file }}" ]; then
echo "::error::Neither 'prompt' nor 'prompt_file' was provided. At least one is required."
exit 1
fi
if [ ! -z "${{ inputs.prompt_file }}" ]; then
if [ ! -f "${{ inputs.prompt_file }}" ]; then
echo "::error::Prompt file '${{ inputs.prompt_file }}' does not exist."
exit 1
fi
PROMPT_PATH="${{ inputs.prompt_file }}"
else
mkdir -p /tmp/claude-action
PROMPT_PATH="/tmp/claude-action/prompt.txt"
echo "${{ inputs.prompt }}" > "$PROMPT_PATH"
fi
if [ ! -s "$PROMPT_PATH" ]; then
echo "::error::Prompt is empty. Please provide a non-empty prompt."
exit 1
fi
echo "PROMPT_PATH=$PROMPT_PATH" >> $GITHUB_ENV
- name: Run Claude Code
shell: bash
id: run_claude
run: |
timeout_seconds=$((${{ inputs.timeout_minutes }} * 60))
if [ -z "${{ inputs.output_file }}" ]; then
timeout $timeout_seconds claude \
-p \
--verbose \
--output-format stream-json \
"$(cat ${{ env.PROMPT_PATH }})" \
${{ inputs.allowed_tools != '' && format('--allowedTools "{0}"', inputs.allowed_tools) || '' }}
else
timeout $timeout_seconds claude \
-p \
--verbose \
--output-format stream-json \
"$(cat ${{ env.PROMPT_PATH }})" \
${{ inputs.allowed_tools != '' && format('--allowedTools "{0}"', inputs.allowed_tools) || '' }} | tee output.txt
jq -s '.' output.txt > output.json
jq -r '.[-1].result' output.json > "${{ inputs.output_file }}"
echo "Complete output saved to output.json, final response saved to ${{ inputs.output_file }}"
fi
env:
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
GITHUB_TOKEN: ${{ inputs.github_token }}
+39
View File
@@ -0,0 +1,39 @@
name: Build Claude Code Image
on:
workflow_dispatch:
inputs:
version:
description: 'Image version tag'
required: true
default: 'latest'
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: ./.github/actions/claude-code-action
push: true
tags: ghcr.io/mervinpraison/praisonai-claudecode:${{ inputs.version }}
cache-from: type=gha
cache-to: type=gha,mode=max
provenance: false
+46 -1
View File
@@ -23,15 +23,60 @@ jobs:
pull-requests: read
issues: read
id-token: write
packages: read
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Debug Environment
run: |
echo "=== Environment Debug ==="
echo "GITHUB_ACTOR: $GITHUB_ACTOR"
echo "GITHUB_REPOSITORY: $GITHUB_REPOSITORY"
echo "GITHUB_REPOSITORY_OWNER: $GITHUB_REPOSITORY_OWNER"
echo "GITHUB_TOKEN exists: $([ -n "$GITHUB_TOKEN" ] && echo "yes" || echo "no")"
echo "GITHUB_TOKEN length: ${#GITHUB_TOKEN}"
- name: Check Package Visibility
run: |
echo "=== Checking Package Visibility ==="
curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/users/MervinPraison/packages/container/praisonai-claudecode" \
|| echo "Package API call failed"
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Test Docker Authentication
run: |
echo "=== Testing Docker Authentication ==="
echo "Checking ~/.docker/config.json"
cat ~/.docker/config.json | jq '.' || echo "No docker config found"
echo "=== Testing Registry Access ==="
curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
"https://ghcr.io/v2/" || echo "Registry access failed"
- name: Test Docker Pull
run: |
echo "=== Testing Docker Pull ==="
echo "Attempting to pull image: ghcr.io/mervinpraison/praisonai-claudecode:latest"
docker pull ghcr.io/mervinpraison/praisonai-claudecode:latest || echo "Pull failed with exit code: $?"
echo "=== Checking Docker Images ==="
docker images | grep praisonai-claudecode || echo "No images found"
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@beta
uses: ./.github/actions/claude-code-action
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
+60
View File
@@ -0,0 +1,60 @@
name: Run tests and upload coverage
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
test:
name: Run tests and collect coverage
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 2
- 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: |
cd src/praisonai
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-cov pytest-asyncio
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
- 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 "LOGLEVEL=DEBUG" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
- name: Run tests
run: |
cd src/praisonai
pytest --cov=praisonai --cov-branch --cov-report=xml tests/unit/
- name: Upload results to Codecov
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
file: src/praisonai/coverage.xml
flags: unit-tests
name: unit-tests-coverage
fail_ci_if_error: false
verbose: true
+3 -1
View File
@@ -40,6 +40,8 @@ jobs:
python -m pip install ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
python -m pip install duckduckgo_search
python -m pip install pytest-asyncio pytest-cov
# Install knowledge dependencies from praisonai-agents
python -m pip install "praisonaiagents[knowledge]"
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Debug API Key Status
@@ -63,4 +65,4 @@ jobs:
# flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
cd src/praisonai && python -m pytest
cd src/praisonai && python tests/test_runner.py --pattern fast
+17 -5
View File
@@ -51,6 +51,8 @@ jobs:
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
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
- name: Set environment variables
run: |
@@ -67,10 +69,10 @@ jobs:
case $TEST_TYPE in
"unit")
cd src/praisonai && python tests/test_runner.py --pattern unit
cd src/praisonai && python -m pytest tests/unit/ -v --tb=short --disable-warnings --cov=praisonai --cov-report=xml --cov-branch
;;
"integration")
cd src/praisonai && python tests/test_runner.py --pattern integration
cd src/praisonai && python -m pytest tests/integration/ -v --tb=short --disable-warnings --cov=praisonai --cov-report=xml --cov-branch
;;
"fast")
cd src/praisonai && python tests/test_runner.py --pattern fast
@@ -137,6 +139,16 @@ jobs:
echo "- 🔌 MCP server connections" >> comprehensive_report.md
echo "- 💬 LLM integrations (OpenAI, Anthropic, etc.)" >> comprehensive_report.md
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
file: src/praisonai/coverage.xml
flags: comprehensive-tests
name: comprehensive-tests-coverage
fail_ci_if_error: false
verbose: true
- name: Upload Comprehensive Test Results
uses: actions/upload-artifact@v4
if: always()
@@ -144,9 +156,9 @@ jobs:
name: comprehensive-test-results-python-${{ matrix.python-version }}
path: |
comprehensive_report.md
htmlcov/
coverage.xml
.coverage
src/praisonai/htmlcov/
src/praisonai/coverage.xml
src/praisonai/.coverage
retention-days: 30
test-matrix-summary:
+18 -4
View File
@@ -34,6 +34,8 @@ jobs:
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
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
- name: Set environment variables
run: |
@@ -193,7 +195,7 @@ jobs:
- name: Run Unit Tests
run: |
cd src/praisonai && python -m pytest tests/unit/ -v --tb=short --disable-warnings --cov=praisonai --cov-report=term-missing
cd src/praisonai && python -m pytest tests/unit/ -v --tb=short --disable-warnings --cov=praisonai --cov-report=term-missing --cov-report=xml --cov-branch
- name: Run Integration Tests
run: |
@@ -261,12 +263,24 @@ jobs:
export OPENAI_MODEL_NAME="$OPENAI_MODEL_NAME"
cd src/praisonai && python -m pytest tests/test.py -v --tb=short --disable-warnings
- name: Upload Coverage Reports
- name: Upload coverage reports to Codecov
if: matrix.python-version == '3.11'
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
file: src/praisonai/coverage.xml
flags: core-tests
name: core-tests-coverage
fail_ci_if_error: false
verbose: true
- name: Upload Coverage Reports (Artifacts)
if: matrix.python-version == '3.11'
uses: actions/upload-artifact@v4
with:
name: coverage-reports
path: |
.coverage
htmlcov/
src/praisonai/.coverage
src/praisonai/htmlcov/
src/praisonai/coverage.xml
retention-days: 7
+4
View File
@@ -34,6 +34,8 @@ jobs:
cd src/praisonai
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system duckduckgo_search
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
- name: Set environment variables
run: |
@@ -92,6 +94,8 @@ jobs:
cd src/praisonai
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
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
- name: Run Performance Benchmarks
run: |
+2
View File
@@ -58,6 +58,8 @@ jobs:
cd src/praisonai
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
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
- name: Set environment variables
run: |
+14 -2
View File
@@ -27,6 +27,8 @@ jobs:
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
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
- name: Set environment variables
run: |
@@ -469,8 +471,8 @@ jobs:
- name: Run Fast Tests
run: |
# Run the fastest, most essential tests
cd src/praisonai && python tests/test_runner.py --pattern fast
# Run the fastest, most essential tests with coverage
cd src/praisonai && python -m pytest tests/unit/test_core_agents.py -v --tb=short --disable-warnings --cov=praisonai --cov-report=xml --cov-branch
- name: Run Real API Tests
run: |
@@ -489,6 +491,16 @@ jobs:
cd src/praisonai && python -m pytest tests/test.py -v --tb=short --disable-warnings
continue-on-error: true
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
file: src/praisonai/coverage.xml
flags: quick-validation
name: quick-validation-coverage
fail_ci_if_error: false
verbose: true
- name: Restore Root Config Files
run: |
echo "🔄 Restoring root configuration files..."
+2 -1
View File
@@ -74,4 +74,5 @@ agents/praisonaiagents/praisonaiagents.egg-info
.praison
# Local Netlify folder
.netlify
.qodo
.qodo
CopilotKit*
+1 -1
View File
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
flask \
"praisonai>=2.2.22" \
"praisonai>=2.2.33" \
"praisonai[api]" \
gunicorn \
markdown
+1 -1
View File
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=2.2.22" \
"praisonai>=2.2.33" \
"praisonai[chat]" \
"embedchain[github,youtube]"
+1 -1
View File
@@ -20,7 +20,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=2.2.22" \
"praisonai>=2.2.33" \
"praisonai[ui]" \
"praisonai[chat]" \
"praisonai[realtime]" \
+1 -1
View File
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=2.2.22" \
"praisonai>=2.2.33" \
"praisonai[ui]" \
"praisonai[crewai]"
+2 -2
View File
@@ -121,7 +121,7 @@ healthcheck:
## 📦 Package Versions
All Docker images use consistent, up-to-date versions:
- PraisonAI: `>=2.2.22`
- PraisonAI: `>=2.2.33`
- PraisonAI Agents: `>=0.0.92`
- Python: `3.11-slim`
@@ -218,7 +218,7 @@ docker-compose up -d
### Version Pinning
To use specific versions, update the Dockerfile:
```dockerfile
RUN pip install "praisonai==2.2.22" "praisonaiagents==0.0.92"
RUN pip install "praisonai==2.2.33" "praisonaiagents==0.0.92"
```
## 🌐 Production Deployment
+18 -1
View File
@@ -129,12 +129,29 @@ services:
# Standalone database for development
database:
security_opt:
- "no-new-privileges:true"
image: postgres:15-alpine
environment:
POSTGRES_DB: praisonai_dev
POSTGRES_USER: praisonai
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-praisonai_dev_pass}
volumes:
database:
image: postgres:15-alpine
environment:
POSTGRES_DB: praisonai_dev
POSTGRES_USER: praisonai
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-praisonai_dev_pass}
volumes:
- postgres_data:/var/lib/postgresql/data
read_only: true
tmpfs:
- /tmp
- /var/tmp
ports:
- "5432:5432"
networks:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
@@ -181,4 +198,4 @@ volumes:
networks:
praison_network:
driver: bridge
driver: bridge
-23
View File
@@ -1,23 +0,0 @@
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the OS, Python version and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.12"
jobs:
post_install:
- bash docs/generate_docs.sh
mkdocs:
configuration: mkdocs.yml
fail_on_warning: true
python:
install:
- requirements: docs/requirements.txt
-1
View File
@@ -1 +0,0 @@
docs.praison.ai
-20
View File
@@ -1,20 +0,0 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
-124
View File
@@ -1,124 +0,0 @@
---
title: "AI Agents"
description: "Overview of all available PraisonAI agents and their capabilities"
icon: "robot"
---
PraisonAI provides a diverse set of specialized agents for various tasks. Each agent is designed with specific capabilities and tools to handle different types of tasks effectively.
```mermaid
graph LR
%% Define the main flow
Start([▶ Start]) --> Agent1
Agent1 --> Process[⚙ Process]
Process --> Agent2
Agent2 --> Output([✓ Output])
Process -.-> Agent1
%% Define subgraphs for agents and their tasks
subgraph Agent1[ ]
Task1[📋 Task]
AgentIcon1[🤖 AI Agent]
Tools1[🔧 Tools]
Task1 --- AgentIcon1
AgentIcon1 --- Tools1
end
subgraph Agent2[ ]
Task2[📋 Task]
AgentIcon2[🤖 AI Agent]
Tools2[🔧 Tools]
Task2 --- AgentIcon2
AgentIcon2 --- Tools2
end
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Start,Output,Task1,Task2 input
class Process,AgentIcon1,AgentIcon2 process
class Tools1,Tools2 tools
class Agent1,Agent2 transparent
```
## Data & Analysis
<CardGroup cols={2}>
<Card title="Data Analyst" icon="chart-line" href="/agents/data-analyst">
Analyze data from various sources, create visualizations, and generate insights.
</Card>
<Card title="Finance" icon="money-bill-trend-up" href="/agents/finance">
Track stocks, analyze financial data, and provide investment recommendations.
</Card>
<Card title="Research" icon="magnifying-glass-chart" href="/agents/research">
Conduct comprehensive research and analysis across various topics.
</Card>
<Card title="Wikipedia" icon="book" href="/agents/wikipedia">
Search and extract information from Wikipedia articles.
</Card>
</CardGroup>
## Media & Content
<CardGroup cols={2}>
<Card title="Image Analysis" icon="image" href="/agents/image">
Analyze and understand visual content from images.
</Card>
<Card title="Image to Text" icon="text" href="/agents/image-to-text">
Convert images to textual descriptions and extract text content.
</Card>
<Card title="Video" icon="video" href="/agents/video">
Analyze video content and extract meaningful information.
</Card>
<Card title="Markdown" icon="markdown" href="/agents/markdown">
Generate and format content in Markdown syntax.
</Card>
</CardGroup>
## Search & Recommendations
<CardGroup cols={2}>
<Card title="Web Search" icon="globe" href="/agents/websearch">
Perform intelligent web searches and gather information.
</Card>
<Card title="Recommendation" icon="thumbs-up" href="/agents/recommendation">
Generate personalized recommendations based on preferences.
</Card>
<Card title="Shopping" icon="shop" href="/agents/shopping">
Compare prices and find the best deals across stores.
</Card>
<Card title="Planning" icon="calendar" href="/agents/planning">
Create travel plans and detailed itineraries.
</Card>
</CardGroup>
## Development
<CardGroup cols={2}>
<Card title="Programming" icon="code" href="/agents/programming">
Write, analyze, and debug code across multiple languages.
</Card>
<Card title="Single Agent" icon="circle-1" href="/agents/single">
Simple, focused agent for basic tasks without external tools.
</Card>
</CardGroup>
## Getting Started
Each agent can be easily initialized and customized for your specific needs. Here's a basic example:
```python
from praisonaiagents import Agent
# Create an agent with specific instructions
agent = Agent(instructions="Your task-specific instructions")
# Start the agent with a task
response = agent.start("Your task description")
```
For more detailed information about each agent, click on the respective cards above.
-120
View File
@@ -1,120 +0,0 @@
---
title: "Data Analyst Agent"
sidebarTitle: "Data Analyst"
description: "Learn how to create AI agents for data analysis and insights generation."
icon: "chart-line"
---
```mermaid
flowchart LR
In[Data Source] --> Reader[Data Reader]
Reader --> Analyzer[Data Analyzer]
Analyzer --> Generator[Insights Generator]
Generator --> Out[Output]
style In fill:#8B0000,color:#fff
style Reader fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Data Analyst Agent can read data from various sources, analyze it, and generate insights.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `data_analysis.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import (
read_csv, read_excel, write_csv, write_excel,
filter_data, get_summary, group_by, pivot_table
)
agent = Agent(
instructions="You are a Data Analyst Agent",
tools=[
read_csv, read_excel, write_csv, write_excel,
filter_data, get_summary, group_by, pivot_table
]
)
# Start analysis with a specific task
agent.start(f"""
Read the data from the csv file {os.path.join(os.path.dirname(__file__), "tesla-stock-price.csv")}
Analyse the data and give me the insights
read_csv to read the file
""")
```
</Step>
</Steps>
## Understanding Data Analysis Workflow
The Data Analyst Agent is designed to perform comprehensive data analysis tasks using a suite of specialized tools. Here's how it works:
1. **Data Reading**: The agent can read data from various sources:
- CSV files using `read_csv`
- Excel files using `read_excel`
2. **Data Analysis**: Multiple analysis tools are available:
- `filter_data`: Filter datasets based on conditions
- `get_summary`: Generate statistical summaries
- `group_by`: Group data by specific columns
- `pivot_table`: Create pivot tables for analysis
3. **Data Export**: Results can be exported to:
- CSV format using `write_csv`
- Excel format using `write_excel`
## Features
<CardGroup cols={2}>
<Card title="Multiple Data Sources" icon="table">
Support for both CSV and Excel file formats.
</Card>
<Card title="Analysis Tools" icon="calculator">
Comprehensive suite of analysis tools including filtering, summarization, and pivoting.
</Card>
<Card title="Data Export" icon="file-export">
Export capabilities to various formats.
</Card>
<Card title="Automated Insights" icon="lightbulb">
Automatic generation of data insights and patterns.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Analyzing stock data
agent.start("""
1. Read 'stock_data.csv'
2. Filter data for the last 30 days
3. Calculate daily returns
4. Generate summary statistics
5. Export results to 'analysis_results.xlsx'
""")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex analysis workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
- Check out other specialized agents like the [Finance Agent](/agents/finance) for specific use cases
-97
View File
@@ -1,97 +0,0 @@
---
title: "Finance Agent"
sidebarTitle: "Finance"
description: "Learn how to create AI agents for financial analysis and investment recommendations."
icon: "money-bill-trend-up"
---
```mermaid
flowchart LR
In[Request] --> Price[Stock Price]
Price --> Info[Stock Info]
Info --> History[Historical Data]
History --> Out[Investment Advice]
style In fill:#8B0000,color:#fff
style Price fill:#2E8B57,color:#fff
style Info fill:#2E8B57,color:#fff
style History fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Finance Agent can analyze stock market data and provide investment recommendations.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `finance_analysis.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import get_stock_price, get_stock_info, get_historical_data
agent = Agent(
instructions="You are a Research Agent",
tools=[get_stock_price, get_stock_info, get_historical_data]
)
agent.start("Understand current stock price and historical data of Apple and Google. Tell me if I can invest in them")
```
</Step>
</Steps>
## Understanding Financial Analysis
The Finance Agent specializes in stock market analysis and investment recommendations using three key components:
1. **Real-time Price Data**: Uses `get_stock_price` to fetch current market prices
2. **Company Information**: Retrieves company details using `get_stock_info`
3. **Historical Analysis**: Analyzes trends with `get_historical_data`
## Features
<CardGroup cols={2}>
<Card title="Real-time Data" icon="clock">
Access to current stock market prices and information.
</Card>
<Card title="Company Analysis" icon="building">
Detailed company information and fundamentals.
</Card>
<Card title="Historical Trends" icon="chart-line">
Analysis of historical price movements and patterns.
</Card>
<Card title="Investment Advice" icon="money-bill">
AI-powered investment recommendations.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Analyzing specific stocks
agent.start("""
1. Get current prices for AAPL and GOOGL
2. Retrieve company information
3. Analyze 6-month historical data
4. Provide investment recommendations
""")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex financial analysis
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendation accuracy
- Check out the [Data Analyst Agent](/agents/data-analyst) for detailed data analysis capabilities
-140
View File
@@ -1,140 +0,0 @@
---
title: "Image to Text Agent"
sidebarTitle: "Image to Text"
description: "Learn how to create AI agents for converting images to textual descriptions and extracting text from images."
icon: "text"
---
```mermaid
flowchart LR
In[Image Input] --> OCR[Text Extractor]
OCR --> Analyzer[Content Analyzer]
Analyzer --> Generator[Description Generator]
Generator --> Out[Text Output]
style In fill:#8B0000,color:#fff
style OCR fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Image-to-Text Agent can extract text from images and generate comprehensive descriptions.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `image_to_text.py`:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create Image-to-Text Agent
image_text_agent = Agent(
name="ImageTextConverter",
role="Image Text Extraction Specialist",
goal="Convert image content to textual descriptions and extract text",
backstory="""You are an expert in OCR and image understanding.
You excel at extracting text from images and generating detailed descriptions.""",
llm="gpt-4o-mini",
self_reflect=False
)
# Create text extraction task
extraction_task = Task(
name="extract_text",
description="Extract all text from this image and describe its layout.",
expected_output="Extracted text and layout description",
agent=image_text_agent,
images=["document.jpg"]
)
# Create description task
description_task = Task(
name="generate_description",
description="Generate a detailed description of the image content.",
expected_output="Comprehensive description of visual elements",
agent=image_text_agent,
images=["scene.jpg"]
)
# Create PraisonAIAgents instance
agents = PraisonAIAgents(
agents=[image_text_agent],
tasks=[extraction_task, description_task],
process="sequential",
verbose=1
)
# Run analysis
agents.start()
```
</Step>
</Steps>
## Understanding Image-to-Text Conversion
The Image-to-Text Agent combines multiple capabilities to convert visual content into textual form:
1. **OCR Processing**: Extracts text from images using optical character recognition
2. **Layout Analysis**: Understands the spatial arrangement of text and visual elements
3. **Content Description**: Generates natural language descriptions of image content
4. **Text Formatting**: Preserves text formatting and structure where possible
## Features
<CardGroup cols={2}>
<Card title="Text Extraction" icon="text">
Advanced OCR capabilities for text extraction.
</Card>
<Card title="Layout Understanding" icon="table-layout">
Analysis of text and content layout.
</Card>
<Card title="Content Description" icon="pen-to-square">
Detailed descriptions of visual content.
</Card>
<Card title="Format Preservation" icon="paragraph">
Maintains text formatting and structure.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Processing a document image
document_task = Task(
name="process_document",
description="Extract text and analyze document layout",
expected_output="Extracted text with layout information",
agent=image_text_agent,
images=["business_document.jpg"]
)
# Run single task
agents = PraisonAIAgents(
agents=[image_text_agent],
tasks=[document_task],
process="sequential"
)
agents.start()
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex document processing
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving text extraction accuracy
- Check out the [Image Agent](/agents/image) for pure image analysis capabilities
-139
View File
@@ -1,139 +0,0 @@
---
title: "Image Analysis Agent"
sidebarTitle: "Image Analysis"
description: "Learn how to create AI agents for image analysis and visual content understanding."
icon: "image"
---
```mermaid
flowchart LR
In[Image Input] --> Analyzer[Image Analyzer]
Analyzer --> Detector[Object Detector]
Detector --> Generator[Description Generator]
Generator --> Out[Analysis Output]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Detector fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Image Analysis Agent can process and analyze visual content, detect objects, and generate detailed descriptions.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `image_analysis.py`:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create Image Analysis Agent
image_agent = Agent(
name="ImageAnalyst",
role="Image Analysis Specialist",
goal="Analyze images and videos to extract meaningful information",
backstory="""You are an expert in computer vision and image analysis.
You excel at describing images, detecting objects, and understanding visual content.""",
llm="gpt-4o-mini",
self_reflect=False
)
# Create tasks for different types of analysis
task1 = Task(
name="analyze_landmark",
description="Describe this famous landmark and its architectural features.",
expected_output="Detailed description of the landmark's architecture and significance",
agent=image_agent,
images=["https://example.com/landmark.jpg"]
)
task2 = Task(
name="analyze_local_image",
description="What objects can you see in this image? Describe their arrangement.",
expected_output="Detailed description of objects and their spatial relationships",
agent=image_agent,
images=["local_image.jpg"]
)
# Create PraisonAIAgents instance
agents = PraisonAIAgents(
agents=[image_agent],
tasks=[task1, task2],
process="sequential",
verbose=1
)
# Run analysis
agents.start()
```
</Step>
</Steps>
## Understanding Image Analysis
The Image Analysis Agent is designed to process and understand visual content through several key capabilities:
1. **Image Input**: Supports both URL and local file inputs
2. **Object Detection**: Identifies and locates objects within images
3. **Architectural Analysis**: Specialized in analyzing architectural features
4. **Spatial Understanding**: Describes spatial relationships between objects
## Features
<CardGroup cols={2}>
<Card title="Multiple Input Sources" icon="images">
Support for both URL and local image files.
</Card>
<Card title="Object Detection" icon="magnifying-glass">
Advanced object detection and recognition.
</Card>
<Card title="Architectural Analysis" icon="building">
Specialized analysis of architectural features.
</Card>
<Card title="Detailed Descriptions" icon="pen">
Generation of comprehensive visual descriptions.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Analyzing a landmark image
landmark_task = Task(
name="analyze_famous_landmark",
description="Analyze this historical landmark",
expected_output="Architectural details and historical significance",
agent=image_agent,
images=["https://example.com/landmark.jpg"]
)
# Run single task
agents = PraisonAIAgents(
agents=[image_agent],
tasks=[landmark_task],
process="sequential"
)
agents.start()
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex image analysis workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
- Check out the [Video Agent](/agents/video) for video content analysis
-120
View File
@@ -1,120 +0,0 @@
---
title: "Markdown Agent"
sidebarTitle: "Markdown"
description: "Learn how to create AI agents for generating and formatting content in Markdown."
icon: "markdown"
---
```mermaid
flowchart LR
In[Content Request] --> Generator[Content Generator]
Generator --> Formatter[Markdown Formatter]
Formatter --> Validator[Format Validator]
Validator --> Out[Markdown Output]
style In fill:#8B0000,color:#fff
style Generator fill:#2E8B57,color:#fff
style Formatter fill:#2E8B57,color:#fff
style Validator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Markdown Agent can generate and format content in Markdown syntax.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `markdown_generator.py`:
```python
from praisonaiagents import Agent
# Create Markdown Agent
markdown_agent = Agent(
name="MarkdownWriter",
role="Markdown Content Specialist",
goal="Generate well-formatted content in Markdown syntax",
instructions="You are a Markdown Agent, output in markdown format",
llm="gpt-4o-mini",
self_reflect=False
)
# Generate content
response = markdown_agent.start(
"Write a blog post about artificial intelligence"
)
# Save to file
with open('blog_post.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Markdown Generation
The Markdown Agent specializes in creating properly formatted Markdown content:
1. **Content Generation**: Creates original content based on prompts
2. **Markdown Formatting**: Applies proper Markdown syntax
3. **Structure Validation**: Ensures correct formatting
4. **Document Organization**: Creates well-structured documents
## Features
<CardGroup cols={2}>
<Card title="Content Creation" icon="pen-to-square">
Generates original, well-structured content.
</Card>
<Card title="Markdown Syntax" icon="code">
Proper implementation of Markdown formatting.
</Card>
<Card title="Document Structure" icon="sitemap">
Organized document hierarchy and sections.
</Card>
<Card title="Format Validation" icon="check">
Ensures correct Markdown syntax usage.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Generate a technical documentation
agent = Agent(
instructions="You are a Markdown Agent, output in markdown format"
)
# Generate API documentation
response = agent.start("""
Create technical documentation for a REST API with:
- Introduction
- Authentication
- Endpoints
- Examples
""")
# Save documentation
with open('api_docs.md', 'w') as f:
f.write(response)
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex document generation
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving content quality
- Check out the [Documentation Agent](/agents/documentation) for specialized documentation generation
-109
View File
@@ -1,109 +0,0 @@
---
title: "Planning Agent"
sidebarTitle: "Planning"
description: "Learn how to create AI agents for trip planning and itinerary generation."
icon: "calendar"
---
```mermaid
flowchart LR
In[Request] --> Search[Web Search]
Search --> Analyzer[Options Analyzer]
Analyzer --> Generator[Plan Generator]
Generator --> Out[Itinerary]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Planning Agent can search for travel options and create detailed itineraries.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `travel_planner.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Planning Agent
planning_agent = Agent(
name="TravelPlanner",
role="Travel Planning Specialist",
goal="Create comprehensive travel plans and itineraries",
instructions="You are a Planning Agent",
tools=[duckduckgo]
)
# Generate travel plan
response = planning_agent.start(
"I want to go to London next week, find me a good hotel and flight"
)
# Save plan
with open('travel_plan.txt', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Travel Planning
The Planning Agent combines multiple capabilities to create comprehensive travel plans:
1. **Web Search**: Uses DuckDuckGo to find current travel options
2. **Options Analysis**: Evaluates and compares different choices
3. **Plan Generation**: Creates detailed itineraries
4. **Recommendations**: Provides personalized suggestions
## Features
<CardGroup cols={2}>
<Card title="Flight Search" icon="plane">
Finds and compares flight options.
</Card>
<Card title="Hotel Booking" icon="hotel">
Recommends suitable accommodations.
</Card>
<Card title="Itinerary Creation" icon="calendar-days">
Generates detailed travel schedules.
</Card>
<Card title="Real-time Data" icon="clock">
Uses current pricing and availability.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Create a weekend trip plan
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(instructions="You are a Planning Agent", tools=[duckduckgo])
agent.start("I want to go London next week, find me a good hotel and flight")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex travel planning
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendations
- Check out the [Research Agent](/agents/research) for detailed destination research
-125
View File
@@ -1,125 +0,0 @@
---
title: "Programming Agent"
sidebarTitle: "Programming"
description: "Learn how to create AI agents for code development, analysis, and execution."
icon: "code"
---
```mermaid
flowchart LR
In[Code Request] --> Analyzer[Code Analyzer]
Analyzer --> Generator[Code Generator]
Generator --> Executor[Code Executor]
Executor --> Debugger[Code Debugger]
Debugger --> Out[Output]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Executor fill:#2E8B57,color:#fff
style Debugger fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Programming Agent can analyze, generate, execute, and debug code.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `code_assistant.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import execute_code, analyze_code, format_code, lint_code, disassemble_code # Code Tools
from praisonaiagents.tools import execute_command, list_processes, kill_process, get_system_info # Shell Tools
from praisonaiagents.tools import duckduckgo # Web Search Tool
agent = Agent(
instructions="You are a Programming Agent", self_reflect=True, min_reflect=5, max_reflect=10,
tools=[execute_code, analyze_code, format_code, lint_code, disassemble_code, execute_command, list_processes, kill_process, get_system_info, duckduckgo]
)
agent.start(
"Write a python script using yfinance to find the stock price of Tesla"
"First check if required packages are installed"
"Run it using execute_code"
"execute_command if you want to run any terminal command"
"search internet using duckduckgo if you want to know update python package information"
"Analyse the output using analyze_code and fix error if required"
"if no package is installed, install it"
"then run the code"
)
```
</Step>
</Steps>
## Understanding Code Development
The Programming Agent combines multiple tools for comprehensive code development:
1. **Code Tools**:
- `execute_code`: Run Python code
- `analyze_code`: Analyze code structure
- `format_code`: Format code to standards
- `lint_code`: Check code quality
- `disassemble_code`: View bytecode
2. **Shell Tools**:
- `execute_command`: Run terminal commands
- `list_processes`: View running processes
- `kill_process`: Terminate processes
- `get_system_info`: System information
3. **Web Tools**:
- `duckduckgo`: Search for programming resources
## Features
<CardGroup cols={2}>
<Card title="Code Execution" icon="play">
Run and test code directly.
</Card>
<Card title="Code Analysis" icon="magnifying-glass-code">
Analyze and improve code quality.
</Card>
<Card title="System Integration" icon="terminal">
Execute system commands and manage processes.
</Card>
<Card title="Package Management" icon="box">
Handle dependencies and installations.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Create and run a data analysis script
response = agent.start("""
1. Create a script that:
- Uses pandas for data analysis
- Reads a CSV file
- Performs basic statistics
- Creates a visualization
2. Check and install required packages
3. Execute and analyze the results
""")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex development workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving code quality
- Check out the [Data Analyst Agent](/agents/data-analyst) for specialized data analysis
-109
View File
@@ -1,109 +0,0 @@
---
title: "Recommendation Agent"
sidebarTitle: "Recommendation"
description: "Learn how to create AI agents for personalized recommendations across various domains."
icon: "thumbs-up"
---
```mermaid
flowchart LR
In[User Preferences] --> Search[Content Search]
Search --> Analyzer[Preference Analyzer]
Analyzer --> Generator[Recommendation Generator]
Generator --> Out[Recommendations]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Generator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Recommendation Agent can analyze preferences and generate personalized recommendations.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `recommendation_system.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Recommendation Agent
recommendation_agent = Agent(
name="RecommendationEngine",
role="Recommendation Specialist",
goal="Generate personalized recommendations based on preferences",
instructions="You are a Recommendation Agent",
tools=[duckduckgo]
)
# Get recommendations
response = recommendation_agent.start(
"Recommend me a good movie to watch in 2025"
)
# Save recommendations
with open('recommendations.txt', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Recommendation System
The Recommendation Agent uses multiple approaches to generate personalized suggestions:
1. **Content Search**: Uses DuckDuckGo to find current options
2. **Preference Analysis**: Understands user preferences
3. **Recommendation Generation**: Creates personalized suggestions
4. **Content Filtering**: Filters based on relevance and quality
## Features
<CardGroup cols={2}>
<Card title="Personalization" icon="user">
Tailored recommendations based on preferences.
</Card>
<Card title="Real-time Data" icon="clock">
Up-to-date content and information.
</Card>
<Card title="Multi-domain" icon="layer-group">
Recommendations across various categories.
</Card>
<Card title="Content Filtering" icon="filter">
Quality-based content selection.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Get personalized recommendations
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(instructions="You are a Recommendation Agent", tools=[duckduckgo])
agent.start("Recommend me a good movie to watch in 2025")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex recommendation systems
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving recommendation accuracy
- Check out the [Research Agent](/agents/research) for detailed content research
-108
View File
@@ -1,108 +0,0 @@
---
title: "Research Agent"
sidebarTitle: "Research"
description: "Learn how to create AI agents for conducting comprehensive research and analysis."
icon: "magnifying-glass-chart"
---
```mermaid
flowchart LR
In[Research Query] --> Search[Web Search]
Search --> Analyzer[Content Analyzer]
Analyzer --> Synthesizer[Information Synthesizer]
Synthesizer --> Out[Research Report]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Synthesizer fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Research Agent can gather, analyze, and synthesize information from various sources.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `research_assistant.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Research Agent
research_agent = Agent(
name="ResearchAssistant",
role="Research Specialist",
goal="Conduct comprehensive research and analysis",
instructions="You are a Research Agent",
tools=[duckduckgo]
)
# Conduct research
response = research_agent.start(
"Research about AI developments in 2024"
)
# Save research findings
with open('research_report.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Research Process
The Research Agent employs a systematic approach to information gathering and analysis:
1. **Web Search**: Uses DuckDuckGo to find relevant sources
2. **Content Analysis**: Evaluates source credibility and relevance
3. **Information Synthesis**: Combines findings into coherent insights
4. **Report Generation**: Creates structured research reports
## Features
<CardGroup cols={2}>
<Card title="Web Research" icon="globe">
Comprehensive online information gathering.
</Card>
<Card title="Content Analysis" icon="microscope">
In-depth evaluation of sources.
</Card>
<Card title="Information Synthesis" icon="layer-group">
Integration of multiple sources.
</Card>
<Card title="Report Generation" icon="file-lines">
Structured research documentation.
</Card>
</CardGroup>
## Example Usage
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(instructions="You are a Research Agent", tools=[duckduckgo])
agent.start("Research about AI 2024")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex research projects
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving research quality
- Check out the [Data Analyst Agent](/agents/data-analyst) for data-driven research
-109
View File
@@ -1,109 +0,0 @@
---
title: "Shopping Agent"
sidebarTitle: "Shopping"
description: "Learn how to create AI agents for price comparison and shopping assistance."
icon: "shop"
---
```mermaid
flowchart LR
In[Product Query] --> Search[Store Search]
Search --> Analyzer[Price Analyzer]
Analyzer --> Comparator[Price Comparator]
Comparator --> Out[Price Report]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Comparator fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Shopping Agent can search for products, compare prices, and provide shopping recommendations.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `shopping_assistant.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Shopping Agent
shopping_agent = Agent(
name="ShoppingAssistant",
role="Shopping Specialist",
goal="Find the best prices and deals across stores",
instructions="You are a Shopping Agent",
tools=[duckduckgo]
)
# Search for product prices
response = shopping_agent.start(
"I want to buy iPhone 16 Pro Max, check 5 stores and give me price in table"
)
# Save price comparison
with open('price_comparison.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Shopping Assistant
The Shopping Agent combines multiple capabilities for effective price comparison:
1. **Store Search**: Uses DuckDuckGo to find retailers
2. **Price Analysis**: Gathers pricing information
3. **Price Comparison**: Compares prices across stores
4. **Deal Finding**: Identifies special offers and discounts
## Features
<CardGroup cols={2}>
<Card title="Price Comparison" icon="scale-balanced">
Compare prices across multiple stores.
</Card>
<Card title="Deal Detection" icon="tag">
Find special offers and discounts.
</Card>
<Card title="Store Analysis" icon="store">
Evaluate retailer reliability.
</Card>
<Card title="Price Tracking" icon="chart-line">
Monitor price changes over time.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Compare product prices
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(instructions="You are a Shopping Agent", tools=[duckduckgo])
agent.start("I want to buy iPhone 16 Pro Max, check 5 stores and give me price in table")
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex shopping research
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving price accuracy
- Check out the [Research Agent](/agents/research) for detailed product research
-102
View File
@@ -1,102 +0,0 @@
---
title: "Single Agent"
sidebarTitle: "Single"
description: "Learn how to create a basic single-purpose AI agent for simple tasks."
icon: "circle-1"
---
```mermaid
flowchart LR
In[Input] --> Agent[Single Agent]
Agent --> Out[Output]
style In fill:#8B0000,color:#fff
style Agent fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how to create and use a simple single-purpose agent.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `simple_agent.py`:
```python
from praisonaiagents import Agent
agent = Agent(instructions="You are a Markdown Agent, output in markdown format")
agent.start("Write a blog post about AI")
```
</Step>
</Steps>
## Understanding Single Agent
The Single Agent is the simplest form of PraisonAI agent:
1. **Simple Setup**: Minimal configuration required
2. **Single Purpose**: Focused on one specific task
3. **Direct Execution**: Straightforward input-output flow
4. **No Dependencies**: No external tools required
## Features
<CardGroup cols={2}>
<Card title="Simple Setup" icon="square-1">
Minimal configuration needed.
</Card>
<Card title="Focused Task" icon="bullseye">
Single-purpose execution.
</Card>
<Card title="Quick Start" icon="bolt">
Rapid implementation.
</Card>
<Card title="No Tools" icon="toolbox">
No external dependencies.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Create a content generation agent
from praisonaiagents import Agent
# Create content agent
agent = Agent(
instructions="You are a Content Generation Agent, create engaging content"
)
# Generate content
response = agent.start("""
Write a short story about:
- A future world
- With advanced AI
- And human collaboration
""")
# Save the story
with open('ai_story.txt', 'w') as f:
f.write(response)
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for more complex workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving output quality
- Check out other specialized agents like the [Markdown Agent](/agents/markdown) for specific use cases
-149
View File
@@ -1,149 +0,0 @@
---
title: "Video Agent"
sidebarTitle: "Video"
description: "Learn how to create AI agents for video analysis and content understanding."
icon: "video"
---
```mermaid
flowchart LR
In[Video Input] --> Analyzer[Content Analyzer]
Analyzer --> Detector[Object Detector]
Detector --> Transcriber[Text Transcriber]
Transcriber --> Out[Analysis Report]
style In fill:#8B0000,color:#fff
style Analyzer fill:#2E8B57,color:#fff
style Detector fill:#2E8B57,color:#fff
style Transcriber fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Video Agent can analyze video content, detect objects, and extract meaningful information.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `video_analyzer.py`:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create Video Analysis Agent
video_agent = Agent(
name="VideoAnalyst",
role="Video Analysis Specialist",
goal="Analyze videos to extract meaningful information",
backstory="""You are an expert in computer vision and video analysis.
You excel at describing content, detecting objects, and understanding context.""",
llm="gpt-4o-mini",
self_reflect=False
)
# Create video analysis task
analysis_task = Task(
name="analyze_video",
description="""Analyze this video and provide:
1. Summary of main events
2. Key objects and people
3. Text and important information
4. Context and setting""",
expected_output="Comprehensive video analysis",
agent=video_agent,
images=["video.mp4"]
)
# Create PraisonAIAgents instance
agents = PraisonAIAgents(
agents=[video_agent],
tasks=[analysis_task],
process="sequential",
verbose=1
)
# Run analysis
agents.start()
```
</Step>
</Steps>
## Understanding Video Analysis
The Video Agent combines multiple capabilities for comprehensive video understanding:
1. **Content Analysis**: Analyzes video scenes and events
2. **Object Detection**: Identifies objects and people
3. **Text Extraction**: Captures text shown in videos
4. **Context Understanding**: Interprets settings and situations
## Features
<CardGroup cols={2}>
<Card title="Scene Analysis" icon="film">
Detailed analysis of video scenes.
</Card>
<Card title="Object Detection" icon="cube">
Identification of objects and people.
</Card>
<Card title="Text Extraction" icon="closed-captioning">
Capture of text and captions.
</Card>
<Card title="Context Analysis" icon="sitemap">
Understanding of video context.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Analyze a presentation video
from praisonaiagents import Agent, Task, PraisonAIAgents
video_agent = Agent(
name="VideoAnalyst",
role="Video Analysis Specialist",
goal="Extract information from presentation videos",
llm="gpt-4o-mini"
)
# Create presentation analysis task
presentation_task = Task(
name="analyze_presentation",
description="""Analyze this presentation video:
1. Extract key points
2. Capture slide content
3. Note speaker's main arguments
4. Summarize Q&A session""",
expected_output="Detailed presentation summary",
agent=video_agent,
images=["presentation.mp4"]
)
# Run analysis
agents = PraisonAIAgents(
agents=[video_agent],
tasks=[presentation_task],
process="sequential"
)
agents.start()
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex video analysis
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving analysis accuracy
- Check out the [Image Agent](/agents/image) for still image analysis
-124
View File
@@ -1,124 +0,0 @@
---
title: "Web Search Agent"
sidebarTitle: "Web Search"
description: "Learn how to create AI agents for intelligent web searching and information gathering."
icon: "globe"
---
```mermaid
flowchart LR
In[Search Query] --> Search[Web Search]
Search --> Filter[Content Filter]
Filter --> Summarizer[Content Summarizer]
Summarizer --> Out[Search Results]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Filter fill:#2E8B57,color:#fff
style Summarizer fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Web Search Agent can perform intelligent searches and process web content.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `web_search.py`:
```python
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
# Create Web Search Agent
search_agent = Agent(
name="WebSearcher",
role="Web Search Specialist",
goal="Perform intelligent web searches and gather information",
instructions="You are a Web Search Agent",
tools=[duckduckgo]
)
# Perform search
response = search_agent.start(
"Search about AI developments in 2024"
)
# Save search results
with open('search_results.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Web Search
The Web Search Agent employs sophisticated search strategies:
1. **Query Processing**: Optimizes search queries
2. **Content Filtering**: Filters relevant results
3. **Information Extraction**: Extracts key information
4. **Result Summarization**: Summarizes findings
## Features
<CardGroup cols={2}>
<Card title="Smart Search" icon="magnifying-glass">
Intelligent query processing.
</Card>
<Card title="Content Filtering" icon="filter">
Relevance-based filtering.
</Card>
<Card title="Information Extraction" icon="scissors">
Key information extraction.
</Card>
<Card title="Result Summary" icon="list">
Concise result summaries.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Perform topic research
from praisonaiagents import Agent, Tools
from praisonaiagents.tools import duckduckgo
agent = Agent(
instructions="You are a Web Search Agent",
tools=[duckduckgo]
)
# Research specific topic
response = agent.start("""
Search for information about quantum computing:
- Recent breakthroughs
- Leading companies
- Current applications
- Future predictions
""")
# Save research results
with open('quantum_computing_research.md', 'w') as f:
f.write(response)
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex search workflows
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving search relevance
- Check out the [Research Agent](/agents/research) for comprehensive research capabilities
-139
View File
@@ -1,139 +0,0 @@
---
title: "Wikipedia Agent"
sidebarTitle: "Wikipedia"
description: "Learn how to create AI agents for searching and extracting information from Wikipedia."
icon: "book"
---
```mermaid
flowchart LR
In[Query] --> Search[Wiki Search]
Search --> Page[Page Retrieval]
Page --> Summary[Content Summary]
Summary --> Out[Knowledge Output]
style In fill:#8B0000,color:#fff
style Search fill:#2E8B57,color:#fff
style Page fill:#2E8B57,color:#fff
style Summary fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
A workflow demonstrating how the Wikipedia Agent can search, retrieve, and summarize Wikipedia content.
## Quick Start
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install praisonaiagents
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create Script">
Create a new file `wikipedia_assistant.py`:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import (
wiki_search,
wiki_summary,
wiki_page,
wiki_random,
wiki_language
)
# Create Wikipedia Agent
wiki_agent = Agent(
name="WikipediaAssistant",
role="Wikipedia Research Specialist",
goal="Extract and summarize Wikipedia content",
instructions="You are a Wikipedia Agent",
tools=[
wiki_search,
wiki_summary,
wiki_page,
wiki_random,
wiki_language
],
self_reflect=True,
min_reflect=3,
max_reflect=5
)
# Research a topic
response = wiki_agent.start("""
What is the history of AI?
First search the history of AI
Read the page of the history of AI
Get the summary of the page
""")
# Save research results
with open('ai_history.md', 'w') as f:
f.write(response)
```
</Step>
</Steps>
## Understanding Wikipedia Research
The Wikipedia Agent provides comprehensive Wikipedia access through multiple tools:
1. **Wiki Search**: `wiki_search` for finding relevant articles
2. **Page Access**: `wiki_page` for retrieving full articles
3. **Summarization**: `wiki_summary` for concise overviews
4. **Random Articles**: `wiki_random` for discovering content
5. **Language Support**: `wiki_language` for multilingual access
## Features
<CardGroup cols={2}>
<Card title="Article Search" icon="magnifying-glass">
Find relevant Wikipedia articles.
</Card>
<Card title="Content Retrieval" icon="book-open">
Access complete article content.
</Card>
<Card title="Summarization" icon="compress">
Generate concise article summaries.
</Card>
<Card title="Multilingual" icon="language">
Access content in multiple languages.
</Card>
</CardGroup>
## Example Usage
```python
# Example: Research a scientific topic
from praisonaiagents import Agent
from praisonaiagents.tools import wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language
agent = Agent(
instructions="You are a Wikipedia Agent",
tools=[wiki_search, wiki_summary, wiki_page, wiki_random, wiki_language],
self_reflect=True,
min_reflect=3,
max_reflect=5,
)
agent.start(
"What is the history of AI?"
"First search the history of AI"
"Read the page of the history of AI"
"Get the summary of the page"
)
```
## Next Steps
- Learn about [Prompt Chaining](/features/promptchaining) for complex Wikipedia research
- Explore [Evaluator Optimizer](/features/evaluator-optimiser) for improving research quality
- Check out the [Research Agent](/agents/research) for broader research capabilities
-45
View File
@@ -1,45 +0,0 @@
---
title: 'API Reference'
description: 'PraisonAI API documentation with framework-specific details'
icon: "book-open"
---
# API Reference
This section provides detailed information about the PraisonAI API and its framework-specific implementations.
## Core Modules
- [praisonai](../api/praisonai/index) - Core package functionality
- [praisonai.auto](../api/praisonai/auto) - Automated agent generation
- [praisonai.agents_generator](../api/praisonai/agents_generator) - Framework-specific agent generation
- [praisonai.cli](../api/praisonai/cli) - Command-line interface
- [praisonai.deploy](../api/praisonai/deploy) - Deployment utilities
## Framework Support
### CrewAI Integration
Requires installation with:
```bash
pip install "praisonai[crewai]"
```
Features:
- Task delegation
- Sequential/parallel execution
- Built-in tools
- Structured workflows
### AG2 (Formerly AutoGen) Integration
Requires installation with:
```bash
pip install "praisonai[autogen]"
```
Features:
- Multi-agent conversations
- Code execution
- Built-in tools
- Flexible interactions
For detailed API documentation of each module, please refer to the generated files in the `api` folder.
-79
View File
@@ -1,79 +0,0 @@
---
title: "API Reference"
description: "Complete API reference for PraisonAI, including core modules, installation options, and framework-specific features"
icon: "code"
---
## Core Modules
### praisonai
The main package containing core functionality.
```python
from praisonai import PraisonAI
```
### praisonai.auto
Automated agent generation functionality.
```python
from praisonai.auto import AutoGenerator
```
### praisonai.agents_generator
Framework-specific agent generation and orchestration:
- CrewAI support (requires `praisonai[crewai]`)
- AG2 (Formerly AutoGen) support (requires `praisonai[autogen]`)
```python
from praisonai.agents_generator import AgentsGenerator
```
### praisonai.cli
Command-line interface with framework-specific handling.
```python
from praisonai.cli import PraisonAI
```
### praisonai.deploy
Deployment utilities.
```python
from praisonai.deploy import CloudDeployer
```
## Installation Options
```bash
# Basic installation
pip install praisonai
# Framework-specific installations
pip install "praisonai[crewai]" # Install with CrewAI support
pip install "praisonai[autogen]" # Install with AG2 support
pip install "praisonai[crewai,autogen]" # Install both frameworks
# Additional features
pip install "praisonai[ui]" # Install UI support
pip install "praisonai[chat]" # Install Chat interface
pip install "praisonai[code]" # Install Code interface
pip install "praisonai[realtime]" # Install Realtime voice interaction
pip install "praisonai[call]" # Install Call feature
```
## Framework-specific Features
### CrewAI
When installing with `pip install "praisonai[crewai]"`, you get:
- CrewAI framework support
- PraisonAI tools integration
- Task delegation capabilities
- Sequential and parallel task execution
### AG2 (Formerly AutoGen)
When installing with `pip install "praisonai[autogen]"`, you get:
- AG2 framework support
- PraisonAI tools integration
- Multi-agent conversation capabilities
- Code execution environment
-566
View File
@@ -1,566 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.agents_generator API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.agents_generator</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="praisonai.agents_generator.disable_crewai_telemetry"><code class="name flex">
<span>def <span class="ident">disable_crewai_telemetry</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.agents_generator.noop"><code class="name flex">
<span>def <span class="ident">noop</span></span>(<span>*args, **kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="praisonai.agents_generator.AgentsGenerator"><code class="flex name class">
<span>class <span class="ident">AgentsGenerator</span></span>
<span>(</span><span>agent_file, framework, config_list, log_level=None, agent_callback=None, task_callback=None, agent_yaml=None, tools=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Initialize the AgentsGenerator object.</p>
<h2 id="parameters">Parameters</h2>
<p>agent_file (str): The path to the agent file.
framework (str): The framework to be used for the agents.
config_list (list): A list of configurations for the agents.
log_level (int, optional): The logging level to use. Defaults to logging.INFO.
agent_callback (callable, optional): A callback function to be executed after each agent step.
task_callback (callable, optional): A callback function to be executed after each tool run.
agent_yaml (str, optional): The content of the YAML file. Defaults to None.
tools (dict, optional): A dictionary containing the tools to be used for the agents. Defaults to None.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>agent_file</code></strong> :&ensp;<code>str</code></dt>
<dd>The path to the agent file.</dd>
<dt><strong><code>framework</code></strong> :&ensp;<code>str</code></dt>
<dd>The framework to be used for the agents.</dd>
<dt><strong><code>config_list</code></strong> :&ensp;<code>list</code></dt>
<dd>A list of configurations for the agents.</dd>
<dt><strong><code>log_level</code></strong> :&ensp;<code>int</code></dt>
<dd>The logging level to use.</dd>
<dt><strong><code>agent_callback</code></strong> :&ensp;<code>callable</code>, optional</dt>
<dd>A callback function to be executed after each agent step.</dd>
<dt><strong><code>task_callback</code></strong> :&ensp;<code>callable</code>, optional</dt>
<dd>A callback function to be executed after each tool run.</dd>
<dt><strong><code>tools</code></strong> :&ensp;<code>dict</code></dt>
<dd>A dictionary containing the tools to be used for the agents.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class AgentsGenerator:
def __init__(self, agent_file, framework, config_list, log_level=None, agent_callback=None, task_callback=None, agent_yaml=None, tools=None):
&#34;&#34;&#34;
Initialize the AgentsGenerator object.
Parameters:
agent_file (str): The path to the agent file.
framework (str): The framework to be used for the agents.
config_list (list): A list of configurations for the agents.
log_level (int, optional): The logging level to use. Defaults to logging.INFO.
agent_callback (callable, optional): A callback function to be executed after each agent step.
task_callback (callable, optional): A callback function to be executed after each tool run.
agent_yaml (str, optional): The content of the YAML file. Defaults to None.
tools (dict, optional): A dictionary containing the tools to be used for the agents. Defaults to None.
Attributes:
agent_file (str): The path to the agent file.
framework (str): The framework to be used for the agents.
config_list (list): A list of configurations for the agents.
log_level (int): The logging level to use.
agent_callback (callable, optional): A callback function to be executed after each agent step.
task_callback (callable, optional): A callback function to be executed after each tool run.
tools (dict): A dictionary containing the tools to be used for the agents.
&#34;&#34;&#34;
self.agent_file = agent_file
self.framework = framework
self.config_list = config_list
self.log_level = log_level
self.agent_callback = agent_callback
self.task_callback = task_callback
self.agent_yaml = agent_yaml
self.tools = tools or [] # Store tool class names as a list
self.log_level = log_level or logging.getLogger().getEffectiveLevel()
if self.log_level == logging.NOTSET:
self.log_level = os.environ.get(&#39;LOGLEVEL&#39;, &#39;INFO&#39;).upper()
logging.basicConfig(level=self.log_level, format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)
self.logger = logging.getLogger(__name__)
self.logger.setLevel(self.log_level)
def is_function_or_decorated(self, obj):
&#34;&#34;&#34;
Checks if the given object is a function or has a __call__ method.
Parameters:
obj (object): The object to be checked.
Returns:
bool: True if the object is a function or has a __call__ method, False otherwise.
&#34;&#34;&#34;
return inspect.isfunction(obj) or hasattr(obj, &#39;__call__&#39;)
def load_tools_from_module(self, module_path):
&#34;&#34;&#34;
Loads tools from a specified module path.
Parameters:
module_path (str): The path to the module containing the tools.
Returns:
dict: A dictionary containing the names of the tools as keys and the corresponding functions or objects as values.
Raises:
FileNotFoundError: If the specified module path does not exist.
&#34;&#34;&#34;
spec = importlib.util.spec_from_file_location(&#34;tools_module&#34;, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return {name: obj for name, obj in inspect.getmembers(module, self.is_function_or_decorated)}
def load_tools_from_module_class(self, module_path):
&#34;&#34;&#34;
Loads tools from a specified module path containing classes that inherit from BaseTool or are part of langchain_community.tools package.
Parameters:
module_path (str): The path to the module containing the tools.
Returns:
dict: A dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.
Raises:
FileNotFoundError: If the specified module path does not exist.
&#34;&#34;&#34;
spec = importlib.util.spec_from_file_location(&#34;tools_module&#34;, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return {name: obj() for name, obj in inspect.getmembers(module, lambda x: inspect.isclass(x) and (x.__module__.startswith(&#39;langchain_community.tools&#39;) or issubclass(x, BaseTool)) and x is not BaseTool)}
def load_tools_from_package(self, package_path):
&#34;&#34;&#34;
Loads tools from a specified package path containing modules with functions or classes.
Parameters:
package_path (str): The path to the package containing the tools.
Returns:
dict: A dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.
Raises:
FileNotFoundError: If the specified package path does not exist.
This function iterates through all the .py files in the specified package path, excluding those that start with &#34;__&#34;. For each file, it imports the corresponding module and checks if it contains any functions or classes that can be loaded as tools. The function then returns a dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.
&#34;&#34;&#34;
tools_dict = {}
for module_file in os.listdir(package_path):
if module_file.endswith(&#39;.py&#39;) and not module_file.startswith(&#39;__&#39;):
module_name = f&#34;{package_path.name}.{module_file[:-3]}&#34; # Remove .py for import
module = importlib.import_module(module_name)
for name, obj in inspect.getmembers(module, self.is_function_or_decorated):
tools_dict[name] = obj
return tools_dict
def generate_crew_and_kickoff(self):
&#34;&#34;&#34;
Generates a crew of agents and initiates tasks based on the provided configuration.
Parameters:
agent_file (str): The path to the agent file.
framework (str): The framework to be used for the agents.
config_list (list): A list of configurations for the agents.
Returns:
str: The output of the tasks performed by the crew of agents.
Raises:
FileNotFoundError: If the specified agent file does not exist.
This function first loads the agent configuration from the specified file. It then initializes the tools required for the agents based on the specified framework. If the specified framework is &#34;autogen&#34;, it loads the LLM configuration dynamically and creates an AssistantAgent for each role in the configuration. It then adds tools to the agents if specified in the configuration. Finally, it prepares tasks for the agents based on the configuration and initiates the tasks using the crew of agents. If the specified framework is not &#34;autogen&#34;, it creates a crew of agents and initiates tasks based on the configuration.
&#34;&#34;&#34;
if self.agent_yaml:
config = yaml.safe_load(self.agent_yaml)
else:
if self.agent_file == &#39;/app/api:app&#39; or self.agent_file == &#39;api:app&#39;:
self.agent_file = &#39;agents.yaml&#39;
try:
with open(self.agent_file, &#39;r&#39;) as f:
config = yaml.safe_load(f)
except FileNotFoundError:
print(f&#34;File not found: {self.agent_file}&#34;)
return
topic = config[&#39;topic&#39;]
tools_dict = {
&#39;CodeDocsSearchTool&#39;: CodeDocsSearchTool(),
&#39;CSVSearchTool&#39;: CSVSearchTool(),
&#39;DirectorySearchTool&#39;: DirectorySearchTool(),
&#39;DOCXSearchTool&#39;: DOCXSearchTool(),
&#39;DirectoryReadTool&#39;: DirectoryReadTool(),
&#39;FileReadTool&#39;: FileReadTool(),
# &#39;GithubSearchTool&#39;: GithubSearchTool(),
# &#39;SeperDevTool&#39;: SeperDevTool(),
&#39;TXTSearchTool&#39;: TXTSearchTool(),
&#39;JSONSearchTool&#39;: JSONSearchTool(),
&#39;MDXSearchTool&#39;: MDXSearchTool(),
&#39;PDFSearchTool&#39;: PDFSearchTool(),
# &#39;PGSearchTool&#39;: PGSearchTool(),
&#39;RagTool&#39;: RagTool(),
&#39;ScrapeElementFromWebsiteTool&#39;: ScrapeElementFromWebsiteTool(),
&#39;ScrapeWebsiteTool&#39;: ScrapeWebsiteTool(),
&#39;WebsiteSearchTool&#39;: WebsiteSearchTool(),
&#39;XMLSearchTool&#39;: XMLSearchTool(),
&#39;YoutubeChannelSearchTool&#39;: YoutubeChannelSearchTool(),
&#39;YoutubeVideoSearchTool&#39;: YoutubeVideoSearchTool(),
}
# Add tools from class names
for tool_class in self.tools:
if isinstance(tool_class, type) and issubclass(tool_class, BaseTool):
tool_name = tool_class.__name__
tools_dict[tool_name] = tool_class()
self.logger.debug(f&#34;Added tool: {tool_name}&#34;)
root_directory = os.getcwd()
tools_py_path = os.path.join(root_directory, &#39;tools.py&#39;)
tools_dir_path = Path(root_directory) / &#39;tools&#39;
if os.path.isfile(tools_py_path):
tools_dict.update(self.load_tools_from_module_class(tools_py_path))
self.logger.debug(&#34;tools.py exists in the root directory. Loading tools.py and skipping tools folder.&#34;)
elif tools_dir_path.is_dir():
tools_dict.update(self.load_tools_from_module_class(tools_dir_path))
self.logger.debug(&#34;tools folder exists in the root directory&#34;)
framework = self.framework or config.get(&#39;framework&#39;)
agents = {}
tasks = []
if framework == &#34;autogen&#34;:
# Load the LLM configuration dynamically
# print(self.config_list)
llm_config = {&#34;config_list&#34;: self.config_list}
if agentops_exists:
agentops.init(os.environ.get(&#34;AGENTOPS_API_KEY&#34;), tags=[&#34;autogen&#34;])
# Assuming the user proxy agent is set up as per your requirements
user_proxy = autogen.UserProxyAgent(
name=&#34;User&#34;,
human_input_mode=&#34;NEVER&#34;,
is_termination_msg=lambda x: (x.get(&#34;content&#34;) or &#34;&#34;).rstrip().rstrip(&#34;.&#34;).lower().endswith(&#34;terminate&#34;) or &#34;TERMINATE&#34; in (x.get(&#34;content&#34;) or &#34;&#34;),
code_execution_config={
&#34;work_dir&#34;: &#34;coding&#34;,
&#34;use_docker&#34;: False,
},
# additional setup for the user proxy agent
)
for role, details in config[&#39;roles&#39;].items():
agent_name = details[&#39;role&#39;].format(topic=topic).replace(&#34;{topic}&#34;, topic)
agent_goal = details[&#39;goal&#39;].format(topic=topic)
# Creating an AssistantAgent for each role dynamically
agents[role] = autogen.AssistantAgent(
name=agent_name,
llm_config=llm_config,
system_message=details[&#39;backstory&#39;].format(topic=topic)+&#34;. Must Reply \&#34;TERMINATE\&#34; in the end when everything is done.&#34;,
)
for tool in details.get(&#39;tools&#39;, []):
if tool in tools_dict:
try:
tool_class = globals()[f&#39;autogen_{type(tools_dict[tool]).__name__}&#39;]
print(f&#34;Found {tool_class.__name__} for {tool}&#34;)
except KeyError:
print(f&#34;Warning: autogen_{type(tools_dict[tool]).__name__} function not found. Skipping this tool.&#34;)
continue
tool_class(agents[role], user_proxy)
# Preparing tasks for initiate_chats
for task_name, task_details in details.get(&#39;tasks&#39;, {}).items():
description_filled = task_details[&#39;description&#39;].format(topic=topic)
expected_output_filled = task_details[&#39;expected_output&#39;].format(topic=topic)
chat_task = {
&#34;recipient&#34;: agents[role],
&#34;message&#34;: description_filled,
&#34;summary_method&#34;: &#34;last_msg&#34;,
# Additional fields like carryover can be added based on dependencies
}
tasks.append(chat_task)
response = user_proxy.initiate_chats(tasks)
result = &#34;### Output ###\n&#34;+response[-1].summary if hasattr(response[-1], &#39;summary&#39;) else &#34;&#34;
if agentops_exists:
agentops.end_session(&#34;Success&#34;)
else: # framework=crewai
if agentops_exists:
agentops.init(os.environ.get(&#34;AGENTOPS_API_KEY&#34;), tags=[&#34;crewai&#34;])
tasks_dict = {}
for role, details in config[&#39;roles&#39;].items():
role_filled = details[&#39;role&#39;].format(topic=topic)
goal_filled = details[&#39;goal&#39;].format(topic=topic)
backstory_filled = details[&#39;backstory&#39;].format(topic=topic)
# Adding tools to the agent if exists
agent_tools = [tools_dict[tool] for tool in details.get(&#39;tools&#39;, []) if tool in tools_dict]
llm_model = details.get(&#39;llm&#39;) # Get the llm configuration
if llm_model:
llm = PraisonAIModel(
model=llm_model.get(&#34;model&#34;, os.environ.get(&#34;MODEL_NAME&#34;, &#34;openai/gpt-4o&#34;)),
).get_model()
else:
llm = PraisonAIModel().get_model()
function_calling_llm_model = details.get(&#39;function_calling_llm&#39;)
if function_calling_llm_model:
function_calling_llm = PraisonAIModel(
model=function_calling_llm_model.get(&#34;model&#34;, os.environ.get(&#34;MODEL_NAME&#34;, &#34;openai/gpt-4o&#34;)),
).get_model()
else:
function_calling_llm = PraisonAIModel().get_model()
agent = Agent(
role=role_filled,
goal=goal_filled,
backstory=backstory_filled,
tools=agent_tools,
allow_delegation=details.get(&#39;allow_delegation&#39;, False),
llm=llm,
function_calling_llm=function_calling_llm,
max_iter=details.get(&#39;max_iter&#39;, 15),
max_rpm=details.get(&#39;max_rpm&#39;),
max_execution_time=details.get(&#39;max_execution_time&#39;),
verbose=details.get(&#39;verbose&#39;, True),
cache=details.get(&#39;cache&#39;, True),
system_template=details.get(&#39;system_template&#39;),
prompt_template=details.get(&#39;prompt_template&#39;),
response_template=details.get(&#39;response_template&#39;),
)
# Set agent callback if provided
if self.agent_callback:
agent.step_callback = self.agent_callback
agents[role] = agent
for task_name, task_details in details.get(&#39;tasks&#39;, {}).items():
description_filled = task_details[&#39;description&#39;].format(topic=topic)
expected_output_filled = task_details[&#39;expected_output&#39;].format(topic=topic)
task = Task(
description=description_filled, # Clear, concise statement of what the task entails
expected_output=expected_output_filled, # Detailed description of what task&#39;s completion looks like
agent=agent, # The agent responsible for the task
tools=task_details.get(&#39;tools&#39;, []), # Functions or capabilities the agent can utilize
async_execution=task_details.get(&#39;async_execution&#39;) if task_details.get(&#39;async_execution&#39;) is not None else False, # Execute asynchronously if set
context=[], ## TODO:
config=task_details.get(&#39;config&#39;) if task_details.get(&#39;config&#39;) is not None else {}, # Additional configuration details
output_json=task_details.get(&#39;output_json&#39;) if task_details.get(&#39;output_json&#39;) is not None else None, # Outputs a JSON object
output_pydantic=task_details.get(&#39;output_pydantic&#39;) if task_details.get(&#39;output_pydantic&#39;) is not None else None, # Outputs a Pydantic model object
output_file=task_details.get(&#39;output_file&#39;) if task_details.get(&#39;output_file&#39;) is not None else &#34;&#34;, # Saves the task output to a file
callback=task_details.get(&#39;callback&#39;) if task_details.get(&#39;callback&#39;) is not None else None, # Python callable executed with the task&#39;s output
human_input=task_details.get(&#39;human_input&#39;) if task_details.get(&#39;human_input&#39;) is not None else False, # Indicates if the task requires human feedback
create_directory=task_details.get(&#39;create_directory&#39;) if task_details.get(&#39;create_directory&#39;) is not None else False # Indicates if a directory needs to be created
)
# Set tool callback if provided
if self.task_callback:
task.callback = self.task_callback
tasks.append(task)
tasks_dict[task_name] = task
for role, details in config[&#39;roles&#39;].items():
for task_name, task_details in details.get(&#39;tasks&#39;, {}).items():
task = tasks_dict[task_name]
context_tasks = [tasks_dict[ctx] for ctx in task_details.get(&#39;context&#39;, []) if ctx in tasks_dict]
task.context = context_tasks
crew = Crew(
agents=list(agents.values()),
tasks=tasks,
verbose=2
)
self.logger.debug(&#34;Final Crew Configuration:&#34;)
self.logger.debug(f&#34;Agents: {crew.agents}&#34;)
self.logger.debug(f&#34;Tasks: {crew.tasks}&#34;)
response = crew.kickoff()
result = f&#34;### Task Output ###\n{response}&#34;
if agentops_exists:
agentops.end_session(&#34;Success&#34;)
return result</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="praisonai.agents_generator.AgentsGenerator.generate_crew_and_kickoff"><code class="name flex">
<span>def <span class="ident">generate_crew_and_kickoff</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Generates a crew of agents and initiates tasks based on the provided configuration.</p>
<h2 id="parameters">Parameters</h2>
<p>agent_file (str): The path to the agent file.
framework (str): The framework to be used for the agents.
config_list (list): A list of configurations for the agents.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>The output of the tasks performed by the crew of agents.</dd>
</dl>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>FileNotFoundError</code></dt>
<dd>If the specified agent file does not exist.</dd>
</dl>
<p>This function first loads the agent configuration from the specified file. It then initializes the tools required for the agents based on the specified framework. If the specified framework is "autogen", it loads the LLM configuration dynamically and creates an AssistantAgent for each role in the configuration. It then adds tools to the agents if specified in the configuration. Finally, it prepares tasks for the agents based on the configuration and initiates the tasks using the crew of agents. If the specified framework is not "autogen", it creates a crew of agents and initiates tasks based on the configuration.</p></div>
</dd>
<dt id="praisonai.agents_generator.AgentsGenerator.is_function_or_decorated"><code class="name flex">
<span>def <span class="ident">is_function_or_decorated</span></span>(<span>self, obj)</span>
</code></dt>
<dd>
<div class="desc"><p>Checks if the given object is a function or has a <strong>call</strong> method.</p>
<h2 id="parameters">Parameters</h2>
<p>obj (object): The object to be checked.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>bool</code></dt>
<dd>True if the object is a function or has a <strong>call</strong> method, False otherwise.</dd>
</dl></div>
</dd>
<dt id="praisonai.agents_generator.AgentsGenerator.load_tools_from_module"><code class="name flex">
<span>def <span class="ident">load_tools_from_module</span></span>(<span>self, module_path)</span>
</code></dt>
<dd>
<div class="desc"><p>Loads tools from a specified module path.</p>
<h2 id="parameters">Parameters</h2>
<p>module_path (str): The path to the module containing the tools.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>dict</code></dt>
<dd>A dictionary containing the names of the tools as keys and the corresponding functions or objects as values.</dd>
</dl>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>FileNotFoundError</code></dt>
<dd>If the specified module path does not exist.</dd>
</dl></div>
</dd>
<dt id="praisonai.agents_generator.AgentsGenerator.load_tools_from_module_class"><code class="name flex">
<span>def <span class="ident">load_tools_from_module_class</span></span>(<span>self, module_path)</span>
</code></dt>
<dd>
<div class="desc"><p>Loads tools from a specified module path containing classes that inherit from BaseTool or are part of langchain_community.tools package.</p>
<h2 id="parameters">Parameters</h2>
<p>module_path (str): The path to the module containing the tools.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>dict</code></dt>
<dd>A dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.</dd>
</dl>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>FileNotFoundError</code></dt>
<dd>If the specified module path does not exist.</dd>
</dl></div>
</dd>
<dt id="praisonai.agents_generator.AgentsGenerator.load_tools_from_package"><code class="name flex">
<span>def <span class="ident">load_tools_from_package</span></span>(<span>self, package_path)</span>
</code></dt>
<dd>
<div class="desc"><p>Loads tools from a specified package path containing modules with functions or classes.</p>
<h2 id="parameters">Parameters</h2>
<p>package_path (str): The path to the package containing the tools.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>dict</code></dt>
<dd>A dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.</dd>
</dl>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>FileNotFoundError</code></dt>
<dd>If the specified package path does not exist.</dd>
</dl>
<p>This function iterates through all the .py files in the specified package path, excluding those that start with "__". For each file, it imports the corresponding module and checks if it contains any functions or classes that can be loaded as tools. The function then returns a dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.</p></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="praisonai.agents_generator.disable_crewai_telemetry" href="#praisonai.agents_generator.disable_crewai_telemetry">disable_crewai_telemetry</a></code></li>
<li><code><a title="praisonai.agents_generator.noop" href="#praisonai.agents_generator.noop">noop</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="praisonai.agents_generator.AgentsGenerator" href="#praisonai.agents_generator.AgentsGenerator">AgentsGenerator</a></code></h4>
<ul class="">
<li><code><a title="praisonai.agents_generator.AgentsGenerator.generate_crew_and_kickoff" href="#praisonai.agents_generator.AgentsGenerator.generate_crew_and_kickoff">generate_crew_and_kickoff</a></code></li>
<li><code><a title="praisonai.agents_generator.AgentsGenerator.is_function_or_decorated" href="#praisonai.agents_generator.AgentsGenerator.is_function_or_decorated">is_function_or_decorated</a></code></li>
<li><code><a title="praisonai.agents_generator.AgentsGenerator.load_tools_from_module" href="#praisonai.agents_generator.AgentsGenerator.load_tools_from_module">load_tools_from_module</a></code></li>
<li><code><a title="praisonai.agents_generator.AgentsGenerator.load_tools_from_module_class" href="#praisonai.agents_generator.AgentsGenerator.load_tools_from_module_class">load_tools_from_module_class</a></code></li>
<li><code><a title="praisonai.agents_generator.AgentsGenerator.load_tools_from_package" href="#praisonai.agents_generator.AgentsGenerator.load_tools_from_package">load_tools_from_package</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-622
View File
@@ -1,622 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.auto API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.auto</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="praisonai.auto.AutoGenerator"><code class="flex name class">
<span>class <span class="ident">AutoGenerator</span></span>
<span>(</span><span>topic='Movie Story writing about AI', agent_file='test.yaml', framework='crewai', config_list: Optional[List[Dict]] = None)</span>
</code></dt>
<dd>
<div class="desc"><p>Initialize the AutoGenerator class with the specified topic, agent file, and framework.
Note: autogen framework is different from this AutoGenerator class.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>topic</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The topic for the generated team structure. Defaults to "Movie Story writing about AI".</dd>
<dt><strong><code>agent_file</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The name of the YAML file to save the generated team structure. Defaults to "test.yaml".</dd>
<dt><strong><code>framework</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The framework for the generated team structure. Defaults to "crewai".</dd>
<dt><strong><code>config_list</code></strong> :&ensp;<code>Optional[List[Dict]]</code>, optional</dt>
<dd>A list containing the configuration details for the OpenAI API.
If None, it defaults to using environment variables or hardcoded values.</dd>
</dl>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>config_list</code></strong> :&ensp;<code>list</code></dt>
<dd>A list containing the configuration details for the OpenAI API.</dd>
<dt><strong><code>topic</code></strong> :&ensp;<code>str</code></dt>
<dd>The specified topic for the generated team structure.</dd>
<dt><strong><code>agent_file</code></strong> :&ensp;<code>str</code></dt>
<dd>The specified name of the YAML file to save the generated team structure.</dd>
<dt><strong><code>framework</code></strong> :&ensp;<code>str</code></dt>
<dd>The specified framework for the generated team structure.</dd>
<dt><strong><code>client</code></strong> :&ensp;<code>instructor.Client</code></dt>
<dd>An instance of the instructor.Client class initialized with the specified OpenAI API configuration.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class AutoGenerator:
def __init__(self, topic=&#34;Movie Story writing about AI&#34;, agent_file=&#34;test.yaml&#34;, framework=&#34;crewai&#34;, config_list: Optional[List[Dict]] = None):
&#34;&#34;&#34;
Initialize the AutoGenerator class with the specified topic, agent file, and framework.
Note: autogen framework is different from this AutoGenerator class.
Args:
topic (str, optional): The topic for the generated team structure. Defaults to &#34;Movie Story writing about AI&#34;.
agent_file (str, optional): The name of the YAML file to save the generated team structure. Defaults to &#34;test.yaml&#34;.
framework (str, optional): The framework for the generated team structure. Defaults to &#34;crewai&#34;.
config_list (Optional[List[Dict]], optional): A list containing the configuration details for the OpenAI API.
If None, it defaults to using environment variables or hardcoded values.
Attributes:
config_list (list): A list containing the configuration details for the OpenAI API.
topic (str): The specified topic for the generated team structure.
agent_file (str): The specified name of the YAML file to save the generated team structure.
framework (str): The specified framework for the generated team structure.
client (instructor.Client): An instance of the instructor.Client class initialized with the specified OpenAI API configuration.
&#34;&#34;&#34;
self.config_list = config_list or [
{
&#39;model&#39;: os.environ.get(&#34;OPENAI_MODEL_NAME&#34;, &#34;gpt-4o&#34;),
&#39;base_url&#39;: os.environ.get(&#34;OPENAI_API_BASE&#34;, &#34;https://api.openai.com/v1&#34;),
&#39;api_key&#39;: os.environ.get(&#34;OPENAI_API_KEY&#34;)
}
]
self.topic = topic
self.agent_file = agent_file
self.framework = framework or &#34;crewai&#34;
self.client = instructor.patch(
OpenAI(
base_url=self.config_list[0][&#39;base_url&#39;],
api_key=os.getenv(&#34;OPENAI_API_KEY&#34;),
),
mode=instructor.Mode.JSON,
)
def generate(self):
&#34;&#34;&#34;
Generates a team structure for the specified topic.
Args:
None
Returns:
str: The full path of the YAML file containing the generated team structure.
Raises:
Exception: If the generation process fails.
Usage:
generator = AutoGenerator(framework=&#34;crewai&#34;, topic=&#34;Create a movie script about Cat in Mars&#34;)
path = generator.generate()
print(path)
&#34;&#34;&#34;
response = self.client.chat.completions.create(
model=self.config_list[0][&#39;model&#39;],
response_model=TeamStructure,
max_retries=10,
messages=[
{&#34;role&#34;: &#34;system&#34;, &#34;content&#34;: &#34;You are a helpful assistant designed to output complex team structures.&#34;},
{&#34;role&#34;: &#34;user&#34;, &#34;content&#34;: self.get_user_content()}
]
)
json_data = json.loads(response.model_dump_json())
self.convert_and_save(json_data)
full_path = os.path.abspath(self.agent_file)
return full_path
def convert_and_save(self, json_data):
&#34;&#34;&#34;Converts the provided JSON data into the desired YAML format and saves it to a file.
Args:
json_data (dict): The JSON data representing the team structure.
topic (str, optional): The topic to be inserted into the YAML. Defaults to &#34;Artificial Intelligence&#34;.
agent_file (str, optional): The name of the YAML file to save. Defaults to &#34;test.yaml&#34;.
&#34;&#34;&#34;
yaml_data = {
&#34;framework&#34;: self.framework,
&#34;topic&#34;: self.topic,
&#34;roles&#34;: {},
&#34;dependencies&#34;: []
}
for role_id, role_details in json_data[&#39;roles&#39;].items():
yaml_data[&#39;roles&#39;][role_id] = {
&#34;backstory&#34;: &#34;&#34; + role_details[&#39;backstory&#39;],
&#34;goal&#34;: role_details[&#39;goal&#39;],
&#34;role&#34;: role_details[&#39;role&#39;],
&#34;tasks&#34;: {},
# &#34;tools&#34;: role_details.get(&#39;tools&#39;, []),
&#34;tools&#34;: [&#39;&#39;]
}
for task_id, task_details in role_details[&#39;tasks&#39;].items():
yaml_data[&#39;roles&#39;][role_id][&#39;tasks&#39;][task_id] = {
&#34;description&#34;: &#34;&#34; + task_details[&#39;description&#39;],
&#34;expected_output&#34;: &#34;&#34; + task_details[&#39;expected_output&#39;]
}
# Save to YAML file, maintaining the order
with open(self.agent_file, &#39;w&#39;) as f:
yaml.dump(yaml_data, f, allow_unicode=True, sort_keys=False)
def get_user_content(self):
&#34;&#34;&#34;
Generates a prompt for the OpenAI API to generate a team structure.
Args:
None
Returns:
str: The prompt for the OpenAI API.
Usage:
generator = AutoGenerator(framework=&#34;crewai&#34;, topic=&#34;Create a movie script about Cat in Mars&#34;)
prompt = generator.get_user_content()
print(prompt)
&#34;&#34;&#34;
user_content = &#34;&#34;&#34;Generate a team structure for \&#34;&#34;&#34;&#34; + self.topic + &#34;&#34;&#34;\&#34; task.
No Input data will be provided to the team.
The team will work in sequence. First role will pass the output to the next role, and so on.
The last role will generate the final output.
Think step by step.
With maximum 3 roles, each with 1 task. Include role goals, backstories, task descriptions, and expected outputs.
List of Available Tools: CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool, DirectoryReadTool, FileReadTool, TXTSearchTool, JSONSearchTool, MDXSearchTool, PDFSearchTool, RagTool, ScrapeElementFromWebsiteTool, ScrapeWebsiteTool, WebsiteSearchTool, XMLSearchTool, YoutubeChannelSearchTool, YoutubeVideoSearchTool.
Only use Available Tools. Do Not use any other tools.
Example Below:
Use below example to understand the structure of the output.
The final role you create should satisfy the provided task: &#34;&#34;&#34; + self.topic + &#34;&#34;&#34;.
{
&#34;roles&#34;: {
&#34;narrative_designer&#34;: {
&#34;role&#34;: &#34;Narrative Designer&#34;,
&#34;goal&#34;: &#34;Create AI storylines&#34;,
&#34;backstory&#34;: &#34;Skilled in narrative development for AI, with a focus on story resonance.&#34;,
&#34;tools&#34;: [&#34;ScrapeWebsiteTool&#34;],
&#34;tasks&#34;: {
&#34;story_concept_development&#34;: {
&#34;description&#34;: &#34;Craft a unique AI story concept with depth and engagement using concept from this page the content https://www.asthebirdfliesblog.com/posts/how-to-write-book-story-development .&#34;,
&#34;expected_output&#34;: &#34;Document with narrative arcs, character bios, and settings.&#34;
}
}
},
&#34;scriptwriter&#34;: {
&#34;role&#34;: &#34;Scriptwriter&#34;,
&#34;goal&#34;: &#34;Write scripts from AI concepts&#34;,
&#34;backstory&#34;: &#34;Expert in dialogue and script structure, translating concepts into scripts.&#34;,
&#34;tasks&#34;: {
&#34;scriptwriting_task&#34;: {
&#34;description&#34;: &#34;Turn narrative concepts into scripts, including dialogue and scenes.&#34;,
&#34;expected_output&#34;: &#34;Production-ready script with dialogue and scene details.&#34;
}
}
}
}
}
&#34;&#34;&#34;
return user_content</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="praisonai.auto.AutoGenerator.convert_and_save"><code class="name flex">
<span>def <span class="ident">convert_and_save</span></span>(<span>self, json_data)</span>
</code></dt>
<dd>
<div class="desc"><p>Converts the provided JSON data into the desired YAML format and saves it to a file.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>json_data</code></strong> :&ensp;<code>dict</code></dt>
<dd>The JSON data representing the team structure.</dd>
<dt><strong><code>topic</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The topic to be inserted into the YAML. Defaults to "Artificial Intelligence".</dd>
<dt><strong><code>agent_file</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The name of the YAML file to save. Defaults to "test.yaml".</dd>
</dl></div>
</dd>
<dt id="praisonai.auto.AutoGenerator.generate"><code class="name flex">
<span>def <span class="ident">generate</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Generates a team structure for the specified topic.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>The full path of the YAML file containing the generated team structure.</dd>
</dl>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>Exception</code></dt>
<dd>If the generation process fails.</dd>
</dl>
<h2 id="usage">Usage</h2>
<p>generator = AutoGenerator(framework="crewai", topic="Create a movie script about Cat in Mars")
path = generator.generate()
print(path)</p></div>
</dd>
<dt id="praisonai.auto.AutoGenerator.get_user_content"><code class="name flex">
<span>def <span class="ident">get_user_content</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Generates a prompt for the OpenAI API to generate a team structure.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>str</code></dt>
<dd>The prompt for the OpenAI API.</dd>
</dl>
<h2 id="usage">Usage</h2>
<p>generator = AutoGenerator(framework="crewai", topic="Create a movie script about Cat in Mars")
prompt = generator.get_user_content()
print(prompt)</p></div>
</dd>
</dl>
</dd>
<dt id="praisonai.auto.RoleDetails"><code class="flex name class">
<span>class <span class="ident">RoleDetails</span></span>
<span>(</span><span>**data: Any)</span>
</code></dt>
<dd>
<div class="desc"><p>Usage docs: <a href="https://docs.pydantic.dev/2.9/concepts/models/">https://docs.pydantic.dev/2.9/concepts/models/</a></p>
<p>A base class for creating Pydantic models.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>__class_vars__</code></strong></dt>
<dd>The names of the class variables defined on the model.</dd>
<dt><strong><code>__private_attributes__</code></strong></dt>
<dd>Metadata about the private attributes of the model.</dd>
<dt><strong><code>__signature__</code></strong></dt>
<dd>The synthesized <code>__init__</code> [<code>Signature</code>][inspect.Signature] of the model.</dd>
<dt><strong><code>__pydantic_complete__</code></strong></dt>
<dd>Whether model building is completed, or if there are still undefined fields.</dd>
<dt><strong><code>__pydantic_core_schema__</code></strong></dt>
<dd>The core schema of the model.</dd>
<dt><strong><code>__pydantic_custom_init__</code></strong></dt>
<dd>Whether the model has a custom <code>__init__</code> function.</dd>
<dt><strong><code>__pydantic_decorators__</code></strong></dt>
<dd>Metadata containing the decorators defined on the model.
This replaces <code>Model.__validators__</code> and <code>Model.__root_validators__</code> from Pydantic V1.</dd>
<dt><strong><code>__pydantic_generic_metadata__</code></strong></dt>
<dd>Metadata for generic models; contains data used for a similar purpose to
<strong>args</strong>, <strong>origin</strong>, <strong>parameters</strong> in typing-module generics. May eventually be replaced by these.</dd>
<dt><strong><code>__pydantic_parent_namespace__</code></strong></dt>
<dd>Parent namespace of the model, used for automatic rebuilding of models.</dd>
<dt><strong><code>__pydantic_post_init__</code></strong></dt>
<dd>The name of the post-init method for the model, if defined.</dd>
<dt><strong><code>__pydantic_root_model__</code></strong></dt>
<dd>Whether the model is a [<code>RootModel</code>][pydantic.root_model.RootModel].</dd>
<dt><strong><code>__pydantic_serializer__</code></strong></dt>
<dd>The <code>pydantic-core</code> <code>SchemaSerializer</code> used to dump instances of the model.</dd>
<dt><strong><code>__pydantic_validator__</code></strong></dt>
<dd>The <code>pydantic-core</code> <code>SchemaValidator</code> used to validate instances of the model.</dd>
<dt><strong><code>__pydantic_extra__</code></strong></dt>
<dd>A dictionary containing extra values, if [<code>extra</code>][pydantic.config.ConfigDict.extra]
is set to <code>'allow'</code>.</dd>
<dt><strong><code>__pydantic_fields_set__</code></strong></dt>
<dd>The names of fields explicitly set during instantiation.</dd>
<dt><strong><code>__pydantic_private__</code></strong></dt>
<dd>Values of private attributes set on the model instance.</dd>
</dl>
<p>Create a new model by parsing and validating input data from keyword arguments.</p>
<p>Raises [<code>ValidationError</code>][pydantic_core.ValidationError] if the input data cannot be
validated to form a valid model.</p>
<p><code>self</code> is explicitly positional-only to allow <code>self</code> as a field name.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class RoleDetails(BaseModel):
role: str
goal: str
backstory: str
tasks: Dict[str, TaskDetails]
tools: List[str]</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>pydantic.main.BaseModel</li>
</ul>
<h3>Class variables</h3>
<dl>
<dt id="praisonai.auto.RoleDetails.backstory"><code class="name">var <span class="ident">backstory</span> : str</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.RoleDetails.goal"><code class="name">var <span class="ident">goal</span> : str</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.RoleDetails.model_computed_fields"><code class="name">var <span class="ident">model_computed_fields</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.RoleDetails.model_config"><code class="name">var <span class="ident">model_config</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.RoleDetails.model_fields"><code class="name">var <span class="ident">model_fields</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.RoleDetails.role"><code class="name">var <span class="ident">role</span> : str</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.RoleDetails.tasks"><code class="name">var <span class="ident">tasks</span> : Dict[str, <a title="praisonai.auto.TaskDetails" href="#praisonai.auto.TaskDetails">TaskDetails</a>]</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.RoleDetails.tools"><code class="name">var <span class="ident">tools</span> : List[str]</code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</dd>
<dt id="praisonai.auto.TaskDetails"><code class="flex name class">
<span>class <span class="ident">TaskDetails</span></span>
<span>(</span><span>**data: Any)</span>
</code></dt>
<dd>
<div class="desc"><p>Usage docs: <a href="https://docs.pydantic.dev/2.9/concepts/models/">https://docs.pydantic.dev/2.9/concepts/models/</a></p>
<p>A base class for creating Pydantic models.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>__class_vars__</code></strong></dt>
<dd>The names of the class variables defined on the model.</dd>
<dt><strong><code>__private_attributes__</code></strong></dt>
<dd>Metadata about the private attributes of the model.</dd>
<dt><strong><code>__signature__</code></strong></dt>
<dd>The synthesized <code>__init__</code> [<code>Signature</code>][inspect.Signature] of the model.</dd>
<dt><strong><code>__pydantic_complete__</code></strong></dt>
<dd>Whether model building is completed, or if there are still undefined fields.</dd>
<dt><strong><code>__pydantic_core_schema__</code></strong></dt>
<dd>The core schema of the model.</dd>
<dt><strong><code>__pydantic_custom_init__</code></strong></dt>
<dd>Whether the model has a custom <code>__init__</code> function.</dd>
<dt><strong><code>__pydantic_decorators__</code></strong></dt>
<dd>Metadata containing the decorators defined on the model.
This replaces <code>Model.__validators__</code> and <code>Model.__root_validators__</code> from Pydantic V1.</dd>
<dt><strong><code>__pydantic_generic_metadata__</code></strong></dt>
<dd>Metadata for generic models; contains data used for a similar purpose to
<strong>args</strong>, <strong>origin</strong>, <strong>parameters</strong> in typing-module generics. May eventually be replaced by these.</dd>
<dt><strong><code>__pydantic_parent_namespace__</code></strong></dt>
<dd>Parent namespace of the model, used for automatic rebuilding of models.</dd>
<dt><strong><code>__pydantic_post_init__</code></strong></dt>
<dd>The name of the post-init method for the model, if defined.</dd>
<dt><strong><code>__pydantic_root_model__</code></strong></dt>
<dd>Whether the model is a [<code>RootModel</code>][pydantic.root_model.RootModel].</dd>
<dt><strong><code>__pydantic_serializer__</code></strong></dt>
<dd>The <code>pydantic-core</code> <code>SchemaSerializer</code> used to dump instances of the model.</dd>
<dt><strong><code>__pydantic_validator__</code></strong></dt>
<dd>The <code>pydantic-core</code> <code>SchemaValidator</code> used to validate instances of the model.</dd>
<dt><strong><code>__pydantic_extra__</code></strong></dt>
<dd>A dictionary containing extra values, if [<code>extra</code>][pydantic.config.ConfigDict.extra]
is set to <code>'allow'</code>.</dd>
<dt><strong><code>__pydantic_fields_set__</code></strong></dt>
<dd>The names of fields explicitly set during instantiation.</dd>
<dt><strong><code>__pydantic_private__</code></strong></dt>
<dd>Values of private attributes set on the model instance.</dd>
</dl>
<p>Create a new model by parsing and validating input data from keyword arguments.</p>
<p>Raises [<code>ValidationError</code>][pydantic_core.ValidationError] if the input data cannot be
validated to form a valid model.</p>
<p><code>self</code> is explicitly positional-only to allow <code>self</code> as a field name.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class TaskDetails(BaseModel):
description: str
expected_output: str</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>pydantic.main.BaseModel</li>
</ul>
<h3>Class variables</h3>
<dl>
<dt id="praisonai.auto.TaskDetails.description"><code class="name">var <span class="ident">description</span> : str</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.TaskDetails.expected_output"><code class="name">var <span class="ident">expected_output</span> : str</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.TaskDetails.model_computed_fields"><code class="name">var <span class="ident">model_computed_fields</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.TaskDetails.model_config"><code class="name">var <span class="ident">model_config</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.TaskDetails.model_fields"><code class="name">var <span class="ident">model_fields</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</dd>
<dt id="praisonai.auto.TeamStructure"><code class="flex name class">
<span>class <span class="ident">TeamStructure</span></span>
<span>(</span><span>**data: Any)</span>
</code></dt>
<dd>
<div class="desc"><p>Usage docs: <a href="https://docs.pydantic.dev/2.9/concepts/models/">https://docs.pydantic.dev/2.9/concepts/models/</a></p>
<p>A base class for creating Pydantic models.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>__class_vars__</code></strong></dt>
<dd>The names of the class variables defined on the model.</dd>
<dt><strong><code>__private_attributes__</code></strong></dt>
<dd>Metadata about the private attributes of the model.</dd>
<dt><strong><code>__signature__</code></strong></dt>
<dd>The synthesized <code>__init__</code> [<code>Signature</code>][inspect.Signature] of the model.</dd>
<dt><strong><code>__pydantic_complete__</code></strong></dt>
<dd>Whether model building is completed, or if there are still undefined fields.</dd>
<dt><strong><code>__pydantic_core_schema__</code></strong></dt>
<dd>The core schema of the model.</dd>
<dt><strong><code>__pydantic_custom_init__</code></strong></dt>
<dd>Whether the model has a custom <code>__init__</code> function.</dd>
<dt><strong><code>__pydantic_decorators__</code></strong></dt>
<dd>Metadata containing the decorators defined on the model.
This replaces <code>Model.__validators__</code> and <code>Model.__root_validators__</code> from Pydantic V1.</dd>
<dt><strong><code>__pydantic_generic_metadata__</code></strong></dt>
<dd>Metadata for generic models; contains data used for a similar purpose to
<strong>args</strong>, <strong>origin</strong>, <strong>parameters</strong> in typing-module generics. May eventually be replaced by these.</dd>
<dt><strong><code>__pydantic_parent_namespace__</code></strong></dt>
<dd>Parent namespace of the model, used for automatic rebuilding of models.</dd>
<dt><strong><code>__pydantic_post_init__</code></strong></dt>
<dd>The name of the post-init method for the model, if defined.</dd>
<dt><strong><code>__pydantic_root_model__</code></strong></dt>
<dd>Whether the model is a [<code>RootModel</code>][pydantic.root_model.RootModel].</dd>
<dt><strong><code>__pydantic_serializer__</code></strong></dt>
<dd>The <code>pydantic-core</code> <code>SchemaSerializer</code> used to dump instances of the model.</dd>
<dt><strong><code>__pydantic_validator__</code></strong></dt>
<dd>The <code>pydantic-core</code> <code>SchemaValidator</code> used to validate instances of the model.</dd>
<dt><strong><code>__pydantic_extra__</code></strong></dt>
<dd>A dictionary containing extra values, if [<code>extra</code>][pydantic.config.ConfigDict.extra]
is set to <code>'allow'</code>.</dd>
<dt><strong><code>__pydantic_fields_set__</code></strong></dt>
<dd>The names of fields explicitly set during instantiation.</dd>
<dt><strong><code>__pydantic_private__</code></strong></dt>
<dd>Values of private attributes set on the model instance.</dd>
</dl>
<p>Create a new model by parsing and validating input data from keyword arguments.</p>
<p>Raises [<code>ValidationError</code>][pydantic_core.ValidationError] if the input data cannot be
validated to form a valid model.</p>
<p><code>self</code> is explicitly positional-only to allow <code>self</code> as a field name.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class TeamStructure(BaseModel):
roles: Dict[str, RoleDetails]</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>pydantic.main.BaseModel</li>
</ul>
<h3>Class variables</h3>
<dl>
<dt id="praisonai.auto.TeamStructure.model_computed_fields"><code class="name">var <span class="ident">model_computed_fields</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.TeamStructure.model_config"><code class="name">var <span class="ident">model_config</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.TeamStructure.model_fields"><code class="name">var <span class="ident">model_fields</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.auto.TeamStructure.roles"><code class="name">var <span class="ident">roles</span> : Dict[str, <a title="praisonai.auto.RoleDetails" href="#praisonai.auto.RoleDetails">RoleDetails</a>]</code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="praisonai.auto.AutoGenerator" href="#praisonai.auto.AutoGenerator">AutoGenerator</a></code></h4>
<ul class="">
<li><code><a title="praisonai.auto.AutoGenerator.convert_and_save" href="#praisonai.auto.AutoGenerator.convert_and_save">convert_and_save</a></code></li>
<li><code><a title="praisonai.auto.AutoGenerator.generate" href="#praisonai.auto.AutoGenerator.generate">generate</a></code></li>
<li><code><a title="praisonai.auto.AutoGenerator.get_user_content" href="#praisonai.auto.AutoGenerator.get_user_content">get_user_content</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="praisonai.auto.RoleDetails" href="#praisonai.auto.RoleDetails">RoleDetails</a></code></h4>
<ul class="">
<li><code><a title="praisonai.auto.RoleDetails.backstory" href="#praisonai.auto.RoleDetails.backstory">backstory</a></code></li>
<li><code><a title="praisonai.auto.RoleDetails.goal" href="#praisonai.auto.RoleDetails.goal">goal</a></code></li>
<li><code><a title="praisonai.auto.RoleDetails.model_computed_fields" href="#praisonai.auto.RoleDetails.model_computed_fields">model_computed_fields</a></code></li>
<li><code><a title="praisonai.auto.RoleDetails.model_config" href="#praisonai.auto.RoleDetails.model_config">model_config</a></code></li>
<li><code><a title="praisonai.auto.RoleDetails.model_fields" href="#praisonai.auto.RoleDetails.model_fields">model_fields</a></code></li>
<li><code><a title="praisonai.auto.RoleDetails.role" href="#praisonai.auto.RoleDetails.role">role</a></code></li>
<li><code><a title="praisonai.auto.RoleDetails.tasks" href="#praisonai.auto.RoleDetails.tasks">tasks</a></code></li>
<li><code><a title="praisonai.auto.RoleDetails.tools" href="#praisonai.auto.RoleDetails.tools">tools</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="praisonai.auto.TaskDetails" href="#praisonai.auto.TaskDetails">TaskDetails</a></code></h4>
<ul class="">
<li><code><a title="praisonai.auto.TaskDetails.description" href="#praisonai.auto.TaskDetails.description">description</a></code></li>
<li><code><a title="praisonai.auto.TaskDetails.expected_output" href="#praisonai.auto.TaskDetails.expected_output">expected_output</a></code></li>
<li><code><a title="praisonai.auto.TaskDetails.model_computed_fields" href="#praisonai.auto.TaskDetails.model_computed_fields">model_computed_fields</a></code></li>
<li><code><a title="praisonai.auto.TaskDetails.model_config" href="#praisonai.auto.TaskDetails.model_config">model_config</a></code></li>
<li><code><a title="praisonai.auto.TaskDetails.model_fields" href="#praisonai.auto.TaskDetails.model_fields">model_fields</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="praisonai.auto.TeamStructure" href="#praisonai.auto.TeamStructure">TeamStructure</a></code></h4>
<ul class="">
<li><code><a title="praisonai.auto.TeamStructure.model_computed_fields" href="#praisonai.auto.TeamStructure.model_computed_fields">model_computed_fields</a></code></li>
<li><code><a title="praisonai.auto.TeamStructure.model_config" href="#praisonai.auto.TeamStructure.model_config">model_config</a></code></li>
<li><code><a title="praisonai.auto.TeamStructure.model_fields" href="#praisonai.auto.TeamStructure.model_fields">model_fields</a></code></li>
<li><code><a title="praisonai.auto.TeamStructure.roles" href="#praisonai.auto.TeamStructure.roles">roles</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-664
View File
@@ -1,664 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.cli API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.cli</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="praisonai.cli.stream_subprocess"><code class="name flex">
<span>def <span class="ident">stream_subprocess</span></span>(<span>command, env=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Execute a subprocess command and stream the output to the terminal in real-time.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>command</code></strong> :&ensp;<code>list</code></dt>
<dd>A list containing the command and its arguments.</dd>
<dt><strong><code>env</code></strong> :&ensp;<code>dict</code>, optional</dt>
<dd>Environment variables for the subprocess.</dd>
</dl></div>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="praisonai.cli.PraisonAI"><code class="flex name class">
<span>class <span class="ident">PraisonAI</span></span>
<span>(</span><span>agent_file='agents.yaml', framework='', auto=False, init=False, agent_yaml=None, tools=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Initialize the PraisonAI object with default parameters.</p>
<h2 id="parameters">Parameters</h2>
<p>agent_file (str): The default agent file to use. Defaults to "agents.yaml".
framework (str): The default framework to use. Defaults to "crewai".
auto (bool): A flag indicating whether to enable auto mode. Defaults to False.
init (bool): A flag indicating whether to enable initialization mode. Defaults to False.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>config_list</code></strong> :&ensp;<code>list</code></dt>
<dd>A list of configuration dictionaries for the OpenAI API.</dd>
<dt><strong><code>agent_file</code></strong> :&ensp;<code>str</code></dt>
<dd>The agent file to use.</dd>
<dt><strong><code>framework</code></strong> :&ensp;<code>str</code></dt>
<dd>The framework to use.</dd>
<dt><strong><code>auto</code></strong> :&ensp;<code>bool</code></dt>
<dd>A flag indicating whether to enable auto mode.</dd>
<dt><strong><code>init</code></strong> :&ensp;<code>bool</code></dt>
<dd>A flag indicating whether to enable initialization mode.</dd>
<dt><strong><code>agent_yaml</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The content of the YAML file. Defaults to None.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class PraisonAI:
def __init__(self, agent_file=&#34;agents.yaml&#34;, framework=&#34;&#34;, auto=False, init=False, agent_yaml=None, tools=None):
&#34;&#34;&#34;
Initialize the PraisonAI object with default parameters.
Parameters:
agent_file (str): The default agent file to use. Defaults to &#34;agents.yaml&#34;.
framework (str): The default framework to use. Defaults to &#34;crewai&#34;.
auto (bool): A flag indicating whether to enable auto mode. Defaults to False.
init (bool): A flag indicating whether to enable initialization mode. Defaults to False.
Attributes:
config_list (list): A list of configuration dictionaries for the OpenAI API.
agent_file (str): The agent file to use.
framework (str): The framework to use.
auto (bool): A flag indicating whether to enable auto mode.
init (bool): A flag indicating whether to enable initialization mode.
agent_yaml (str, optional): The content of the YAML file. Defaults to None.
&#34;&#34;&#34;
self.agent_yaml = agent_yaml
self.config_list = [
{
&#39;model&#39;: os.environ.get(&#34;OPENAI_MODEL_NAME&#34;, &#34;gpt-4o&#34;),
&#39;base_url&#39;: os.environ.get(&#34;OPENAI_API_BASE&#34;, &#34;https://api.openai.com/v1&#34;),
&#39;api_key&#39;: os.environ.get(&#34;OPENAI_API_KEY&#34;)
}
]
self.agent_file = agent_file
self.framework = framework
self.auto = auto
self.init = init
self.tools = tools or [] # Store tool class names as a list
def run(self):
&#34;&#34;&#34;
Run the PraisonAI application.
&#34;&#34;&#34;
self.main()
def main(self):
&#34;&#34;&#34;
The main function of the PraisonAI object. It parses the command-line arguments,
initializes the necessary attributes, and then calls the appropriate methods based on the
provided arguments.
Args:
self (PraisonAI): An instance of the PraisonAI class.
Returns:
Any: Depending on the arguments provided, the function may return a result from the
AgentsGenerator, a deployment result from the CloudDeployer, or a message indicating
the successful creation of a file.
&#34;&#34;&#34;
args = self.parse_args()
if args is None:
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
result = agents_generator.generate_crew_and_kickoff()
return result
if args.deploy:
from .deploy import CloudDeployer
deployer = CloudDeployer()
deployer.run_commands()
return
if getattr(args, &#39;chat&#39;, False):
self.create_chainlit_chat_interface()
return
if getattr(args, &#39;code&#39;, False):
self.create_code_interface()
return
if getattr(args, &#39;realtime&#39;, False):
self.create_realtime_interface()
return
if getattr(args, &#39;call&#39;, False):
call_args = []
if args.public:
call_args.append(&#39;--public&#39;)
call_module.main(call_args)
return
if args.agent_file == &#39;train&#39;:
package_root = os.path.dirname(os.path.abspath(__file__))
config_yaml_destination = os.path.join(os.getcwd(), &#39;config.yaml&#39;)
# Create config.yaml only if it doesn&#39;t exist or --model or --dataset is provided
if not os.path.exists(config_yaml_destination) or args.model or args.dataset:
config = generate_config(
model_name=args.model,
hf_model_name=args.hf,
ollama_model_name=args.ollama,
dataset=[{
&#34;name&#34;: args.dataset
}]
)
with open(&#39;config.yaml&#39;, &#39;w&#39;) as f:
yaml.dump(config, f, default_flow_style=False, indent=2)
# Overwrite huggingface_save and ollama_save if --hf or --ollama are provided
if args.hf:
config[&#34;huggingface_save&#34;] = &#34;true&#34;
if args.ollama:
config[&#34;ollama_save&#34;] = &#34;true&#34;
if &#39;init&#39; in sys.argv:
from praisonai.setup.setup_conda_env import main as setup_conda_main
setup_conda_main()
print(&#34;All packages installed&#34;)
return
try:
result = subprocess.check_output([&#39;conda&#39;, &#39;env&#39;, &#39;list&#39;])
if &#39;praison_env&#39; in result.decode(&#39;utf-8&#39;):
print(&#34;Conda environment &#39;praison_env&#39; found.&#34;)
else:
raise subprocess.CalledProcessError(1, &#39;grep&#39;)
except subprocess.CalledProcessError:
print(&#34;Conda environment &#39;praison_env&#39; not found. Setting it up...&#34;)
from praisonai.setup.setup_conda_env import main as setup_conda_main
setup_conda_main()
print(&#34;All packages installed.&#34;)
train_args = sys.argv[2:] # Get all arguments after &#39;train&#39;
train_script_path = os.path.join(package_root, &#39;train.py&#39;)
# Set environment variables
env = os.environ.copy()
env[&#39;PYTHONUNBUFFERED&#39;] = &#39;1&#39;
stream_subprocess([&#39;conda&#39;, &#39;run&#39;, &#39;--no-capture-output&#39;, &#39;--name&#39;, &#39;praison_env&#39;, &#39;python&#39;, &#39;-u&#39;, train_script_path, &#39;train&#39;], env=env)
return
invocation_cmd = &#34;praisonai&#34;
version_string = f&#34;PraisonAI version {__version__}&#34;
self.framework = args.framework or self.framework
if args.agent_file:
if args.agent_file.startswith(&#34;tests.test&#34;): # Argument used for testing purposes. eg: python -m unittest tests.test
print(&#34;test&#34;)
else:
self.agent_file = args.agent_file
if args.auto or args.init:
temp_topic = &#39; &#39;.join(args.auto) if args.auto else &#39; &#39;.join(args.init)
self.topic = temp_topic
elif self.auto or self.init: # Use the auto attribute if args.auto is not provided
self.topic = self.auto
if args.auto or self.auto:
self.agent_file = &#34;test.yaml&#34;
generator = AutoGenerator(topic=self.topic , framework=self.framework, agent_file=self.agent_file)
self.agent_file = generator.generate()
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
result = agents_generator.generate_crew_and_kickoff()
return result
elif args.init or self.init:
self.agent_file = &#34;agents.yaml&#34;
generator = AutoGenerator(topic=self.topic , framework=self.framework, agent_file=self.agent_file)
self.agent_file = generator.generate()
print(&#34;File {} created successfully&#34;.format(self.agent_file))
return &#34;File {} created successfully&#34;.format(self.agent_file)
if args.ui:
if args.ui == &#34;gradio&#34;:
self.create_gradio_interface()
elif args.ui == &#34;chainlit&#34;:
self.create_chainlit_interface()
else:
# Modify below code to allow default ui
agents_generator = AgentsGenerator(
self.agent_file,
self.framework,
self.config_list,
agent_yaml=self.agent_yaml,
tools=self.tools # Pass tools to AgentsGenerator
)
result = agents_generator.generate_crew_and_kickoff()
return result
else:
agents_generator = AgentsGenerator(
self.agent_file,
self.framework,
self.config_list,
agent_yaml=self.agent_yaml,
tools=self.tools # Pass tools to AgentsGenerator
)
result = agents_generator.generate_crew_and_kickoff()
return result
def parse_args(self):
&#34;&#34;&#34;
Parse the command-line arguments for the PraisonAI CLI.
Args:
self (PraisonAI): An instance of the PraisonAI class.
Returns:
argparse.Namespace: An object containing the parsed command-line arguments.
Raises:
argparse.ArgumentError: If the arguments provided are invalid.
Example:
&gt;&gt;&gt; args = praison_ai.parse_args()
&gt;&gt;&gt; print(args.agent_file) # Output: &#39;agents.yaml&#39;
&#34;&#34;&#34;
parser = argparse.ArgumentParser(prog=&#34;praisonai&#34;, description=&#34;praisonAI command-line interface&#34;)
parser.add_argument(&#34;--framework&#34;, choices=[&#34;crewai&#34;, &#34;autogen&#34;], help=&#34;Specify the framework&#34;)
parser.add_argument(&#34;--ui&#34;, choices=[&#34;chainlit&#34;, &#34;gradio&#34;], help=&#34;Specify the UI framework (gradio or chainlit).&#34;)
parser.add_argument(&#34;--auto&#34;, nargs=argparse.REMAINDER, help=&#34;Enable auto mode and pass arguments for it&#34;)
parser.add_argument(&#34;--init&#34;, nargs=argparse.REMAINDER, help=&#34;Enable auto mode and pass arguments for it&#34;)
parser.add_argument(&#34;agent_file&#34;, nargs=&#34;?&#34;, help=&#34;Specify the agent file&#34;)
parser.add_argument(&#34;--deploy&#34;, action=&#34;store_true&#34;, help=&#34;Deploy the application&#34;)
parser.add_argument(&#34;--model&#34;, type=str, help=&#34;Model name&#34;)
parser.add_argument(&#34;--hf&#34;, type=str, help=&#34;Hugging Face model name&#34;)
parser.add_argument(&#34;--ollama&#34;, type=str, help=&#34;Ollama model name&#34;)
parser.add_argument(&#34;--dataset&#34;, type=str, help=&#34;Dataset name for training&#34;, default=&#34;yahma/alpaca-cleaned&#34;)
parser.add_argument(&#34;--realtime&#34;, action=&#34;store_true&#34;, help=&#34;Start the realtime voice interaction interface&#34;)
parser.add_argument(&#34;--call&#34;, action=&#34;store_true&#34;, help=&#34;Start the PraisonAI Call server&#34;)
parser.add_argument(&#34;--public&#34;, action=&#34;store_true&#34;, help=&#34;Use ngrok to expose the server publicly (only with --call)&#34;)
args, unknown_args = parser.parse_known_args()
if unknown_args and unknown_args[0] == &#39;-b&#39; and unknown_args[1] == &#39;api:app&#39;:
args.agent_file = &#39;agents.yaml&#39;
if args.agent_file == &#39;api:app&#39; or args.agent_file == &#39;/app/api:app&#39;:
args.agent_file = &#39;agents.yaml&#39;
if args.agent_file == &#39;ui&#39;:
args.ui = &#39;chainlit&#39;
if args.agent_file == &#39;chat&#39;:
args.ui = &#39;chainlit&#39;
args.chat = True
if args.agent_file == &#39;code&#39;:
args.ui = &#39;chainlit&#39;
args.code = True
if args.agent_file == &#39;realtime&#39;:
args.realtime = True
if args.agent_file == &#39;call&#39;:
args.call = True
return args
def create_chainlit_chat_interface(self):
&#34;&#34;&#34;
Create a Chainlit interface for the chat application.
This function sets up a Chainlit application that listens for messages.
When a message is received, it runs PraisonAI with the provided message as the topic.
The generated agents are then used to perform tasks.
Returns:
None: This function does not return any value. It starts the Chainlit application.
&#34;&#34;&#34;
if CHAINLIT_AVAILABLE:
import praisonai
os.environ[&#34;CHAINLIT_PORT&#34;] = &#34;8084&#34;
root_path = os.path.join(os.path.expanduser(&#34;~&#34;), &#34;.praison&#34;)
os.environ[&#34;CHAINLIT_APP_ROOT&#34;] = root_path
public_folder = os.path.join(os.path.dirname(praisonai.__file__), &#39;public&#39;)
if not os.path.exists(os.path.join(root_path, &#34;public&#34;)): # Check if the folder exists in the current directory
if os.path.exists(public_folder):
shutil.copytree(public_folder, os.path.join(root_path, &#34;public&#34;), dirs_exist_ok=True)
logging.info(&#34;Public folder copied successfully!&#34;)
else:
logging.info(&#34;Public folder not found in the package.&#34;)
else:
logging.info(&#34;Public folder already exists.&#34;)
chat_ui_path = os.path.join(os.path.dirname(praisonai.__file__), &#39;ui&#39;, &#39;chat.py&#39;)
chainlit_run([chat_ui_path])
else:
print(&#34;ERROR: Chat UI is not installed. Please install it with &#39;pip install \&#34;praisonai\[chat]\&#34;&#39; to use the chat UI.&#34;)
def create_code_interface(self):
&#34;&#34;&#34;
Create a Chainlit interface for the code application.
This function sets up a Chainlit application that listens for messages.
When a message is received, it runs PraisonAI with the provided message as the topic.
The generated agents are then used to perform tasks.
Returns:
None: This function does not return any value. It starts the Chainlit application.
&#34;&#34;&#34;
if CHAINLIT_AVAILABLE:
import praisonai
os.environ[&#34;CHAINLIT_PORT&#34;] = &#34;8086&#34;
root_path = os.path.join(os.path.expanduser(&#34;~&#34;), &#34;.praison&#34;)
os.environ[&#34;CHAINLIT_APP_ROOT&#34;] = root_path
public_folder = os.path.join(os.path.dirname(__file__), &#39;public&#39;)
if not os.path.exists(os.path.join(root_path, &#34;public&#34;)): # Check if the folder exists in the current directory
if os.path.exists(public_folder):
shutil.copytree(public_folder, os.path.join(root_path, &#34;public&#34;), dirs_exist_ok=True)
logging.info(&#34;Public folder copied successfully!&#34;)
else:
logging.info(&#34;Public folder not found in the package.&#34;)
else:
logging.info(&#34;Public folder already exists.&#34;)
code_ui_path = os.path.join(os.path.dirname(praisonai.__file__), &#39;ui&#39;, &#39;code.py&#39;)
chainlit_run([code_ui_path])
else:
print(&#34;ERROR: Code UI is not installed. Please install it with &#39;pip install \&#34;praisonai\[code]\&#34;&#39; to use the code UI.&#34;)
def create_gradio_interface(self):
&#34;&#34;&#34;
Create a Gradio interface for generating agents and performing tasks.
Args:
self (PraisonAI): An instance of the PraisonAI class.
Returns:
None: This method does not return any value. It launches the Gradio interface.
Raises:
None: This method does not raise any exceptions.
Example:
&gt;&gt;&gt; praison_ai.create_gradio_interface()
&#34;&#34;&#34;
if GRADIO_AVAILABLE:
def generate_crew_and_kickoff_interface(auto_args, framework):
&#34;&#34;&#34;
Generate a crew and kick off tasks based on the provided auto arguments and framework.
Args:
auto_args (list): Topic.
framework (str): The framework to use for generating agents.
Returns:
str: A string representing the result of generating the crew and kicking off tasks.
Raises:
None: This method does not raise any exceptions.
Example:
&gt;&gt;&gt; result = generate_crew_and_kickoff_interface(&#34;Create a movie about Cat in Mars&#34;, &#34;crewai&#34;)
&gt;&gt;&gt; print(result)
&#34;&#34;&#34;
self.framework = framework
self.agent_file = &#34;test.yaml&#34;
generator = AutoGenerator(topic=auto_args , framework=self.framework)
self.agent_file = generator.generate()
agents_generator = AgentsGenerator(self.agent_file, self.framework, self.config_list)
result = agents_generator.generate_crew_and_kickoff()
return result
gr.Interface(
fn=generate_crew_and_kickoff_interface,
inputs=[gr.Textbox(lines=2, label=&#34;Auto Args&#34;), gr.Dropdown(choices=[&#34;crewai&#34;, &#34;autogen&#34;], label=&#34;Framework&#34;)],
outputs=&#34;textbox&#34;,
title=&#34;Praison AI Studio&#34;,
description=&#34;Create Agents and perform tasks&#34;,
theme=&#34;default&#34;
).launch()
else:
print(&#34;ERROR: Gradio is not installed. Please install it with &#39;pip install gradio&#39; to use this feature.&#34;)
def create_chainlit_interface(self):
&#34;&#34;&#34;
Create a Chainlit interface for generating agents and performing tasks.
This function sets up a Chainlit application that listens for messages.
When a message is received, it runs PraisonAI with the provided message as the topic.
The generated agents are then used to perform tasks.
Returns:
None: This function does not return any value. It starts the Chainlit application.
&#34;&#34;&#34;
if CHAINLIT_AVAILABLE:
import praisonai
os.environ[&#34;CHAINLIT_PORT&#34;] = &#34;8082&#34;
# Get the path to the &#39;public&#39; folder within the package
public_folder = os.path.join(os.path.dirname(praisonai.__file__), &#39;public&#39;)
if not os.path.exists(&#34;public&#34;): # Check if the folder exists in the current directory
if os.path.exists(public_folder):
shutil.copytree(public_folder, &#39;public&#39;, dirs_exist_ok=True)
logging.info(&#34;Public folder copied successfully!&#34;)
else:
logging.info(&#34;Public folder not found in the package.&#34;)
else:
logging.info(&#34;Public folder already exists.&#34;)
chainlit_ui_path = os.path.join(os.path.dirname(praisonai.__file__), &#39;chainlit_ui.py&#39;)
chainlit_run([chainlit_ui_path])
else:
print(&#34;ERROR: Chainlit is not installed. Please install it with &#39;pip install \&#34;praisonai\[ui]\&#34;&#39; to use the UI.&#34;)
def create_realtime_interface(self):
&#34;&#34;&#34;
Create a Chainlit interface for the realtime voice interaction application.
&#34;&#34;&#34;
if CHAINLIT_AVAILABLE:
import praisonai
os.environ[&#34;CHAINLIT_PORT&#34;] = &#34;8088&#34; # Ensure this port is not in use by another service
root_path = os.path.join(os.path.expanduser(&#34;~&#34;), &#34;.praison&#34;)
os.environ[&#34;CHAINLIT_APP_ROOT&#34;] = root_path
public_folder = os.path.join(os.path.dirname(praisonai.__file__), &#39;public&#39;)
if not os.path.exists(os.path.join(root_path, &#34;public&#34;)):
if os.path.exists(public_folder):
shutil.copytree(public_folder, os.path.join(root_path, &#34;public&#34;), dirs_exist_ok=True)
logging.info(&#34;Public folder copied successfully!&#34;)
else:
logging.info(&#34;Public folder not found in the package.&#34;)
else:
logging.info(&#34;Public folder already exists.&#34;)
realtime_ui_path = os.path.join(os.path.dirname(praisonai.__file__), &#39;ui&#39;, &#39;realtime.py&#39;)
chainlit_run([realtime_ui_path])
else:
print(&#34;ERROR: Realtime UI is not installed. Please install it with &#39;pip install \&#34;praisonai[realtime]\&#34;&#39; to use the realtime UI.&#34;)</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="praisonai.cli.PraisonAI.create_chainlit_chat_interface"><code class="name flex">
<span>def <span class="ident">create_chainlit_chat_interface</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Create a Chainlit interface for the chat application.</p>
<p>This function sets up a Chainlit application that listens for messages.
When a message is received, it runs PraisonAI with the provided message as the topic.
The generated agents are then used to perform tasks.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>None</code></dt>
<dd>This function does not return any value. It starts the Chainlit application.</dd>
</dl></div>
</dd>
<dt id="praisonai.cli.PraisonAI.create_chainlit_interface"><code class="name flex">
<span>def <span class="ident">create_chainlit_interface</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Create a Chainlit interface for generating agents and performing tasks.</p>
<p>This function sets up a Chainlit application that listens for messages.
When a message is received, it runs PraisonAI with the provided message as the topic.
The generated agents are then used to perform tasks.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>None</code></dt>
<dd>This function does not return any value. It starts the Chainlit application.</dd>
</dl></div>
</dd>
<dt id="praisonai.cli.PraisonAI.create_code_interface"><code class="name flex">
<span>def <span class="ident">create_code_interface</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Create a Chainlit interface for the code application.</p>
<p>This function sets up a Chainlit application that listens for messages.
When a message is received, it runs PraisonAI with the provided message as the topic.
The generated agents are then used to perform tasks.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>None</code></dt>
<dd>This function does not return any value. It starts the Chainlit application.</dd>
</dl></div>
</dd>
<dt id="praisonai.cli.PraisonAI.create_gradio_interface"><code class="name flex">
<span>def <span class="ident">create_gradio_interface</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Create a Gradio interface for generating agents and performing tasks.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>self</code></strong> :&ensp;<code><a title="praisonai.cli.PraisonAI" href="#praisonai.cli.PraisonAI">PraisonAI</a></code></dt>
<dd>An instance of the PraisonAI class.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>None</code></dt>
<dd>This method does not return any value. It launches the Gradio interface.</dd>
</dl>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>None</code></dt>
<dd>This method does not raise any exceptions.</dd>
</dl>
<h2 id="example">Example</h2>
<pre><code class="language-python-repl">&gt;&gt;&gt; praison_ai.create_gradio_interface()
</code></pre></div>
</dd>
<dt id="praisonai.cli.PraisonAI.create_realtime_interface"><code class="name flex">
<span>def <span class="ident">create_realtime_interface</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Create a Chainlit interface for the realtime voice interaction application.</p></div>
</dd>
<dt id="praisonai.cli.PraisonAI.main"><code class="name flex">
<span>def <span class="ident">main</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>The main function of the PraisonAI object. It parses the command-line arguments,
initializes the necessary attributes, and then calls the appropriate methods based on the
provided arguments.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>self</code></strong> :&ensp;<code><a title="praisonai.cli.PraisonAI" href="#praisonai.cli.PraisonAI">PraisonAI</a></code></dt>
<dd>An instance of the PraisonAI class.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>Any</code></dt>
<dd>Depending on the arguments provided, the function may return a result from the</dd>
</dl>
<p>AgentsGenerator, a deployment result from the CloudDeployer, or a message indicating
the successful creation of a file.</p></div>
</dd>
<dt id="praisonai.cli.PraisonAI.parse_args"><code class="name flex">
<span>def <span class="ident">parse_args</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Parse the command-line arguments for the PraisonAI CLI.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>self</code></strong> :&ensp;<code><a title="praisonai.cli.PraisonAI" href="#praisonai.cli.PraisonAI">PraisonAI</a></code></dt>
<dd>An instance of the PraisonAI class.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>argparse.Namespace</code></dt>
<dd>An object containing the parsed command-line arguments.</dd>
</dl>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>argparse.ArgumentError</code></dt>
<dd>If the arguments provided are invalid.</dd>
</dl>
<h2 id="example">Example</h2>
<pre><code class="language-python-repl">&gt;&gt;&gt; args = praison_ai.parse_args()
&gt;&gt;&gt; print(args.agent_file) # Output: 'agents.yaml'
</code></pre></div>
</dd>
<dt id="praisonai.cli.PraisonAI.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Run the PraisonAI application.</p></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="praisonai.cli.stream_subprocess" href="#praisonai.cli.stream_subprocess">stream_subprocess</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="praisonai.cli.PraisonAI" href="#praisonai.cli.PraisonAI">PraisonAI</a></code></h4>
<ul class="">
<li><code><a title="praisonai.cli.PraisonAI.create_chainlit_chat_interface" href="#praisonai.cli.PraisonAI.create_chainlit_chat_interface">create_chainlit_chat_interface</a></code></li>
<li><code><a title="praisonai.cli.PraisonAI.create_chainlit_interface" href="#praisonai.cli.PraisonAI.create_chainlit_interface">create_chainlit_interface</a></code></li>
<li><code><a title="praisonai.cli.PraisonAI.create_code_interface" href="#praisonai.cli.PraisonAI.create_code_interface">create_code_interface</a></code></li>
<li><code><a title="praisonai.cli.PraisonAI.create_gradio_interface" href="#praisonai.cli.PraisonAI.create_gradio_interface">create_gradio_interface</a></code></li>
<li><code><a title="praisonai.cli.PraisonAI.create_realtime_interface" href="#praisonai.cli.PraisonAI.create_realtime_interface">create_realtime_interface</a></code></li>
<li><code><a title="praisonai.cli.PraisonAI.main" href="#praisonai.cli.PraisonAI.main">main</a></code></li>
<li><code><a title="praisonai.cli.PraisonAI.parse_args" href="#praisonai.cli.PraisonAI.parse_args">parse_args</a></code></li>
<li><code><a title="praisonai.cli.PraisonAI.run" href="#praisonai.cli.PraisonAI.run">run</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-279
View File
@@ -1,279 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.deploy API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.deploy</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="praisonai.deploy.CloudDeployer"><code class="flex name class">
<span>class <span class="ident">CloudDeployer</span></span>
</code></dt>
<dd>
<div class="desc"><p>A class for deploying a cloud-based application.</p>
<h2 id="attributes">Attributes</h2>
<p>None</p>
<h2 id="methods">Methods</h2>
<p><strong>init</strong>(self):
Loads environment variables from .env file or system and sets them.</p>
<p>Loads environment variables from .env file or system and sets them.</p>
<h2 id="parameters">Parameters</h2>
<p>self: An instance of the CloudDeployer class.</p>
<h2 id="returns">Returns</h2>
<p>None</p>
<h2 id="raises">Raises</h2>
<p>None</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class CloudDeployer:
&#34;&#34;&#34;
A class for deploying a cloud-based application.
Attributes:
None
Methods:
__init__(self):
Loads environment variables from .env file or system and sets them.
&#34;&#34;&#34;
def __init__(self):
&#34;&#34;&#34;
Loads environment variables from .env file or system and sets them.
Parameters:
self: An instance of the CloudDeployer class.
Returns:
None
Raises:
None
&#34;&#34;&#34;
# Load environment variables from .env file or system
load_dotenv()
self.set_environment_variables()
def create_dockerfile(self):
&#34;&#34;&#34;
Creates a Dockerfile for the application.
Parameters:
self: An instance of the CloudDeployer class.
Returns:
None
Raises:
None
This method creates a Dockerfile in the current directory with the specified content.
The Dockerfile is used to build a Docker image for the application.
The content of the Dockerfile includes instructions to use the Python 3.11-slim base image,
set the working directory to /app, copy the current directory contents into the container,
install the required Python packages (flask, praisonai, gunicorn, and markdown),
expose port 8080, and run the application using Gunicorn.
&#34;&#34;&#34;
with open(&#34;Dockerfile&#34;, &#34;w&#34;) as file:
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.2.22 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;)
def create_api_file(self):
&#34;&#34;&#34;
Creates an API file for the application.
Parameters:
self (CloudDeployer): An instance of the CloudDeployer class.
Returns:
None
This method creates an API file named &#34;api.py&#34; in the current directory. The file contains a basic Flask application that uses the PraisonAI library to run a simple agent and returns the output as an HTML page. The application listens on the root path (&#34;/&#34;) and uses the Markdown library to format the output.
&#34;&#34;&#34;
with open(&#34;api.py&#34;, &#34;w&#34;) as file:
file.write(&#34;from flask import Flask\n&#34;)
file.write(&#34;from praisonai import PraisonAI\n&#34;)
file.write(&#34;import markdown\n\n&#34;)
file.write(&#34;app = Flask(__name__)\n\n&#34;)
file.write(&#34;def basic():\n&#34;)
file.write(&#34; praisonai = PraisonAI(agent_file=\&#34;agents.yaml\&#34;)\n&#34;)
file.write(&#34; return praisonai.run()\n\n&#34;)
file.write(&#34;@app.route(&#39;/&#39;)\n&#34;)
file.write(&#34;def home():\n&#34;)
file.write(&#34; output = basic()\n&#34;)
file.write(&#34; html_output = markdown.markdown(output)\n&#34;)
file.write(&#34; return f&#39;&lt;html&gt;&lt;body&gt;{html_output}&lt;/body&gt;&lt;/html&gt;&#39;\n\n&#34;)
file.write(&#34;if __name__ == \&#34;__main__\&#34;:\n&#34;)
file.write(&#34; app.run(debug=True)\n&#34;)
def set_environment_variables(self):
&#34;&#34;&#34;Sets environment variables with fallback to .env values or defaults.&#34;&#34;&#34;
os.environ[&#34;OPENAI_MODEL_NAME&#34;] = os.getenv(&#34;OPENAI_MODEL_NAME&#34;, &#34;gpt-4o&#34;)
os.environ[&#34;OPENAI_API_KEY&#34;] = os.getenv(&#34;OPENAI_API_KEY&#34;, &#34;Enter your API key&#34;)
os.environ[&#34;OPENAI_API_BASE&#34;] = os.getenv(&#34;OPENAI_API_BASE&#34;, &#34;https://api.openai.com/v1&#34;)
def run_commands(self):
&#34;&#34;&#34;
Sets environment variables with fallback to .env values or defaults.
Parameters:
None
Returns:
None
Raises:
None
This method sets environment variables for the application. It uses the `os.environ` dictionary to set the following environment variables:
- `OPENAI_MODEL_NAME`: The name of the OpenAI model to use. If not specified in the .env file, it defaults to &#34;gpt-4o&#34;.
- `OPENAI_API_KEY`: The API key for accessing the OpenAI API. If not specified in the .env file, it defaults to &#34;Enter your API key&#34;.
- `OPENAI_API_BASE`: The base URL for the OpenAI API. If not specified in the .env file, it defaults to &#34;https://api.openai.com/v1&#34;.
&#34;&#34;&#34;
self.create_api_file()
self.create_dockerfile()
&#34;&#34;&#34;Runs a sequence of shell commands for deployment, continues on error.&#34;&#34;&#34;
commands = [
&#34;yes | gcloud auth configure-docker us-central1-docker.pkg.dev&#34;,
&#34;gcloud artifacts repositories create praisonai-repository --repository-format=docker --location=us-central1&#34;,
&#34;docker build --platform linux/amd64 -t gcr.io/$(gcloud config get-value project)/praisonai-app:latest .&#34;,
&#34;docker tag gcr.io/$(gcloud config get-value project)/praisonai-app:latest us-central1-docker.pkg.dev/$(gcloud config get-value project)/praisonai-repository/praisonai-app:latest&#34;,
&#34;docker push us-central1-docker.pkg.dev/$(gcloud config get-value project)/praisonai-repository/praisonai-app:latest&#34;,
&#34;gcloud run deploy praisonai-service --image us-central1-docker.pkg.dev/$(gcloud config get-value project)/praisonai-repository/praisonai-app:latest --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}&#34;
]
for cmd in commands:
try:
subprocess.run(cmd, shell=True, check=True)
except subprocess.CalledProcessError as e:
print(f&#34;ERROR: Command &#39;{e.cmd}&#39; failed with exit status {e.returncode}&#34;)
print(f&#34;Continuing with the next command...&#34;)</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="praisonai.deploy.CloudDeployer.create_api_file"><code class="name flex">
<span>def <span class="ident">create_api_file</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Creates an API file for the application.</p>
<h2 id="parameters">Parameters</h2>
<p>self (CloudDeployer): An instance of the CloudDeployer class.</p>
<h2 id="returns">Returns</h2>
<p>None
This method creates an API file named "api.py" in the current directory. The file contains a basic Flask application that uses the PraisonAI library to run a simple agent and returns the output as an HTML page. The application listens on the root path ("/") and uses the Markdown library to format the output.</p></div>
</dd>
<dt id="praisonai.deploy.CloudDeployer.create_dockerfile"><code class="name flex">
<span>def <span class="ident">create_dockerfile</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Creates a Dockerfile for the application.</p>
<h2 id="parameters">Parameters</h2>
<p>self: An instance of the CloudDeployer class.</p>
<h2 id="returns">Returns</h2>
<p>None</p>
<h2 id="raises">Raises</h2>
<p>None
This method creates a Dockerfile in the current directory with the specified content.
The Dockerfile is used to build a Docker image for the application.
The content of the Dockerfile includes instructions to use the Python 3.11-slim base image,
set the working directory to /app, copy the current directory contents into the container,
install the required Python packages (flask, praisonai, gunicorn, and markdown),
expose port 8080, and run the application using Gunicorn.</p></div>
</dd>
<dt id="praisonai.deploy.CloudDeployer.run_commands"><code class="name flex">
<span>def <span class="ident">run_commands</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Sets environment variables with fallback to .env values or defaults.</p>
<h2 id="parameters">Parameters</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>None</p>
<h2 id="raises">Raises</h2>
<p>None
This method sets environment variables for the application. It uses the <code>os.environ</code> dictionary to set the following environment variables:</p>
<ul>
<li><code>OPENAI_MODEL_NAME</code>: The name of the OpenAI model to use. If not specified in the .env file, it defaults to "gpt-4o".</li>
<li><code>OPENAI_API_KEY</code>: The API key for accessing the OpenAI API. If not specified in the .env file, it defaults to "Enter your API key".</li>
<li><code>OPENAI_API_BASE</code>: The base URL for the OpenAI API. If not specified in the .env file, it defaults to "https://api.openai.com/v1".</li>
</ul></div>
</dd>
<dt id="praisonai.deploy.CloudDeployer.set_environment_variables"><code class="name flex">
<span>def <span class="ident">set_environment_variables</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Sets environment variables with fallback to .env values or defaults.</p></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="praisonai.deploy.CloudDeployer" href="#praisonai.deploy.CloudDeployer">CloudDeployer</a></code></h4>
<ul class="">
<li><code><a title="praisonai.deploy.CloudDeployer.create_api_file" href="#praisonai.deploy.CloudDeployer.create_api_file">create_api_file</a></code></li>
<li><code><a title="praisonai.deploy.CloudDeployer.create_dockerfile" href="#praisonai.deploy.CloudDeployer.create_dockerfile">create_dockerfile</a></code></li>
<li><code><a title="praisonai.deploy.CloudDeployer.run_commands" href="#praisonai.deploy.CloudDeployer.run_commands">run_commands</a></code></li>
<li><code><a title="praisonai.deploy.CloudDeployer.set_environment_variables" href="#praisonai.deploy.CloudDeployer.set_environment_variables">set_environment_variables</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
@@ -1,188 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.inbuilt_tools.autogen_tools API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.inbuilt_tools.autogen_tools</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_CSVSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_CSVSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_CodeDocsSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_CodeDocsSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_DOCXSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_DOCXSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_DirectoryReadTool"><code class="name flex">
<span>def <span class="ident">autogen_DirectoryReadTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_DirectorySearchTool"><code class="name flex">
<span>def <span class="ident">autogen_DirectorySearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_FileReadTool"><code class="name flex">
<span>def <span class="ident">autogen_FileReadTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_JSONSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_JSONSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_MDXSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_MDXSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_PDFSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_PDFSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_RagTool"><code class="name flex">
<span>def <span class="ident">autogen_RagTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeElementFromWebsiteTool"><code class="name flex">
<span>def <span class="ident">autogen_ScrapeElementFromWebsiteTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeWebsiteTool"><code class="name flex">
<span>def <span class="ident">autogen_ScrapeWebsiteTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_TXTSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_TXTSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_WebsiteSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_WebsiteSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_XMLSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_XMLSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeChannelSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_YoutubeChannelSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeVideoSearchTool"><code class="name flex">
<span>def <span class="ident">autogen_YoutubeVideoSearchTool</span></span>(<span>assistant, user_proxy)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.inbuilt_tools.autogen_tools.create_autogen_tool_function"><code class="name flex">
<span>def <span class="ident">create_autogen_tool_function</span></span>(<span>tool_name)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai.inbuilt_tools" href="index.html">praisonai.inbuilt_tools</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_CSVSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_CSVSearchTool">autogen_CSVSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_CodeDocsSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_CodeDocsSearchTool">autogen_CodeDocsSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_DOCXSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_DOCXSearchTool">autogen_DOCXSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_DirectoryReadTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_DirectoryReadTool">autogen_DirectoryReadTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_DirectorySearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_DirectorySearchTool">autogen_DirectorySearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_FileReadTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_FileReadTool">autogen_FileReadTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_JSONSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_JSONSearchTool">autogen_JSONSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_MDXSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_MDXSearchTool">autogen_MDXSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_PDFSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_PDFSearchTool">autogen_PDFSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_RagTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_RagTool">autogen_RagTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeElementFromWebsiteTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeElementFromWebsiteTool">autogen_ScrapeElementFromWebsiteTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeWebsiteTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_ScrapeWebsiteTool">autogen_ScrapeWebsiteTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_TXTSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_TXTSearchTool">autogen_TXTSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_WebsiteSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_WebsiteSearchTool">autogen_WebsiteSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_XMLSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_XMLSearchTool">autogen_XMLSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeChannelSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeChannelSearchTool">autogen_YoutubeChannelSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeVideoSearchTool" href="#praisonai.inbuilt_tools.autogen_tools.autogen_YoutubeVideoSearchTool">autogen_YoutubeVideoSearchTool</a></code></li>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools.create_autogen_tool_function" href="#praisonai.inbuilt_tools.autogen_tools.create_autogen_tool_function">create_autogen_tool_function</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
@@ -1,67 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.inbuilt_tools API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.inbuilt_tools</code></h1>
</header>
<section id="section-intro">
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="praisonai.inbuilt_tools.autogen_tools" href="autogen_tools.html">praisonai.inbuilt_tools.autogen_tools</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="../index.html">praisonai</a></code></li>
</ul>
</li>
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="praisonai.inbuilt_tools.autogen_tools" href="autogen_tools.html">praisonai.inbuilt_tools.autogen_tools</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-69
View File
@@ -1,69 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.inc.config API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.inc.config</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="praisonai.inc.config.generate_config"><code class="name flex">
<span>def <span class="ident">generate_config</span></span>(<span>ollama_save=None, huggingface_save=None, train=None, model_name=None, hf_model_name=None, ollama_model_name=None, model_parameters=None, max_seq_length=None, load_in_4bit=None, lora_r=None, lora_target_modules=None, lora_alpha=None, lora_dropout=None, lora_bias=None, use_gradient_checkpointing=None, random_state=None, use_rslora=None, loftq_config=None, dataset=None, dataset_text_field=None, dataset_num_proc=None, packing=None, per_device_train_batch_size=None, gradient_accumulation_steps=None, warmup_steps=None, num_train_epochs=None, max_steps=None, learning_rate=None, logging_steps=None, optim=None, weight_decay=None, lr_scheduler_type=None, seed=None, output_dir=None, quantization_method=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Generates the configuration for PraisonAI with dynamic overrides.</p></div>
</dd>
</dl>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai.inc" href="index.html">praisonai.inc</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="praisonai.inc.config.generate_config" href="#praisonai.inc.config.generate_config">generate_config</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-72
View File
@@ -1,72 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.inc API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.inc</code></h1>
</header>
<section id="section-intro">
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="praisonai.inc.config" href="config.html">praisonai.inc.config</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.inc.models" href="models.html">praisonai.inc.models</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="../index.html">praisonai</a></code></li>
</ul>
</li>
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="praisonai.inc.config" href="config.html">praisonai.inc.config</a></code></li>
<li><code><a title="praisonai.inc.models" href="models.html">praisonai.inc.models</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-200
View File
@@ -1,200 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.inc.models API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.inc.models</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="praisonai.inc.models.PraisonAIModel"><code class="flex name class">
<span>class <span class="ident">PraisonAIModel</span></span>
<span>(</span><span>model=None, api_key_var=None, base_url=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Initializes the PraisonAIModel with the provided parameters or environment variables.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>model</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The name of the OpenAI model. Defaults to None.</dd>
<dt><strong><code>api_key_var</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The OpenAI API key. Defaults to None.</dd>
<dt><strong><code>base_url</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The base URL for the OpenAI API. Defaults to None.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class PraisonAIModel:
def __init__(self, model=None, api_key_var=None, base_url=None):
&#34;&#34;&#34;
Initializes the PraisonAIModel with the provided parameters or environment variables.
Args:
model (str, optional): The name of the OpenAI model. Defaults to None.
api_key_var (str, optional): The OpenAI API key. Defaults to None.
base_url (str, optional): The base URL for the OpenAI API. Defaults to None.
&#34;&#34;&#34;
self.model = model or os.getenv(&#34;OPENAI_MODEL_NAME&#34;, &#34;gpt-4o&#34;)
if self.model.startswith(&#34;openai/&#34;):
self.api_key_var = &#34;OPENAI_API_KEY&#34;
self.base_url = base_url or &#34;https://api.openai.com/v1&#34;
self.model_name = self.model.replace(&#34;openai/&#34;, &#34;&#34;)
elif self.model.startswith(&#34;groq/&#34;):
self.api_key_var = &#34;GROQ_API_KEY&#34;
self.base_url = base_url or &#34;https://api.groq.com/openai/v1&#34;
self.model_name = self.model.replace(&#34;groq/&#34;, &#34;&#34;)
elif self.model.startswith(&#34;cohere/&#34;):
self.api_key_var = &#34;COHERE_API_KEY&#34;
self.base_url = &#34;&#34;
self.model_name = self.model.replace(&#34;cohere/&#34;, &#34;&#34;)
elif self.model.startswith(&#34;ollama/&#34;):
self.api_key_var = &#34;OLLAMA_API_KEY&#34;
self.base_url = base_url or &#34;http://localhost:11434/v1&#34;
self.model_name = self.model.replace(&#34;ollama/&#34;, &#34;&#34;)
elif self.model.startswith(&#34;anthropic/&#34;):
self.api_key_var = &#34;ANTHROPIC_API_KEY&#34;
self.base_url = &#34;&#34;
self.model_name = self.model.replace(&#34;anthropic/&#34;, &#34;&#34;)
elif self.model.startswith(&#34;google/&#34;):
self.api_key_var = &#34;GOOGLE_API_KEY&#34;
self.base_url = &#34;&#34;
self.model_name = self.model.replace(&#34;google/&#34;, &#34;&#34;)
elif self.model.startswith(&#34;openrouter/&#34;):
self.api_key_var = &#34;OPENROUTER_API_KEY&#34;
self.base_url = base_url or &#34;https://openrouter.ai/api/v1&#34;
self.model_name = self.model.replace(&#34;openrouter/&#34;, &#34;&#34;)
else:
self.api_key_var = api_key_var or &#34;OPENAI_API_KEY&#34;
self.base_url = base_url or os.environ.get(&#34;OPENAI_API_BASE&#34;, &#34;https://api.openai.com/v1&#34;)
self.model_name = self.model
logger.debug(f&#34;Initialized PraisonAIModel with model {self.model_name}, api_key_var {self.api_key_var}, and base_url {self.base_url}&#34;)
self.api_key = os.environ.get(self.api_key_var, &#34;nokey&#34;)
def get_model(self):
&#34;&#34;&#34;
Returns an instance of the langchain Chat client with the configured parameters.
Returns:
Chat: An instance of the langchain Chat client.
&#34;&#34;&#34;
if self.model.startswith(&#34;google/&#34;):
if GOOGLE_GENAI_AVAILABLE:
return ChatGoogleGenerativeAI(
model=self.model_name,
google_api_key=self.api_key
)
else:
raise ImportError(
&#34;Required Langchain Integration &#39;langchain-google-genai&#39; not found. &#34;
&#34;Please install with &#39;pip install langchain-google-genai&#39;&#34;
)
elif self.model.startswith(&#34;cohere/&#34;):
if COHERE_AVAILABLE:
return ChatCohere(
model=self.model_name,
cohere_api_key=self.api_key,
)
else:
raise ImportError(
&#34;Required Langchain Integration &#39;langchain-cohere&#39; not found. &#34;
&#34;Please install with &#39;pip install langchain-cohere&#39;&#34;
)
elif self.model.startswith(&#34;anthropic/&#34;):
if ANTHROPIC_AVAILABLE:
return ChatAnthropic(
model=self.model_name,
anthropic_api_key=self.api_key,
)
else:
raise ImportError(
&#34;Required Langchain Integration &#39;langchain-anthropic&#39; not found. &#34;
&#34;Please install with &#39;pip install langchain-anthropic&#39;&#34;
)
elif OPENAI_AVAILABLE:
return ChatOpenAI(
model=self.model_name,
api_key=self.api_key,
base_url=self.base_url,
)
else:
raise ImportError(
&#34;Required Langchain Integration &#39;langchain-openai&#39; not found. &#34;
&#34;Please install with &#39;pip install langchain-openai&#39;&#34;
)</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="praisonai.inc.models.PraisonAIModel.get_model"><code class="name flex">
<span>def <span class="ident">get_model</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Returns an instance of the langchain Chat client with the configured parameters.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>Chat</code></dt>
<dd>An instance of the langchain Chat client.</dd>
</dl></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai.inc" href="index.html">praisonai.inc</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="praisonai.inc.models.PraisonAIModel" href="#praisonai.inc.models.PraisonAIModel">PraisonAIModel</a></code></h4>
<ul class="">
<li><code><a title="praisonai.inc.models.PraisonAIModel.get_model" href="#praisonai.inc.models.PraisonAIModel.get_model">get_model</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-107
View File
@@ -1,107 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Package <code>praisonai</code></h1>
</header>
<section id="section-intro">
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="praisonai.agents_generator" href="agents_generator.html">praisonai.agents_generator</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.auto" href="auto.html">praisonai.auto</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.cli" href="cli.html">praisonai.cli</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.deploy" href="deploy.html">praisonai.deploy</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.inbuilt_tools" href="inbuilt_tools/index.html">praisonai.inbuilt_tools</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.inc" href="inc/index.html">praisonai.inc</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.setup" href="setup/index.html">praisonai.setup</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.test" href="test.html">praisonai.test</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.ui" href="ui/index.html">praisonai.ui</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.version" href="version.html">praisonai.version</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="praisonai.agents_generator" href="agents_generator.html">praisonai.agents_generator</a></code></li>
<li><code><a title="praisonai.auto" href="auto.html">praisonai.auto</a></code></li>
<li><code><a title="praisonai.cli" href="cli.html">praisonai.cli</a></code></li>
<li><code><a title="praisonai.deploy" href="deploy.html">praisonai.deploy</a></code></li>
<li><code><a title="praisonai.inbuilt_tools" href="inbuilt_tools/index.html">praisonai.inbuilt_tools</a></code></li>
<li><code><a title="praisonai.inc" href="inc/index.html">praisonai.inc</a></code></li>
<li><code><a title="praisonai.setup" href="setup/index.html">praisonai.setup</a></code></li>
<li><code><a title="praisonai.test" href="test.html">praisonai.test</a></code></li>
<li><code><a title="praisonai.ui" href="ui/index.html">praisonai.ui</a></code></li>
<li><code><a title="praisonai.version" href="version.html">praisonai.version</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-69
View File
@@ -1,69 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.setup.build API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.setup.build</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="praisonai.setup.build.build"><code class="name flex">
<span>def <span class="ident">build</span></span>(<span>setup_kwargs)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai.setup" href="index.html">praisonai.setup</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="praisonai.setup.build.build" href="#praisonai.setup.build.build">build</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-77
View File
@@ -1,77 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.setup API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.setup</code></h1>
</header>
<section id="section-intro">
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="praisonai.setup.build" href="build.html">praisonai.setup.build</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.setup.post_install" href="post_install.html">praisonai.setup.post_install</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.setup.setup_conda_env" href="setup_conda_env.html">praisonai.setup.setup_conda_env</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="../index.html">praisonai</a></code></li>
</ul>
</li>
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="praisonai.setup.build" href="build.html">praisonai.setup.build</a></code></li>
<li><code><a title="praisonai.setup.post_install" href="post_install.html">praisonai.setup.post_install</a></code></li>
<li><code><a title="praisonai.setup.setup_conda_env" href="setup_conda_env.html">praisonai.setup.setup_conda_env</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
@@ -1,69 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.setup.post_install API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.setup.post_install</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="praisonai.setup.post_install.main"><code class="name flex">
<span>def <span class="ident">main</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai.setup" href="index.html">praisonai.setup</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="praisonai.setup.post_install.main" href="#praisonai.setup.post_install.main">main</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
@@ -1,69 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.setup.setup_conda_env API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.setup.setup_conda_env</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="praisonai.setup.setup_conda_env.main"><code class="name flex">
<span>def <span class="ident">main</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai.setup" href="index.html">praisonai.setup</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="praisonai.setup.setup_conda_env.main" href="#praisonai.setup.setup_conda_env.main">main</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-73
View File
@@ -1,73 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.test API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.test</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="praisonai.test.generate_crew_and_kickoff"><code class="name flex">
<span>def <span class="ident">generate_crew_and_kickoff</span></span>(<span>agent_file)</span>
</code></dt>
<dd>
<div class="desc"><p>This function generates a crew of agents and kicks off tasks based on the configuration provided in a YAML file.</p>
<p>Parameters:
agent_file (str): The path to the YAML file containing the configuration for the agents and tasks.</p>
<p>Returns:
str: The result of the last task executed by the crew.</p></div>
</dd>
</dl>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="praisonai.test.generate_crew_and_kickoff" href="#praisonai.test.generate_crew_and_kickoff">generate_crew_and_kickoff</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-428
View File
@@ -1,428 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.ui.context API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.ui.context</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="praisonai.ui.context.main"><code class="name flex">
<span>def <span class="ident">main</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="praisonai.ui.context.ContextGatherer"><code class="flex name class">
<span>class <span class="ident">ContextGatherer</span></span>
<span>(</span><span>directory='.', output_file='context.txt', relevant_extensions=None, max_file_size=1000000, max_tokens=900000)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class ContextGatherer:
def __init__(self, directory=&#39;.&#39;, output_file=&#39;context.txt&#39;,
relevant_extensions=None, max_file_size=1_000_000, max_tokens=900000):
self.directory = directory
self.output_file = output_file
self.relevant_extensions = relevant_extensions or [
&#39;.py&#39;, &#39;.js&#39;, &#39;.ts&#39;, &#39;.java&#39;, &#39;.rb&#39;, &#39;.php&#39;, &#39;.pl&#39;, &#39;.pm&#39;, &#39;.c&#39;, &#39;.h&#39;,
&#39;.cpp&#39;, &#39;.hpp&#39;, &#39;.cs&#39;, &#39;.vb&#39;, &#39;.swift&#39;, &#39;.kt&#39;, &#39;.m&#39;, &#39;.mm&#39;, &#39;.go&#39;, &#39;.rs&#39;,
&#39;.hs&#39;, &#39;.r&#39;, &#39;.lua&#39;, &#39;.sh&#39;, &#39;.bat&#39;, &#39;.clj&#39;, &#39;.scala&#39;, &#39;.erl&#39;, &#39;.ex&#39;,
&#39;.ml&#39;, &#39;.fs&#39;, &#39;.groovy&#39;, &#39;.jsm&#39;, &#39;.jsx&#39;, &#39;.tsx&#39;, &#39;.yaml&#39;
]
self.max_file_size = max_file_size
self.max_tokens = int(os.getenv(&#34;PRAISONAI_MAX_TOKENS&#34;, max_tokens))
self.ignore_patterns = self.get_ignore_patterns()
self.include_paths = self.get_include_paths()
self.included_files = []
def get_ignore_patterns(self):
&#34;&#34;&#34;
Loads ignore patterns from various sources, prioritizing them in
the following order:
1. .praisonignore
2. settings.yaml (under code.ignore_files)
3. PRAISONAI_IGNORE_FILES environment variable
4. .gitignore
5. Default patterns
&#34;&#34;&#34;
ignore_patterns = []
def load_from_file(filepath):
if os.path.exists(filepath):
with open(filepath, &#39;r&#39;) as f:
ignore_patterns.extend(
line.strip() for line in f
if line.strip() and not line.startswith(&#39;#&#39;)
)
# 1. Load from .praisonignore
load_from_file(os.path.join(self.directory, &#39;.praisonignore&#39;))
# 2. Load from settings.yaml
settings_path = os.path.join(self.directory, &#39;settings.yaml&#39;)
if os.path.exists(settings_path):
with open(settings_path, &#39;r&#39;) as f:
settings = yaml.safe_load(f)
if &#39;code&#39; in settings and &#39;ignore_files&#39; in settings[&#39;code&#39;]:
ignore_patterns.extend(settings[&#39;code&#39;][&#39;ignore_files&#39;])
# 3. Load from environment variable
ignore_files_env = os.getenv(&#34;PRAISONAI_IGNORE_FILES&#34;)
if ignore_files_env:
ignore_patterns.extend(ignore_files_env.split(&#34;,&#34;))
# 4. Load from .gitignore
load_from_file(os.path.join(self.directory, &#39;.gitignore&#39;))
# 5. Default patterns (only if no patterns loaded from above sources)
if not ignore_patterns:
ignore_patterns = [
&#34;.*&#34;, &#34;*.pyc&#34;, &#34;__pycache__&#34;, &#34;.git&#34;, &#34;.gitignore&#34;, &#34;.vscode&#34;,
&#34;.idea&#34;, &#34;.DS_Store&#34;, &#34;*.lock&#34;, &#34;*.pyc&#34;, &#34;.env&#34;, &#34;docs&#34;, &#34;tests&#34;,
&#34;test&#34;, &#34;tmp&#34;, &#34;temp&#34;, &#34;*.txt&#34;, &#34;*.md&#34;, &#34;*.json&#34;, &#34;*.csv&#34;, &#34;*.tsv&#34;,
&#34;public&#34;, &#34;*.sql&#34;, &#34;*.sqlite&#34;, &#34;*.db&#34;, &#34;*.db3&#34;, &#34;*.sqlite3&#34;,
&#34;*.log&#34;, &#34;*.zip&#34;, &#34;*.gz&#34;, &#34;*.tar&#34;, &#34;*.rar&#34;, &#34;*.7z&#34;, &#34;*.pdf&#34;,
&#34;*.jpg&#34;, &#34;*.jpeg&#34;, &#34;*.png&#34;, &#34;*.gif&#34;, &#34;*.svg&#34;, &#34;cookbooks&#34;,
&#34;assets&#34;, &#34;__pycache__&#34;, &#34;dist&#34;, &#34;build&#34;, &#34;node_modules&#34;, &#34;venv&#34;
]
logger.debug(f&#34;Using default ignore patterns: {ignore_patterns}&#34;)
# Modify patterns to match directories and add leading &#39;*&#39; if necessary
modified_ignore_patterns = [
&#39;*&#39; + pattern if not pattern.startswith(&#39;.&#39;) and not pattern.startswith(&#39;*&#39;) else pattern
for pattern in ignore_patterns
]
logger.debug(f&#34;Final ignore patterns: {modified_ignore_patterns}&#34;)
return modified_ignore_patterns
def get_include_paths(self):
&#34;&#34;&#34;
Loads include paths from:
1. .praisoninclude (includes ONLY files/directories listed)
2. .praisoncontext (if .praisoninclude doesn&#39;t exist, this is used
to include all other relevant files, excluding ignore patterns)
&#34;&#34;&#34;
include_paths = []
include_all = False # Flag to indicate if we need to include all files
include_file = os.path.join(self.directory, &#39;.praisoncontext&#39;)
if os.path.exists(include_file):
with open(include_file, &#39;r&#39;) as f:
include_paths.extend(
line.strip() for line in f
if line.strip() and not line.startswith(&#39;#&#39;)
)
# If .praisoncontext doesn&#39;t exist, fall back to .praisoninclude
# for including all relevant files
if not include_paths:
include_file = os.path.join(self.directory, &#39;.praisoninclude&#39;)
if os.path.exists(include_file):
with open(include_file, &#39;r&#39;) as f:
include_paths.extend(
line.strip() for line in f
if line.strip() and not line.startswith(&#39;#&#39;)
)
include_all = True # Include all files along with specified paths
return include_paths, include_all
def should_ignore(self, file_path):
&#34;&#34;&#34;
Check if a file or directory should be ignored based on patterns.
Handles both file names and directory names for more comprehensive filtering.
&#34;&#34;&#34;
relative_path = os.path.relpath(file_path, self.directory)
if relative_path.startswith(&#39;.&#39;):
return True
for pattern in self.ignore_patterns:
if fnmatch.fnmatch(relative_path, pattern) or \
fnmatch.fnmatch(os.path.basename(file_path), pattern):
return True
return False
def is_relevant_file(self, file_path):
&#34;&#34;&#34;Determine if a file is relevant for the context.&#34;&#34;&#34;
return os.path.isfile(file_path) and \
os.path.getsize(file_path) &lt;= self.max_file_size and \
any(file_path.endswith(ext) for ext in self.relevant_extensions)
def gather_context(self):
&#34;&#34;&#34;
Gather context from relevant files, respecting ignore patterns
and include options from .praisoninclude and .praisoncontext.
&#34;&#34;&#34;
context = []
total_files = 0
processed_files = 0
self.include_paths, include_all = self.get_include_paths()
def add_file_content(file_path):
&#34;&#34;&#34;Helper function to add file content to context.&#34;&#34;&#34;
try:
with open(file_path, &#39;r&#39;, encoding=&#39;utf-8&#39;) as f:
content = f.read()
context.append(
f&#34;File: {file_path}\n\n{content}\n\n{&#39;=&#39; * 50}\n&#34;
)
self.included_files.append(
Path(file_path).relative_to(self.directory)
)
except Exception as e:
logger.error(f&#34;Error reading {file_path}: {e}&#34;)
def process_path(path):
&#34;&#34;&#34;Helper function to process a single path (file or directory).&#34;&#34;&#34;
nonlocal total_files, processed_files
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
total_files += len(files)
dirs[:] = [
d
for d in dirs
if not self.should_ignore(os.path.join(root, d))
]
for file in files:
file_path = os.path.join(root, file)
if not self.should_ignore(file_path) and self.is_relevant_file(file_path):
add_file_content(file_path)
processed_files += 1
print(
f&#34;\rProcessed {processed_files}/{total_files} files&#34;,
end=&#34;&#34;,
flush=True,
)
elif os.path.isfile(path) and self.is_relevant_file(path):
add_file_content(path)
processed_files += 1
print(
f&#34;\rProcessed {processed_files}/1 files&#34;,
end=&#34;&#34;,
flush=True,
)
if include_all:
# Include ALL relevant files from the entire directory
process_path(self.directory)
# Include files from .praisoninclude specifically
for include_path in self.include_paths:
full_path = os.path.join(self.directory, include_path)
process_path(full_path)
elif self.include_paths:
# Include only files specified in .praisoncontext
for include_path in self.include_paths:
full_path = os.path.join(self.directory, include_path)
process_path(full_path)
else:
# No include options, process the entire directory
process_path(self.directory)
print() # New line after progress indicator
return &#34;\n&#34;.join(context)
def count_tokens(self, text):
&#34;&#34;&#34;Count tokens using a simple whitespace-based tokenizer.&#34;&#34;&#34;
return len(text.split())
def truncate_context(self, context):
&#34;&#34;&#34;Truncate context to stay within the token limit.&#34;&#34;&#34;
tokens = context.split()
if len(tokens) &gt; self.max_tokens:
truncated_context = &#39; &#39;.join(tokens[:self.max_tokens])
logger.warning(&#34;Context truncated due to token limit.&#34;)
return truncated_context
return context
def save_context(self, context):
&#34;&#34;&#34;Save the gathered context to a file.&#34;&#34;&#34;
with open(self.output_file, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:
f.write(context)
def get_context_tree(self):
&#34;&#34;&#34;Generate a formatted tree structure of included files and folders.&#34;&#34;&#34;
tree = []
start_dir = Path(self.directory)
def add_to_tree(path, prefix=&#39;&#39;):
contents = sorted(path.iterdir())
pointers = [(&#39;└── &#39; if i == len(contents) - 1 else &#39;├── &#39;) for i in range(len(contents))]
for pointer, item in zip(pointers, contents):
rel_path = item.relative_to(start_dir)
if rel_path in self.included_files:
tree.append(f&#34;{prefix}{pointer}{rel_path}&#34;)
if item.is_dir():
add_to_tree(item, prefix + (&#39; &#39; if pointer == &#39;└── &#39; else &#39;│ &#39;))
add_to_tree(start_dir)
return &#39;\n&#39;.join(tree)
def run(self):
&#34;&#34;&#34;Execute the context gathering, truncation, and reporting.&#34;&#34;&#34;
context = self.gather_context()
context = self.truncate_context(context)
token_count = self.count_tokens(context)
print(f&#34;Context gathered successfully.&#34;)
print(f&#34;Total number of tokens (estimated): {token_count}&#34;)
# self.save_context(context)
context_tree = self.get_context_tree()
logger.debug(f&#34;Context tree:\n{context_tree}&#34;)
return context, token_count, context_tree</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="praisonai.ui.context.ContextGatherer.count_tokens"><code class="name flex">
<span>def <span class="ident">count_tokens</span></span>(<span>self, text)</span>
</code></dt>
<dd>
<div class="desc"><p>Count tokens using a simple whitespace-based tokenizer.</p></div>
</dd>
<dt id="praisonai.ui.context.ContextGatherer.gather_context"><code class="name flex">
<span>def <span class="ident">gather_context</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Gather context from relevant files, respecting ignore patterns
and include options from .praisoninclude and .praisoncontext.</p></div>
</dd>
<dt id="praisonai.ui.context.ContextGatherer.get_context_tree"><code class="name flex">
<span>def <span class="ident">get_context_tree</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Generate a formatted tree structure of included files and folders.</p></div>
</dd>
<dt id="praisonai.ui.context.ContextGatherer.get_ignore_patterns"><code class="name flex">
<span>def <span class="ident">get_ignore_patterns</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Loads ignore patterns from various sources, prioritizing them in
the following order:
1. .praisonignore
2. settings.yaml (under code.ignore_files)
3. PRAISONAI_IGNORE_FILES environment variable
4. .gitignore
5. Default patterns</p></div>
</dd>
<dt id="praisonai.ui.context.ContextGatherer.get_include_paths"><code class="name flex">
<span>def <span class="ident">get_include_paths</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Loads include paths from:
1. .praisoninclude (includes ONLY files/directories listed)
2. .praisoncontext (if .praisoninclude doesn't exist, this is used
to include all other relevant files, excluding ignore patterns)</p></div>
</dd>
<dt id="praisonai.ui.context.ContextGatherer.is_relevant_file"><code class="name flex">
<span>def <span class="ident">is_relevant_file</span></span>(<span>self, file_path)</span>
</code></dt>
<dd>
<div class="desc"><p>Determine if a file is relevant for the context.</p></div>
</dd>
<dt id="praisonai.ui.context.ContextGatherer.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Execute the context gathering, truncation, and reporting.</p></div>
</dd>
<dt id="praisonai.ui.context.ContextGatherer.save_context"><code class="name flex">
<span>def <span class="ident">save_context</span></span>(<span>self, context)</span>
</code></dt>
<dd>
<div class="desc"><p>Save the gathered context to a file.</p></div>
</dd>
<dt id="praisonai.ui.context.ContextGatherer.should_ignore"><code class="name flex">
<span>def <span class="ident">should_ignore</span></span>(<span>self, file_path)</span>
</code></dt>
<dd>
<div class="desc"><p>Check if a file or directory should be ignored based on patterns.
Handles both file names and directory names for more comprehensive filtering.</p></div>
</dd>
<dt id="praisonai.ui.context.ContextGatherer.truncate_context"><code class="name flex">
<span>def <span class="ident">truncate_context</span></span>(<span>self, context)</span>
</code></dt>
<dd>
<div class="desc"><p>Truncate context to stay within the token limit.</p></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai.ui" href="index.html">praisonai.ui</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="praisonai.ui.context.main" href="#praisonai.ui.context.main">main</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="praisonai.ui.context.ContextGatherer" href="#praisonai.ui.context.ContextGatherer">ContextGatherer</a></code></h4>
<ul class="two-column">
<li><code><a title="praisonai.ui.context.ContextGatherer.count_tokens" href="#praisonai.ui.context.ContextGatherer.count_tokens">count_tokens</a></code></li>
<li><code><a title="praisonai.ui.context.ContextGatherer.gather_context" href="#praisonai.ui.context.ContextGatherer.gather_context">gather_context</a></code></li>
<li><code><a title="praisonai.ui.context.ContextGatherer.get_context_tree" href="#praisonai.ui.context.ContextGatherer.get_context_tree">get_context_tree</a></code></li>
<li><code><a title="praisonai.ui.context.ContextGatherer.get_ignore_patterns" href="#praisonai.ui.context.ContextGatherer.get_ignore_patterns">get_ignore_patterns</a></code></li>
<li><code><a title="praisonai.ui.context.ContextGatherer.get_include_paths" href="#praisonai.ui.context.ContextGatherer.get_include_paths">get_include_paths</a></code></li>
<li><code><a title="praisonai.ui.context.ContextGatherer.is_relevant_file" href="#praisonai.ui.context.ContextGatherer.is_relevant_file">is_relevant_file</a></code></li>
<li><code><a title="praisonai.ui.context.ContextGatherer.run" href="#praisonai.ui.context.ContextGatherer.run">run</a></code></li>
<li><code><a title="praisonai.ui.context.ContextGatherer.save_context" href="#praisonai.ui.context.ContextGatherer.save_context">save_context</a></code></li>
<li><code><a title="praisonai.ui.context.ContextGatherer.should_ignore" href="#praisonai.ui.context.ContextGatherer.should_ignore">should_ignore</a></code></li>
<li><code><a title="praisonai.ui.context.ContextGatherer.truncate_context" href="#praisonai.ui.context.ContextGatherer.truncate_context">truncate_context</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-77
View File
@@ -1,77 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.ui API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Namespace <code>praisonai.ui</code></h1>
</header>
<section id="section-intro">
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="praisonai.ui.context" href="context.html">praisonai.ui.context</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.ui.realtimeclient" href="realtimeclient/index.html">praisonai.ui.realtimeclient</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="praisonai.ui.sql_alchemy" href="sql_alchemy.html">praisonai.ui.sql_alchemy</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="../index.html">praisonai</a></code></li>
</ul>
</li>
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="praisonai.ui.context" href="context.html">praisonai.ui.context</a></code></li>
<li><code><a title="praisonai.ui.realtimeclient" href="realtimeclient/index.html">praisonai.ui.realtimeclient</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy" href="sql_alchemy.html">praisonai.ui.sql_alchemy</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
File diff suppressed because it is too large. Load diff
-898
View File
@@ -1,898 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.ui.sql_alchemy API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.ui.sql_alchemy</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer"><code class="flex name class">
<span>class <span class="ident">SQLAlchemyDataLayer</span></span>
<span>(</span><span>conninfo: str, ssl_require: bool = False, storage_provider: Optional[chainlit.data.base.BaseStorageClient] = None, user_thread_limit: Optional[int] = 1000, show_logger: Optional[bool] = False)</span>
</code></dt>
<dd>
<div class="desc"><p>Base class for data persistence.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class SQLAlchemyDataLayer(BaseDataLayer):
def __init__(
self,
conninfo: str,
ssl_require: bool = False,
storage_provider: Optional[BaseStorageClient] = None,
user_thread_limit: Optional[int] = 1000,
show_logger: Optional[bool] = False,
):
self._conninfo = conninfo
self.user_thread_limit = user_thread_limit
self.show_logger = show_logger
ssl_args = {}
if ssl_require:
# Create an SSL context to require an SSL connection
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
ssl_args[&#34;ssl&#34;] = ssl_context
self.engine: AsyncEngine = create_async_engine(
self._conninfo, connect_args=ssl_args
)
self.async_session = sessionmaker(
bind=self.engine, expire_on_commit=False, class_=AsyncSession
) # type: ignore
if storage_provider:
self.storage_provider: Optional[BaseStorageClient] = storage_provider
if self.show_logger:
logger.info(&#34;SQLAlchemyDataLayer storage client initialized&#34;)
else:
self.storage_provider = None
logger.warn(
&#34;SQLAlchemyDataLayer storage client is not initialized and elements will not be persisted!&#34;
)
async def build_debug_url(self) -&gt; str:
return &#34;&#34;
###### SQL Helpers ######
async def execute_sql(
self, query: str, parameters: dict
) -&gt; Union[List[Dict[str, Any]], int, None]:
parameterized_query = text(query)
async with self.async_session() as session:
try:
await session.begin()
result = await session.execute(parameterized_query, parameters)
await session.commit()
if result.returns_rows:
json_result = [dict(row._mapping) for row in result.fetchall()]
clean_json_result = self.clean_result(json_result)
assert isinstance(clean_json_result, list) or isinstance(
clean_json_result, int
)
return clean_json_result
else:
return result.rowcount
except SQLAlchemyError as e:
await session.rollback()
logger.warn(f&#34;An error occurred: {e}&#34;)
return None
except Exception as e:
await session.rollback()
logger.warn(f&#34;An unexpected error occurred: {e}&#34;)
return None
async def get_current_timestamp(self) -&gt; str:
return datetime.now().isoformat() + &#34;Z&#34;
def clean_result(self, obj):
&#34;&#34;&#34;Recursively change UUID -&gt; str and serialize dictionaries&#34;&#34;&#34;
if isinstance(obj, dict):
return {k: self.clean_result(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [self.clean_result(item) for item in obj]
elif isinstance(obj, uuid.UUID):
return str(obj)
return obj
###### User ######
async def get_user(self, identifier: str) -&gt; Optional[PersistedUser]:
if self.show_logger:
logger.info(f&#34;SQLAlchemy: get_user, identifier={identifier}&#34;)
query = &#34;SELECT * FROM users WHERE identifier = :identifier&#34;
parameters = {&#34;identifier&#34;: identifier}
result = await self.execute_sql(query=query, parameters=parameters)
if result and isinstance(result, list):
user_data = result[0]
# SQLite returns JSON as string, we most convert it. (#1137)
metadata = user_data.get(&#34;metadata&#34;, {})
if isinstance(metadata, str):
metadata = json.loads(metadata)
assert isinstance(metadata, dict)
assert isinstance(user_data[&#34;id&#34;], str)
assert isinstance(user_data[&#34;identifier&#34;], str)
assert isinstance(user_data[&#34;createdAt&#34;], str)
return PersistedUser(
id=user_data[&#34;id&#34;],
identifier=user_data[&#34;identifier&#34;],
createdAt=user_data[&#34;createdAt&#34;],
metadata=metadata,
)
return None
async def _get_user_identifer_by_id(self, user_id: str) -&gt; str:
if self.show_logger:
logger.info(f&#34;SQLAlchemy: _get_user_identifer_by_id, user_id={user_id}&#34;)
query = &#34;SELECT identifier FROM users WHERE id = :user_id&#34;
parameters = {&#34;user_id&#34;: user_id}
result = await self.execute_sql(query=query, parameters=parameters)
assert result
assert isinstance(result, list)
return result[0][&#34;identifier&#34;]
async def _get_user_id_by_thread(self, thread_id: str) -&gt; Optional[str]:
if self.show_logger:
logger.info(f&#34;SQLAlchemy: _get_user_id_by_thread, thread_id={thread_id}&#34;)
query = &#34;SELECT userId FROM threads WHERE id = :thread_id&#34;
parameters = {&#34;thread_id&#34;: thread_id}
result = await self.execute_sql(query=query, parameters=parameters)
if result:
assert isinstance(result, list)
return result[0][&#34;userId&#34;]
return None
async def create_user(self, user: User) -&gt; Optional[PersistedUser]:
if self.show_logger:
logger.info(f&#34;SQLAlchemy: create_user, user_identifier={user.identifier}&#34;)
existing_user: Optional[&#34;PersistedUser&#34;] = await self.get_user(user.identifier)
user_dict: Dict[str, Any] = {
&#34;identifier&#34;: str(user.identifier),
&#34;metadata&#34;: json.dumps(user.metadata) or {},
}
if not existing_user: # create the user
if self.show_logger:
logger.info(&#34;SQLAlchemy: create_user, creating the user&#34;)
user_dict[&#34;id&#34;] = str(uuid.uuid4())
user_dict[&#34;createdAt&#34;] = await self.get_current_timestamp()
query = &#34;&#34;&#34;INSERT INTO users (&#34;id&#34;, &#34;identifier&#34;, &#34;createdAt&#34;, &#34;metadata&#34;) VALUES (:id, :identifier, :createdAt, :metadata)&#34;&#34;&#34;
await self.execute_sql(query=query, parameters=user_dict)
else: # update the user
if self.show_logger:
logger.info(&#34;SQLAlchemy: update user metadata&#34;)
query = &#34;&#34;&#34;UPDATE users SET &#34;metadata&#34; = :metadata WHERE &#34;identifier&#34; = :identifier&#34;&#34;&#34;
await self.execute_sql(
query=query, parameters=user_dict
) # We want to update the metadata
return await self.get_user(user.identifier)
###### Threads ######
async def get_thread_author(self, thread_id: str) -&gt; str:
if self.show_logger:
logger.info(f&#34;SQLAlchemy: get_thread_author, thread_id={thread_id}&#34;)
query = &#34;&#34;&#34;SELECT &#34;userIdentifier&#34; FROM threads WHERE &#34;id&#34; = :id&#34;&#34;&#34;
parameters = {&#34;id&#34;: thread_id}
result = await self.execute_sql(query=query, parameters=parameters)
if isinstance(result, list) and result:
author_identifier = result[0].get(&#34;userIdentifier&#34;)
if author_identifier is not None:
return author_identifier
raise ValueError(f&#34;Author not found for thread_id {thread_id}&#34;)
async def get_thread(self, thread_id: str) -&gt; Optional[ThreadDict]:
if self.show_logger:
logger.info(f&#34;SQLAlchemy: get_thread, thread_id={thread_id}&#34;)
user_threads: Optional[List[ThreadDict]] = await self.get_all_user_threads(
thread_id=thread_id
)
if user_threads:
return user_threads[0]
else:
return None
async def update_thread(
self,
thread_id: str,
name: Optional[str] = None,
user_id: Optional[str] = None,
metadata: Optional[Dict] = None,
tags: Optional[List[str]] = None,
):
if self.show_logger:
logger.info(f&#34;SQLAlchemy: update_thread, thread_id={thread_id}&#34;)
user_identifier = None
if user_id:
user_identifier = await self._get_user_identifer_by_id(user_id)
data = {
&#34;id&#34;: thread_id,
&#34;createdAt&#34;: (
await self.get_current_timestamp() if metadata is None else None
),
&#34;name&#34;: (
name
if name is not None
else (metadata.get(&#34;name&#34;) if metadata and &#34;name&#34; in metadata else None)
),
&#34;userId&#34;: user_id,
&#34;userIdentifier&#34;: user_identifier,
&#34;tags&#34;: tags,
&#34;metadata&#34;: json.dumps(metadata) if metadata else None,
}
parameters = {
key: value for key, value in data.items() if value is not None
} # Remove keys with None values
columns = &#34;, &#34;.join(f&#39;&#34;{key}&#34;&#39; for key in parameters.keys())
values = &#34;, &#34;.join(f&#34;:{key}&#34; for key in parameters.keys())
updates = &#34;, &#34;.join(
f&#39;&#34;{key}&#34; = EXCLUDED.&#34;{key}&#34;&#39; for key in parameters.keys() if key != &#34;id&#34;
)
query = f&#34;&#34;&#34;
INSERT INTO threads ({columns})
VALUES ({values})
ON CONFLICT (&#34;id&#34;) DO UPDATE
SET {updates};
&#34;&#34;&#34;
await self.execute_sql(query=query, parameters=parameters)
async def delete_thread(self, thread_id: str):
if self.show_logger:
logger.info(f&#34;SQLAlchemy: delete_thread, thread_id={thread_id}&#34;)
# Delete feedbacks/elements/steps/thread
feedbacks_query = &#34;&#34;&#34;DELETE FROM feedbacks WHERE &#34;forId&#34; IN (SELECT &#34;id&#34; FROM steps WHERE &#34;threadId&#34; = :id)&#34;&#34;&#34;
elements_query = &#34;&#34;&#34;DELETE FROM elements WHERE &#34;threadId&#34; = :id&#34;&#34;&#34;
steps_query = &#34;&#34;&#34;DELETE FROM steps WHERE &#34;threadId&#34; = :id&#34;&#34;&#34;
thread_query = &#34;&#34;&#34;DELETE FROM threads WHERE &#34;id&#34; = :id&#34;&#34;&#34;
parameters = {&#34;id&#34;: thread_id}
await self.execute_sql(query=feedbacks_query, parameters=parameters)
await self.execute_sql(query=elements_query, parameters=parameters)
await self.execute_sql(query=steps_query, parameters=parameters)
await self.execute_sql(query=thread_query, parameters=parameters)
async def list_threads(
self, pagination: Pagination, filters: ThreadFilter
) -&gt; PaginatedResponse:
if self.show_logger:
logger.info(
f&#34;SQLAlchemy: list_threads, pagination={pagination}, filters={filters}&#34;
)
if not filters.userId:
raise ValueError(&#34;userId is required&#34;)
all_user_threads: List[ThreadDict] = (
await self.get_all_user_threads(user_id=filters.userId) or []
)
search_keyword = filters.search.lower() if filters.search else None
feedback_value = int(filters.feedback) if filters.feedback else None
filtered_threads = []
for thread in all_user_threads:
keyword_match = True
feedback_match = True
if search_keyword or feedback_value is not None:
if search_keyword:
keyword_match = any(
search_keyword in step[&#34;output&#34;].lower()
for step in thread[&#34;steps&#34;]
if &#34;output&#34; in step
)
if feedback_value is not None:
feedback_match = False # Assume no match until found
for step in thread[&#34;steps&#34;]:
feedback = step.get(&#34;feedback&#34;)
if feedback and feedback.get(&#34;value&#34;) == feedback_value:
feedback_match = True
break
if keyword_match and feedback_match:
filtered_threads.append(thread)
start = 0
if pagination.cursor:
for i, thread in enumerate(filtered_threads):
if (
thread[&#34;id&#34;] == pagination.cursor
): # Find the start index using pagination.cursor
start = i + 1
break
end = start + pagination.first
paginated_threads = filtered_threads[start:end] or []
has_next_page = len(filtered_threads) &gt; end
start_cursor = paginated_threads[0][&#34;id&#34;] if paginated_threads else None
end_cursor = paginated_threads[-1][&#34;id&#34;] if paginated_threads else None
return PaginatedResponse(
pageInfo=PageInfo(
hasNextPage=has_next_page,
startCursor=start_cursor,
endCursor=end_cursor,
),
data=paginated_threads,
)
###### Steps ######
@queue_until_user_message()
async def create_step(self, step_dict: &#34;StepDict&#34;):
if self.show_logger:
logger.info(f&#34;SQLAlchemy: create_step, step_id={step_dict.get(&#39;id&#39;)}&#34;)
step_dict[&#34;showInput&#34;] = (
str(step_dict.get(&#34;showInput&#34;, &#34;&#34;)).lower()
if &#34;showInput&#34; in step_dict
else None
)
parameters = {
key: value
for key, value in step_dict.items()
if value is not None and not (isinstance(value, dict) and not value)
}
parameters[&#34;metadata&#34;] = json.dumps(step_dict.get(&#34;metadata&#34;, {}))
parameters[&#34;generation&#34;] = json.dumps(step_dict.get(&#34;generation&#34;, {}))
columns = &#34;, &#34;.join(f&#39;&#34;{key}&#34;&#39; for key in parameters.keys())
values = &#34;, &#34;.join(f&#34;:{key}&#34; for key in parameters.keys())
updates = &#34;, &#34;.join(
f&#39;&#34;{key}&#34; = :{key}&#39; for key in parameters.keys() if key != &#34;id&#34;
)
query = f&#34;&#34;&#34;
INSERT INTO steps ({columns})
VALUES ({values})
ON CONFLICT (id) DO UPDATE
SET {updates};
&#34;&#34;&#34;
await self.execute_sql(query=query, parameters=parameters)
@queue_until_user_message()
async def update_step(self, step_dict: &#34;StepDict&#34;):
if self.show_logger:
logger.info(f&#34;SQLAlchemy: update_step, step_id={step_dict.get(&#39;id&#39;)}&#34;)
await self.create_step(step_dict)
@queue_until_user_message()
async def delete_step(self, step_id: str):
if self.show_logger:
logger.info(f&#34;SQLAlchemy: delete_step, step_id={step_id}&#34;)
# Delete feedbacks/elements/steps
feedbacks_query = &#34;&#34;&#34;DELETE FROM feedbacks WHERE &#34;forId&#34; = :id&#34;&#34;&#34;
elements_query = &#34;&#34;&#34;DELETE FROM elements WHERE &#34;forId&#34; = :id&#34;&#34;&#34;
steps_query = &#34;&#34;&#34;DELETE FROM steps WHERE &#34;id&#34; = :id&#34;&#34;&#34;
parameters = {&#34;id&#34;: step_id}
await self.execute_sql(query=feedbacks_query, parameters=parameters)
await self.execute_sql(query=elements_query, parameters=parameters)
await self.execute_sql(query=steps_query, parameters=parameters)
###### Feedback ######
async def upsert_feedback(self, feedback: Feedback) -&gt; str:
if self.show_logger:
logger.info(f&#34;SQLAlchemy: upsert_feedback, feedback_id={feedback.id}&#34;)
feedback.id = feedback.id or str(uuid.uuid4())
feedback_dict = asdict(feedback)
parameters = {
key: value for key, value in feedback_dict.items() if value is not None
}
columns = &#34;, &#34;.join(f&#39;&#34;{key}&#34;&#39; for key in parameters.keys())
values = &#34;, &#34;.join(f&#34;:{key}&#34; for key in parameters.keys())
updates = &#34;, &#34;.join(
f&#39;&#34;{key}&#34; = :{key}&#39; for key in parameters.keys() if key != &#34;id&#34;
)
query = f&#34;&#34;&#34;
INSERT INTO feedbacks ({columns})
VALUES ({values})
ON CONFLICT (id) DO UPDATE
SET {updates};
&#34;&#34;&#34;
await self.execute_sql(query=query, parameters=parameters)
return feedback.id
async def delete_feedback(self, feedback_id: str) -&gt; bool:
if self.show_logger:
logger.info(f&#34;SQLAlchemy: delete_feedback, feedback_id={feedback_id}&#34;)
query = &#34;&#34;&#34;DELETE FROM feedbacks WHERE &#34;id&#34; = :feedback_id&#34;&#34;&#34;
parameters = {&#34;feedback_id&#34;: feedback_id}
await self.execute_sql(query=query, parameters=parameters)
return True
###### Elements ######
async def get_element(
self, thread_id: str, element_id: str
) -&gt; Optional[&#34;ElementDict&#34;]:
if self.show_logger:
logger.info(
f&#34;SQLAlchemy: get_element, thread_id={thread_id}, element_id={element_id}&#34;
)
query = &#34;&#34;&#34;SELECT * FROM elements WHERE &#34;threadId&#34; = :thread_id AND &#34;id&#34; = :element_id&#34;&#34;&#34;
parameters = {&#34;thread_id&#34;: thread_id, &#34;element_id&#34;: element_id}
element: Union[List[Dict[str, Any]], int, None] = await self.execute_sql(
query=query, parameters=parameters
)
if isinstance(element, list) and element:
element_dict: Dict[str, Any] = element[0]
return ElementDict(
id=element_dict[&#34;id&#34;],
threadId=element_dict.get(&#34;threadId&#34;),
type=element_dict[&#34;type&#34;],
chainlitKey=element_dict.get(&#34;chainlitKey&#34;),
url=element_dict.get(&#34;url&#34;),
objectKey=element_dict.get(&#34;objectKey&#34;),
name=element_dict[&#34;name&#34;],
display=element_dict[&#34;display&#34;],
size=element_dict.get(&#34;size&#34;),
language=element_dict.get(&#34;language&#34;),
page=element_dict.get(&#34;page&#34;),
autoPlay=element_dict.get(&#34;autoPlay&#34;),
playerConfig=element_dict.get(&#34;playerConfig&#34;),
forId=element_dict.get(&#34;forId&#34;),
mime=element_dict.get(&#34;mime&#34;),
)
else:
return None
@queue_until_user_message()
async def create_element(self, element: &#34;Element&#34;):
if self.show_logger:
logger.info(f&#34;SQLAlchemy: create_element, element_id = {element.id}&#34;)
if not self.storage_provider:
logger.warn(
&#34;SQLAlchemy: create_element error. No blob_storage_client is configured!&#34;
)
return
if not element.for_id:
return
content: Optional[Union[bytes, str]] = None
if element.path:
async with aiofiles.open(element.path, &#34;rb&#34;) as f:
content = await f.read()
elif element.url:
async with aiohttp.ClientSession() as session:
async with session.get(element.url) as response:
if response.status == 200:
content = await response.read()
else:
content = None
elif element.content:
content = element.content
else:
raise ValueError(&#34;Element url, path or content must be provided&#34;)
if content is None:
raise ValueError(&#34;Content is None, cannot upload file&#34;)
user_id: str = await self._get_user_id_by_thread(element.thread_id) or &#34;unknown&#34;
file_object_key = f&#34;{user_id}/{element.id}&#34; + (
f&#34;/{element.name}&#34; if element.name else &#34;&#34;
)
if not element.mime:
element.mime = &#34;application/octet-stream&#34;
uploaded_file = await self.storage_provider.upload_file(
object_key=file_object_key, data=content, mime=element.mime, overwrite=True
)
if not uploaded_file:
raise ValueError(
&#34;SQLAlchemy Error: create_element, Failed to persist data in storage_provider&#34;
)
element_dict: ElementDict = element.to_dict()
element_dict[&#34;url&#34;] = uploaded_file.get(&#34;url&#34;)
element_dict[&#34;objectKey&#34;] = uploaded_file.get(&#34;object_key&#34;)
element_dict_cleaned = {k: v for k, v in element_dict.items() if v is not None}
columns = &#34;, &#34;.join(f&#39;&#34;{column}&#34;&#39; for column in element_dict_cleaned.keys())
placeholders = &#34;, &#34;.join(f&#34;:{column}&#34; for column in element_dict_cleaned.keys())
query = f&#34;INSERT INTO elements ({columns}) VALUES ({placeholders})&#34;
await self.execute_sql(query=query, parameters=element_dict_cleaned)
@queue_until_user_message()
async def delete_element(self, element_id: str, thread_id: Optional[str] = None):
if self.show_logger:
logger.info(f&#34;SQLAlchemy: delete_element, element_id={element_id}&#34;)
query = &#34;&#34;&#34;DELETE FROM elements WHERE &#34;id&#34; = :id&#34;&#34;&#34;
parameters = {&#34;id&#34;: element_id}
await self.execute_sql(query=query, parameters=parameters)
async def get_all_user_threads(
self, user_id: Optional[str] = None, thread_id: Optional[str] = None
) -&gt; Optional[List[ThreadDict]]:
&#34;&#34;&#34;Fetch all user threads up to self.user_thread_limit, or one thread by id if thread_id is provided.&#34;&#34;&#34;
if self.show_logger:
logger.info(&#34;SQLAlchemy: get_all_user_threads&#34;)
user_threads_query = &#34;&#34;&#34;
SELECT
&#34;id&#34; AS thread_id,
&#34;createdAt&#34; AS thread_createdat,
&#34;name&#34; AS thread_name,
&#34;userId&#34; AS user_id,
&#34;userIdentifier&#34; AS user_identifier,
&#34;tags&#34; AS thread_tags,
&#34;metadata&#34; AS thread_metadata
FROM threads
WHERE &#34;userId&#34; = :user_id OR &#34;id&#34; = :thread_id
ORDER BY &#34;createdAt&#34; DESC
LIMIT :limit
&#34;&#34;&#34;
user_threads = await self.execute_sql(
query=user_threads_query,
parameters={
&#34;user_id&#34;: user_id,
&#34;limit&#34;: self.user_thread_limit,
&#34;thread_id&#34;: thread_id,
},
)
if not isinstance(user_threads, list):
return None
if not user_threads:
return []
else:
thread_ids = (
&#34;(&#39;&#34;
+ &#34;&#39;,&#39;&#34;.join(map(str, [thread[&#34;thread_id&#34;] for thread in user_threads]))
+ &#34;&#39;)&#34;
)
steps_feedbacks_query = f&#34;&#34;&#34;
SELECT
s.&#34;id&#34; AS step_id,
s.&#34;name&#34; AS step_name,
s.&#34;type&#34; AS step_type,
s.&#34;threadId&#34; AS step_threadid,
s.&#34;parentId&#34; AS step_parentid,
s.&#34;streaming&#34; AS step_streaming,
s.&#34;waitForAnswer&#34; AS step_waitforanswer,
s.&#34;isError&#34; AS step_iserror,
s.&#34;metadata&#34; AS step_metadata,
s.&#34;tags&#34; AS step_tags,
s.&#34;input&#34; AS step_input,
s.&#34;output&#34; AS step_output,
s.&#34;createdAt&#34; AS step_createdat,
s.&#34;start&#34; AS step_start,
s.&#34;end&#34; AS step_end,
s.&#34;generation&#34; AS step_generation,
s.&#34;showInput&#34; AS step_showinput,
s.&#34;language&#34; AS step_language,
s.&#34;indent&#34; AS step_indent,
f.&#34;value&#34; AS feedback_value,
f.&#34;comment&#34; AS feedback_comment,
f.&#34;id&#34; AS feedback_id
FROM steps s LEFT JOIN feedbacks f ON s.&#34;id&#34; = f.&#34;forId&#34;
WHERE s.&#34;threadId&#34; IN {thread_ids}
ORDER BY s.&#34;createdAt&#34; ASC
&#34;&#34;&#34;
steps_feedbacks = await self.execute_sql(
query=steps_feedbacks_query, parameters={}
)
elements_query = f&#34;&#34;&#34;
SELECT
e.&#34;id&#34; AS element_id,
e.&#34;threadId&#34; as element_threadid,
e.&#34;type&#34; AS element_type,
e.&#34;chainlitKey&#34; AS element_chainlitkey,
e.&#34;url&#34; AS element_url,
e.&#34;objectKey&#34; as element_objectkey,
e.&#34;name&#34; AS element_name,
e.&#34;display&#34; AS element_display,
e.&#34;size&#34; AS element_size,
e.&#34;language&#34; AS element_language,
e.&#34;page&#34; AS element_page,
e.&#34;forId&#34; AS element_forid,
e.&#34;mime&#34; AS element_mime
FROM elements e
WHERE e.&#34;threadId&#34; IN {thread_ids}
&#34;&#34;&#34;
elements = await self.execute_sql(query=elements_query, parameters={})
thread_dicts = {}
for thread in user_threads:
thread_id = thread[&#34;thread_id&#34;]
if thread_id is not None:
# Ensure metadata is a dictionary
metadata = thread[&#34;thread_metadata&#34;]
if isinstance(metadata, str):
try:
metadata = json.loads(metadata)
except json.JSONDecodeError:
metadata = {}
elif metadata is None:
metadata = {}
thread_dicts[thread_id] = ThreadDict(
id=thread_id,
createdAt=thread[&#34;thread_createdat&#34;],
name=thread[&#34;thread_name&#34;],
userId=thread[&#34;user_id&#34;],
userIdentifier=thread[&#34;user_identifier&#34;],
tags=thread[&#34;thread_tags&#34;],
metadata=metadata,
steps=[],
elements=[],
)
# Process steps_feedbacks to populate the steps in the corresponding ThreadDict
if isinstance(steps_feedbacks, list):
for step_feedback in steps_feedbacks:
thread_id = step_feedback[&#34;step_threadid&#34;]
if thread_id is not None:
feedback = None
if step_feedback[&#34;feedback_value&#34;] is not None:
feedback = FeedbackDict(
forId=step_feedback[&#34;step_id&#34;],
id=step_feedback.get(&#34;feedback_id&#34;),
value=step_feedback[&#34;feedback_value&#34;],
comment=step_feedback.get(&#34;feedback_comment&#34;),
)
step_dict = StepDict(
id=step_feedback[&#34;step_id&#34;],
name=step_feedback[&#34;step_name&#34;],
type=step_feedback[&#34;step_type&#34;],
threadId=thread_id,
parentId=step_feedback.get(&#34;step_parentid&#34;),
streaming=step_feedback.get(&#34;step_streaming&#34;, False),
waitForAnswer=step_feedback.get(&#34;step_waitforanswer&#34;),
isError=step_feedback.get(&#34;step_iserror&#34;),
metadata=(
step_feedback[&#34;step_metadata&#34;]
if step_feedback.get(&#34;step_metadata&#34;) is not None
else {}
),
tags=step_feedback.get(&#34;step_tags&#34;),
input=(
step_feedback.get(&#34;step_input&#34;, &#34;&#34;)
if step_feedback.get(&#34;step_showinput&#34;)
not in [None, &#34;false&#34;]
else &#34;&#34;
),
output=step_feedback.get(&#34;step_output&#34;, &#34;&#34;),
createdAt=step_feedback.get(&#34;step_createdat&#34;),
start=step_feedback.get(&#34;step_start&#34;),
end=step_feedback.get(&#34;step_end&#34;),
generation=step_feedback.get(&#34;step_generation&#34;),
showInput=step_feedback.get(&#34;step_showinput&#34;),
language=step_feedback.get(&#34;step_language&#34;),
indent=step_feedback.get(&#34;step_indent&#34;),
feedback=feedback,
)
# Append the step to the steps list of the corresponding ThreadDict
thread_dicts[thread_id][&#34;steps&#34;].append(step_dict)
if isinstance(elements, list):
for element in elements:
thread_id = element[&#34;element_threadid&#34;]
if thread_id is not None:
element_dict = ElementDict(
id=element[&#34;element_id&#34;],
threadId=thread_id,
type=element[&#34;element_type&#34;],
chainlitKey=element.get(&#34;element_chainlitkey&#34;),
url=element.get(&#34;element_url&#34;),
objectKey=element.get(&#34;element_objectkey&#34;),
name=element[&#34;element_name&#34;],
display=element[&#34;element_display&#34;],
size=element.get(&#34;element_size&#34;),
language=element.get(&#34;element_language&#34;),
autoPlay=element.get(&#34;element_autoPlay&#34;),
playerConfig=element.get(&#34;element_playerconfig&#34;),
page=element.get(&#34;element_page&#34;),
forId=element.get(&#34;element_forid&#34;),
mime=element.get(&#34;element_mime&#34;),
)
thread_dicts[thread_id][&#34;elements&#34;].append(element_dict) # type: ignore
return list(thread_dicts.values())</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>chainlit.data.base.BaseDataLayer</li>
<li>abc.ABC</li>
</ul>
<h3>Methods</h3>
<dl>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.build_debug_url"><code class="name flex">
<span>async def <span class="ident">build_debug_url</span></span>(<span>self) ‑> str</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.clean_result"><code class="name flex">
<span>def <span class="ident">clean_result</span></span>(<span>self, obj)</span>
</code></dt>
<dd>
<div class="desc"><p>Recursively change UUID -&gt; str and serialize dictionaries</p></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_element"><code class="name flex">
<span>async def <span class="ident">create_element</span></span>(<span>self, element: Element)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_step"><code class="name flex">
<span>async def <span class="ident">create_step</span></span>(<span>self, step_dict: StepDict)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_user"><code class="name flex">
<span>async def <span class="ident">create_user</span></span>(<span>self, user: chainlit.user.User) ‑> Optional[chainlit.user.PersistedUser]</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_element"><code class="name flex">
<span>async def <span class="ident">delete_element</span></span>(<span>self, element_id: str, thread_id: Optional[str] = None)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_feedback"><code class="name flex">
<span>async def <span class="ident">delete_feedback</span></span>(<span>self, feedback_id: str) ‑> bool</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_step"><code class="name flex">
<span>async def <span class="ident">delete_step</span></span>(<span>self, step_id: str)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_thread"><code class="name flex">
<span>async def <span class="ident">delete_thread</span></span>(<span>self, thread_id: str)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.execute_sql"><code class="name flex">
<span>async def <span class="ident">execute_sql</span></span>(<span>self, query: str, parameters: dict) ‑> Union[List[Dict[str, Any]], int, ForwardRef(None)]</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_all_user_threads"><code class="name flex">
<span>async def <span class="ident">get_all_user_threads</span></span>(<span>self, user_id: Optional[str] = None, thread_id: Optional[str] = None) ‑> Optional[List[chainlit.types.ThreadDict]]</span>
</code></dt>
<dd>
<div class="desc"><p>Fetch all user threads up to self.user_thread_limit, or one thread by id if thread_id is provided.</p></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_current_timestamp"><code class="name flex">
<span>async def <span class="ident">get_current_timestamp</span></span>(<span>self) ‑> str</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_element"><code class="name flex">
<span>async def <span class="ident">get_element</span></span>(<span>self, thread_id: str, element_id: str) ‑> Optional[chainlit.element.ElementDict]</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread"><code class="name flex">
<span>async def <span class="ident">get_thread</span></span>(<span>self, thread_id: str) ‑> Optional[chainlit.types.ThreadDict]</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread_author"><code class="name flex">
<span>async def <span class="ident">get_thread_author</span></span>(<span>self, thread_id: str) ‑> str</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_user"><code class="name flex">
<span>async def <span class="ident">get_user</span></span>(<span>self, identifier: str) ‑> Optional[chainlit.user.PersistedUser]</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.list_threads"><code class="name flex">
<span>async def <span class="ident">list_threads</span></span>(<span>self, pagination: chainlit.types.Pagination, filters: chainlit.types.ThreadFilter) ‑> chainlit.types.PaginatedResponse</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_step"><code class="name flex">
<span>async def <span class="ident">update_step</span></span>(<span>self, step_dict: StepDict)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_thread"><code class="name flex">
<span>async def <span class="ident">update_thread</span></span>(<span>self, thread_id: str, name: Optional[str] = None, user_id: Optional[str] = None, metadata: Optional[Dict] = None, tags: Optional[List[str]] = None)</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.upsert_feedback"><code class="name flex">
<span>async def <span class="ident">upsert_feedback</span></span>(<span>self, feedback: chainlit.types.Feedback) ‑> str</span>
</code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai.ui" href="index.html">praisonai.ui</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer">SQLAlchemyDataLayer</a></code></h4>
<ul class="">
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.build_debug_url" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.build_debug_url">build_debug_url</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.clean_result" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.clean_result">clean_result</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_element" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_element">create_element</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_step" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_step">create_step</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_user" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.create_user">create_user</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_element" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_element">delete_element</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_feedback" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_feedback">delete_feedback</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_step" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_step">delete_step</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_thread" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.delete_thread">delete_thread</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.execute_sql" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.execute_sql">execute_sql</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_all_user_threads" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_all_user_threads">get_all_user_threads</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_current_timestamp" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_current_timestamp">get_current_timestamp</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_element" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_element">get_element</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread">get_thread</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread_author" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_thread_author">get_thread_author</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_user" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.get_user">get_user</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.list_threads" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.list_threads">list_threads</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_step" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_step">update_step</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_thread" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.update_thread">update_thread</a></code></li>
<li><code><a title="praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.upsert_feedback" href="#praisonai.ui.sql_alchemy.SQLAlchemyDataLayer.upsert_feedback">upsert_feedback</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-55
View File
@@ -1,55 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.1">
<title>praisonai.version API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>praisonai.version</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="praisonai" href="index.html">praisonai</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.1</a>.</p>
</footer>
</body>
</html>
-79
View File
@@ -1,79 +0,0 @@
---
title: "Agent Module"
description: "Documentation for the praisonaiagents.agent.agent module"
icon: "user"
---
# Module praisonaiagents.agent.agent
## Classes
### Agent
The main class representing an AI agent with specific role, goal, and capabilities.
#### Parameters
- `name: str` - Name of the agent
- `role: str` - Role of the agent
- `goal: str` - Goal the agent aims to achieve
- `backstory: str` - Background story of the agent
- `llm: str | Any | None = 'gpt-4o'` - Language model to use
- `tools: List[Any] | None = None` - List of tools available to the agent
- `function_calling_llm: Any | None = None` - LLM for function calling
- `max_iter: int = 20` - Maximum iterations
- `max_rpm: int | None = None` - Maximum requests per minute
- `max_execution_time: int | None = None` - Maximum execution time
- `memory: bool = True` - Enable memory
- `verbose: bool = True` - Enable verbose output
- `allow_delegation: bool = False` - Allow task delegation
- `step_callback: Any | None = None` - Callback for each step
- `cache: bool = True` - Enable caching
- `system_template: str | None = None` - System prompt template
- `prompt_template: str | None = None` - Prompt template
- `response_template: str | None = None` - Response template
- `allow_code_execution: bool | None = False` - Allow code execution
- `max_retry_limit: int = 2` - Maximum retry attempts
- `respect_context_window: bool = True` - Respect context window size
- `code_execution_mode: Literal['safe', 'unsafe'] = 'safe'` - Code execution mode
- `embedder_config: Dict[str, Any] | None = None` - Embedder configuration
- `knowledge_sources: List[Any] | None = None` - Knowledge sources
- `use_system_prompt: bool | None = True` - Use system prompt
- `markdown: bool = True` - Enable markdown
- `self_reflect: bool = True` - Enable self reflection
- `max_reflect: int = 3` - Maximum reflections
- `min_reflect: int = 1` - Minimum reflections
- `reflect_llm: str | None = None` - LLM for reflection
#### Methods
- `chat(self, prompt, temperature=0.2, tools=None, output_json=None)` - Chat with the agent
- `achat(self, prompt, temperature=0.2, tools=None, output_json=None)` - Async version of chat method
- `clean_json_output(self, output: str) → str` - Clean and extract JSON from response text
- `clear_history(self)` - Clear chat history
- `execute_tool(self, function_name, arguments)` - Execute a tool dynamically based on the function name and arguments
- `_achat_completion(self, response, tools)` - Async version of _chat_completion method
#### Async Support
The Agent class provides async support through the following methods:
- `achat`: Async version of the chat method for non-blocking communication
- `_achat_completion`: Internal async method for handling chat completions
Example usage:
```python
async def main():
agent = Agent(
name="AsyncAgent",
role="Async Specialist",
goal="Handle async operations",
backstory="Expert in async processing"
)
# Use async chat
result = await agent.achat(
prompt="Your prompt here",
tools=your_tools,
output_json=your_schema
)
print(result)
asyncio.run(main())
```
-113
View File
@@ -1,113 +0,0 @@
---
title: "Agents Module"
description: "Documentation for the praisonaiagents.agents.agents module"
icon: "users"
---
# Module praisonaiagents.agents.agents
## Functions
### encode_file_to_base64(file_path: str) → str
Base64-encode a file.
### process_video(video_path: str, seconds_per_frame=2)
Split video into frames (base64-encoded).
## Classes
### LoopItems
A Pydantic model for handling loop items.
#### Class Variables
- `items: List[Any]` - List of items to loop through
- `model_config` - Model configuration
### PraisonAIAgents
The main class for managing agents and tasks execution.
#### Parameters
- `agents: List[Agent]` - List of agents
- `tasks: List[Task]` - List of tasks
- `verbose: int = 0` - Verbosity level
- `completion_checker: Optional[Callable] = None` - Custom completion checker
- `max_retries: int = 5` - Maximum retry attempts
- `process: str = "sequential"` - Process type (sequential, workflow, hierarchical)
- `manager_llm: Optional[str] = None` - Language model for manager agent
#### Methods
- `add_task(self, task)` - Add a task to the crew
- `clean_json_output(self, output: str) → str` - Clean JSON output
- `clear_state(self) → None` - Clear all state values
- `default_completion_checker(self, task, agent_output)` - Default completion checker
- `execute_task(self, task_id)` - Execute a specific task
- `get_agent_details(self, agent_name)` - Get agent details
- `get_all_tasks_status(self)` - Get status of all tasks
- `get_state(self, key: str, default: Any = None) → Any` - Get a state value
- `get_task_details(self, task_id)` - Get task details
- `get_task_result(self, task_id)` - Get task result
- `get_task_status(self, task_id)` - Get task status
- `run_all_tasks(self)` - Execute tasks based on execution mode
- `run_task(self, task_id)` - Run a specific task
- `save_output_to_file(self, task, task_output)` - Save task output to file
- `set_state(self, key: str, value: Any) → None` - Set a state value
- `start(self)` - Start the crew execution
- `update_state(self, updates: Dict) → None` - Update multiple state values
#### Async Methods
- `astart(self)` - Async version of start method
- `aexecute_task(self, task_id)` - Async version of execute_task
- `arun_task(self, task_id)` - Async version of run_task
- `arun_all_tasks(self)` - Async version of run_all_tasks
#### Async Support
The PraisonAIAgents class provides comprehensive async support through the following methods:
```python
class PraisonAIAgents:
async def astart(self):
"""Async version of start method"""
await self.arun_all_tasks()
return {
"task_status": self.get_all_tasks_status(),
"task_results": self.get_task_results()
}
async def aexecute_task(self, task_id):
"""Async version of execute_task method"""
# Async task execution implementation
async def arun_task(self, task_id):
"""Async version of run_task method"""
# Async task running with retries
async def arun_all_tasks(self):
"""Async version of run_all_tasks method"""
# Async execution of all tasks
```
Example usage:
```python
async def main():
# Initialize agents and tasks
agents = PraisonAIAgents(
agents=[async_agent1, async_agent2],
tasks=[async_task1, async_task2],
process="workflow"
)
# Start async execution
result = await agents.astart()
print(result)
# Run the async workflow
asyncio.run(main())
```
#### Async Features
- Full async/await support
- Parallel task execution
- Non-blocking operations
- Efficient resource utilization
- Mixed sync/async task handling
- Async process management
@@ -1,187 +0,0 @@
---
title: "AutoAgents Module"
description: "Documentation for the praisonaiagents.agents.autoagents module"
icon: "robot"
---
# Module praisonaiagents.agents.autoagents
The AutoAgents module provides automatic creation and management of AI agents and tasks based on high-level instructions.
## Classes
### AutoAgents
The main class for automatically creating and managing AI agents and tasks.
#### Parameters
- `instructions: str` - High-level task description for the agents
- `tools: Optional[List[Any]] = None` - List of tools available to the agents
- `verbose: bool = False` - Enable detailed logging
- `process: str = "sequential"` - Process type (sequential or hierarchical)
- `manager_llm: Optional[str] = None` - Language model for manager agent
- `max_retries: int = 5` - Maximum retry attempts
- `completion_checker: Optional[Any] = None` - Custom completion checker
- `allow_code_execution: bool = False` - Allow code execution
- `memory: bool = True` - Enable agent memory
- `markdown: bool = True` - Enable markdown formatting
- `self_reflect: bool = False` - Enable agent self-reflection
- `max_reflect: int = 3` - Maximum reflection iterations
- `min_reflect: int = 1` - Minimum reflection iterations
- `llm: Optional[str] = None` - Language model for agents
- `function_calling_llm: Optional[str] = None` - Language model for tool calling
- `respect_context_window: bool = True` - Respect model context window
- `code_execution_mode: str = "safe"` - Code execution mode (safe/unsafe)
- `embedder_config: Optional[Dict[str, Any]] = None` - Embedder configuration
- `knowledge_sources: Optional[List[Any]] = None` - Knowledge sources
- `use_system_prompt: bool = True` - Use system prompts
- `cache: bool = True` - Enable caching
- `allow_delegation: bool = False` - Allow task delegation
- `step_callback: Optional[Any] = None` - Callback for each step
- `system_template: Optional[str] = None` - Custom system template
- `prompt_template: Optional[str] = None` - Custom prompt template
- `response_template: Optional[str] = None` - Custom response template
- `max_rpm: Optional[int] = None` - Maximum requests per minute
- `max_execution_time: Optional[int] = None` - Maximum execution time
- `max_iter: int = 20` - Maximum iterations
- `reflect_llm: Optional[str] = None` - Language model for reflection
- `max_agents: int = 3` - Maximum number of agents to create
#### Methods
##### start()
Start the agents synchronously.
```python
def start(self):
"""
Creates tasks based on the instructions, then starts execution.
Returns the task status and results dictionary.
"""
return super().start()
```
##### astart()
Start the agents asynchronously.
```python
async def astart(self):
"""
Async version of start() method.
Creates tasks based on the instructions, then starts execution.
Returns the task status and results dictionary.
"""
return await super().astart()
```
#### Internal Methods
##### _generate_config()
Generate the configuration for agents and tasks.
```python
def _generate_config(self) -> AutoAgentsConfig:
"""
Generate the configuration for agents and tasks based on instructions.
Returns AutoAgentsConfig object containing agent and task configurations.
"""
```
##### _create_agents_and_tasks()
Create agents and tasks from configuration.
```python
def _create_agents_and_tasks(self, config: AutoAgentsConfig) -> tuple[List[Agent], List[Task]]:
"""
Create agents and tasks based on the generated configuration.
Returns tuple of (agents, tasks).
"""
```
##### _assign_tools_to_agent()
Assign appropriate tools to an agent.
```python
def _assign_tools_to_agent(self, agent_config: AgentConfig) -> List[Any]:
"""
Assign tools to an agent based on its role and tasks.
Returns list of assigned tools.
"""
```
## Pydantic Models
### TaskConfig
Configuration for a task.
#### Attributes
- `name: str` - Task name
- `description: str` - Task description
- `expected_output: str` - Expected output description
- `tools: List[str]` - Required tools for the task
### AgentConfig
Configuration for an agent.
#### Attributes
- `name: str` - Agent name
- `role: str` - Agent role
- `goal: str` - Agent goal
- `backstory: str` - Agent backstory
- `tools: List[str]` - Required tools
- `tasks: List[TaskConfig]` - Tasks assigned to the agent
### AutoAgentsConfig
Overall configuration for AutoAgents.
#### Attributes
- `main_instruction: str` - Main instruction for the agents
- `process_type: str` - Process type (sequential/hierarchical)
- `agents: List[AgentConfig]` - List of agent configurations
## Example Usage
### Basic Usage
```python
from praisonaiagents import AutoAgents
from praisonaiagents.tools import SerperDevTool
agents = AutoAgents(
instructions="Research recent AI developments",
tools=[SerperDevTool()],
verbose=True
)
result = agents.start()
```
### Async Usage
```python
async def main():
agents = AutoAgents(
instructions="Research recent AI developments",
tools=[SerperDevTool()],
process="hierarchical"
)
result = await agents.astart()
import asyncio
asyncio.run(main())
```
### Advanced Configuration
```python
agents = AutoAgents(
instructions="Complex research task",
tools=[SerperDevTool()],
max_agents=5,
process="hierarchical",
manager_llm="gpt-4o",
memory=True,
allow_delegation=True,
max_execution_time=600,
self_reflect=True
)
```
<Note>
For optimal results, provide clear instructions and appropriate tools for your use case.
</Note>
-52
View File
@@ -1,52 +0,0 @@
---
title: "API Reference"
description: "Praison AI Agents - SDK Documentation"
icon: "code"
---
<CardGroup cols={2}>
<Card title="Agent" icon="user" href="/api/praisonaiagents/agent/agent">
Documentation for individual AI agents and their capabilities
</Card>
<Card title="Agents" icon="users" href="/api/praisonaiagents/agents/agents">
Documentation for managing multiple agents and their interactions
</Card>
<Card title="Task" icon="list-check" href="/api/praisonaiagents/task/task">
Documentation for defining and managing tasks
</Card>
<Card title="Process" icon="diagram-project" href="/api/praisonaiagents/process/process">
Documentation for handling task execution flows
</Card>
</CardGroup>
# Module praisonaiagents
## Sub-modules
* praisonaiagents.agent - Agent module for defining individual AI agents
* praisonaiagents.agents - Agents module for managing multiple agents
* praisonaiagents.task - Task module for defining and managing tasks
* praisonaiagents.process - Process module for handling task execution flows
* praisonaiagents.main - Main module containing utility functions
## Functions
### clean_triple_backticks(text: str) → str
Clean triple backticks from text output.
### display_error(message: str, console=None)
Display error messages in the console.
### display_generating(content: str = '', start_time: float | None = None)
Display generation status with optional timing information.
### display_instruction(message: str, console=None)
Display instruction messages in the console.
### display_interaction(message, response, markdown=True, generation_time=None, console=None)
Display interaction between user and agent.
### display_self_reflection(message: str, console=None)
Display agent self-reflection messages.
### display_tool_call(message: str, console=None)
Display tool call messages.
@@ -1,98 +0,0 @@
---
title: "Process Module"
description: "Documentation for the praisonaiagents.process.process module"
icon: "diagram-project"
---
# Module praisonaiagents.process.process
## Classes
### Process
The main class for handling task execution processes in different modes (sequential, hierarchical, workflow).
#### Parameters
- `tasks: Dict[str, Task]` - Dictionary of tasks to be executed
- `agents: List[Agent]` - List of available agents
- `manager_llm: Optional[str] = None` - Language model for manager agent in hierarchical process
- `verbose: bool = False` - Enable verbose logging
#### Methods
- `workflow(self)` - Execute tasks in a workflow pattern with support for loops and conditions
- `sequential(self)` - Execute tasks in sequential order
- `hierarchical(self)` - Execute tasks in hierarchical order with a manager agent
#### Async Methods
- `aworkflow(self) -> AsyncGenerator[str, None]` - Async version of workflow process
- `asequential(self) -> AsyncGenerator[str, None]` - Async version of sequential process
- `ahierarchical(self) -> AsyncGenerator[str, None]` - Async version of hierarchical process
#### Async Process Support
Each process type has an async counterpart that supports non-blocking execution:
```python
class Process:
async def aworkflow(self):
"""Async workflow process execution"""
# Async workflow implementation
async def asequential(self):
"""Async sequential process execution"""
# Async sequential implementation
async def ahierarchical(self):
"""Async hierarchical process execution"""
# Async hierarchical implementation
```
Example usage:
```python
# Create process instance
process = Process(tasks=tasks, agents=agents)
# Use async workflow
async for task_id in process.aworkflow():
# Handle task execution
if tasks[task_id].async_execution:
await handle_async_task(task_id)
else:
handle_sync_task(task_id)
```
#### Async Process Features
- Non-blocking task execution
- Parallel task processing
- Mixed sync/async task support
- Efficient resource utilization
- Async manager coordination (hierarchical)
- Dynamic task scheduling (workflow)
### LoopItems
A Pydantic model for handling loop data in workflow process.
#### Parameters
- `items: List[Any]` - List of items to be processed in a loop
## Process Types
### Sequential Process
- Tasks are executed one after another in a linear fashion
- Each task is completed before moving to the next one
- Simplest form of task execution
### Hierarchical Process
- Uses a manager agent to coordinate task execution
- Manager decides task order and agent assignments
- Provides more complex task orchestration
- Requires manager_llm parameter
- Supports dynamic agent assignment
### Workflow Process
- Supports complex task relationships
- Features:
- Task dependencies
- Conditional execution
- Loops
- Context sharing between tasks
- Maintains task state and relationships
- Handles data flow between tasks
-78
View File
@@ -1,78 +0,0 @@
---
title: "Task Module"
description: "Documentation for the praisonaiagents.task.task module"
icon: "list-check"
---
# Module praisonaiagents.task.task
## Classes
### Task
Represents a task to be executed by an agent.
#### Parameters
- `description: str` - Task description
- `expected_output: str` - Expected output description
- `agent: Agent | None = None` - Agent assigned to the task
- `name: str | None = None` - Task name
- `tools: List[Any] | None = None` - Tools available for the task
- `context: List[Task] | None = None` - Context from other tasks
- `async_execution: bool | None = False` - Enable async execution
- `config: Dict[str, Any] | None = None` - Task configuration
- `output_file: str | None = None` - Output file path
- `output_json: Type[BaseModel] | None = None` - JSON output schema
- `output_pydantic: Type[BaseModel] | None = None` - Pydantic output schema
- `callback: Any | None = None` - Task callback
- `status: str = 'not started'` - Task status
- `result: TaskOutput | None = None` - Task result
- `create_directory: bool | None = False` - Create output directory
- `id: int | None = None` - Task ID
- `images: List[str] | None = None` - Task images
- `next_tasks: List[str] | None = None` - Next tasks
- `task_type: str = 'task'` - Task type
- `condition: Dict[str, List[str]] | None = None` - Task conditions
- `is_start: bool = False` - Is start task
- `loop_state: Dict[str, str | int] | None = None` - Loop state
#### Async Support
The Task class supports asynchronous execution through the following features:
- `async_execution`: Boolean flag to enable async execution
- `callback`: Supports both sync and async callback functions
- `execute_callback`: Internal async method for handling callbacks
Example usage:
```python
from typing import Coroutine
from praisonaiagents import Task, TaskOutput
# Define an async callback
async def async_callback(output: TaskOutput):
await some_async_operation()
print(f"Processed: {output.raw}")
# Create task with async execution
task = Task(
description="Async task example",
expected_output="Async result",
async_execution=True, # Enable async execution
callback=async_callback # Async callback
)
```
#### Callback Types
The Task class supports both synchronous and asynchronous callbacks:
```python
# Type definition
callback: Optional[Union[
Callable[[TaskOutput], Any], # Sync callback
Callable[[TaskOutput], Coroutine[Any, Any, Any]] # Async callback
]]
```
#### Async Task States
- `not started`: Initial state
- `in progress`: Task is being executed
- `completed`: Task finished successfully
- `failed`: Task execution failed
-126
View File
@@ -1,126 +0,0 @@
---
title: "PraisonAI Call"
description: "Guide to PraisonAI's voice-based interaction feature enabling AI customer service through phone calls, including setup and tool integration"
icon: "phone"
---
<iframe width="560" height="315" src="https://www.youtube.com/embed/m1cwrUG2iAk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## AI Customer Service
PraisonAI Call is a feature that enables voice-based interaction with AI models through phone calls. This functionality allows users to have natural conversations with AI agents over traditional phone lines.
## Installation
### Step 1
```bash
pip install "praisonai[call]"
export OPENAI_API_KEY="enter your openai api key here"
export NGROK_AUTH_TOKEN="enter your ngrok auth token here"
praisonai call --public
```
### Step 2
Buy a number at [PraisonAI Dashboard](https://dashboard.praison.ai/)
### Step 3
Enter the Public URL in the PraisonAI Dashboard phone number field
## Features
- Make and receive phone calls with AI agents
- Natural language processing for voice interactions
- Support for multiple phone carriers and providers
- Call recording and transcription capabilities
- Integration with other PraisonAI features
## Adding Tools
1. Create a file called `tools.py`
2. Add the following code:
```python
import yfinance as yf
# Get Stock Price definition
get_stock_price_def = {
"name": "get_stock_price",
"description": "Get the current stock price for a given ticker symbol",
"parameters": {
"type": "object",
"properties": {
"ticker_symbol": {
"type": "string",
"description": "The ticker symbol of the stock (e.g., AAPL, GOOGL)"
}
},
"required": ["ticker_symbol"]
}
}
# Get Stock Price function / Tool
async def get_stock_price_handler(ticker_symbol):
try:
stock = yf.Ticker(ticker_symbol)
hist = stock.history(period="1d")
if hist.empty:
return {"error": f"No data found for ticker {ticker_symbol}"}
current_price = hist['Close'].iloc[-1] # Using -1 is safer than 0
return {"price": str(current_price)}
except Exception as e:
return {"error": str(e)}
get_stock_price = (get_stock_price_def, get_stock_price_handler)
tools = [
get_stock_price
]
```
3. ```bash
pip install yfinance
```
4. ```bash
export OPENAI_API_KEY="enter your openai api key here"
export NGROK_AUTH_TOKEN="enter your ngrok auth token here"
praisonai call --public
```
## Manage Google Calendar Events
See [Google Calendar Tools](tools/googlecalendar.md)
## Deploy
### Docker Deployment
```dockerfile
# Use an official Python runtime as a parent image
FROM python:3.11-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Install PraisonAI with the 'call' extra and ensure it's the latest version
RUN pip install --no-cache-dir --upgrade "praisonai[call]"
# Expose the port the app runs on
EXPOSE 8090
# Run the application
CMD ["praisonai", "call"]
```
-368
View File
@@ -1,368 +0,0 @@
---
title: "Agents"
description: "Understanding Agents in PraisonAI"
icon: "user"
---
# Understanding Agents
Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.
```mermaid
graph LR
%% 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
```
## Key Components
<CardGroup cols={2}>
<Card title="Role & Goal" icon="target">
Defines the agent's purpose and objectives through role definition and specific goals
</Card>
<Card title="Capabilities" icon="toolbox">
Tools and functions available to the agent for task execution
</Card>
<Card title="Memory" icon="brain">
Context retention and learning capabilities across interactions
</Card>
<Card title="Language Model" icon="microchip">
The underlying AI model powering the agent's intelligence
</Card>
</CardGroup>
## Component Details
### Role and Goal
<Tip>
Clear role and goal definitions are crucial for optimal agent performance.
</Tip>
| Component | Description | Example |
|:----------|:------------|:--------|
| **Role** | Agent's function and expertise | Research Analyst, Code Developer |
| **Goal** | Specific objectives to achieve | Analyze market trends, Generate reports |
| **Backstory** | Contextual background | Expert with 10 years of experience |
### Capabilities
<CodeGroup>
```python Basic
agent = 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
)
```
</CodeGroup>
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Create Agent">
Create `app.py`:
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent
agent = Agent(instructions="Your are a helpful AI assistant")
agent.start("Write a movie script about a robot in Mars")
```
```python Multi Agents
from praisonaiagents import Agent, PraisonAIAgents
research_agent = Agent(instructions="Research about AI")
summarise_agent = Agent(instructions="Summarise research agent's findings")
agents = PraisonAIAgents(agents=[research_agent, summarise_agent])
agents.start()
```
</CodeGroup>
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
python app.py
```
You should see:
- Agent initialization
- Agents progress
- Final results
- Generated report
</Step>
</Steps>
## Agent Types
<CardGroup cols={3}>
<Card title="Basic Agent" icon="user" iconType="solid">
<AccordionGroup>
<Accordion title="Overview">
Perfect for straightforward tasks and direct interactions
</Accordion>
<Accordion title="Features">
- Single-purpose focus
- Direct user interaction
- Limited tool set
- Ideal for simple tasks
</Accordion>
</AccordionGroup>
</Card>
<Card title="Specialized Agent" icon="user-gear" iconType="solid">
<AccordionGroup>
<Accordion title="Overview">
Experts in specific domains with advanced capabilities
</Accordion>
<Accordion title="Features">
- Domain expertise
- Advanced capabilities
- Custom tools
- Deep knowledge base
</Accordion>
</AccordionGroup>
</Card>
<Card title="Collaborative Agent" icon="users" iconType="solid">
<AccordionGroup>
<Accordion title="Overview">
Designed for team-based operations and complex workflows
</Accordion>
<Accordion title="Features">
- Team interaction
- Task delegation
- Shared context
- Coordinated actions
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
## Best Practices
<Note>
Always implement proper error handling and resource management in your agent configurations.
</Note>
<CardGroup cols={2}>
<Card title="Agent Design" icon="compass-drafting" iconType="solid">
<Steps>
<Step title="Role Definition">
Define clear, specific roles for each agent
</Step>
<Step title="Goal Setting">
Set specific, measurable goals
</Step>
<Step title="Tool Selection">
Choose relevant tools for the task
</Step>
<Step title="Memory Setup">
Configure appropriate memory settings
</Step>
</Steps>
</Card>
<Card title="Agent Interaction" icon="network-wired" iconType="solid">
<Steps>
<Step title="Communication">
Establish clear communication protocols
</Step>
<Step title="Delegation">
Define explicit delegation rules
</Step>
<Step title="Error Handling">
Implement robust error handling
</Step>
<Step title="Resource Management">
Set up efficient resource allocation
</Step>
</Steps>
</Card>
</CardGroup>
## Async Capabilities
<CardGroup cols={1}>
<Card title="Key Features" icon="bolt" iconType="solid">
<Tabs>
<Tab title="Async Support">
```python
async def main():
agent = Agent(name="AsyncAgent")
result = await agent.aprocess_task()
```
- Full async/await support
- Non-blocking operations
- Enhanced performance
</Tab>
<Tab title="Parallel Execution">
```python
async def parallel_tasks():
tasks = [agent1.task(), agent2.task()]
results = await asyncio.gather(*tasks)
```
- Parallel task execution
- Efficient resource usage
- Improved throughput
</Tab>
<Tab title="Integration">
```python
@agent.async_tool
async def custom_tool():
async with aiohttp.ClientSession() as session:
# Async operations
pass
```
- Async tool integration
- Callback support
- Mixed sync/async operations
</Tab>
</Tabs>
</Card>
</CardGroup>
## Advanced Features
<CardGroup cols={2}>
<Card title="Memory Management" icon="brain">
- Short-term conversation memory
- Long-term knowledge retention
- Context preservation
</Card>
<Card title="Tool Integration" icon="plug">
- Custom tool development
- External API integration
- Resource access control
</Card>
</CardGroup>
## Async Support
Agents now support asynchronous operations through the following methods:
- `achat`: Async version of the chat method
- `astart`: Async version of start method
- `aexecute_task`: Async version of execute_task method
- `arun_task`: Async version of run_task method
- `arun_all_tasks`: Async version of run_all_tasks method
### Example Usage:
```python
import asyncio
from praisonaiagents import Agent, Task, PraisonAIAgents
async def main():
# Create an async agent
async_agent = Agent(
name="AsyncAgent",
role="Async Task Specialist",
goal="Perform async operations",
backstory="Expert in async operations",
tools=[async_search_tool], # Your async tool
verbose=True
)
# Create an async task
async_task = Task(
description="Perform async operation",
expected_output="Async result",
agent=async_agent,
async_execution=True # Enable async execution
)
# Create and start agents with async support
agents = PraisonAIAgents(
agents=[async_agent],
tasks=[async_task],
verbose=True
)
# Start async execution
result = await agents.astart()
print(result)
# Run the async main function
if __name__ == "__main__":
asyncio.run(main())
```
### Key Features:
- Full async/await support
- Parallel task execution
- Async tool integration
- Async callback support
- Mixed sync/async operations
## Next Steps
<CardGroup cols={2}>
<Card
title="Create Your First Agent"
icon="code"
href="/code/quickstart"
>
Follow our quickstart guide to create your first agent
</Card>
<Card
title="API Reference"
icon="book"
href="/api/praisonaiagents/agent/agent"
>
Explore the complete Agent API documentation
</Card>
</CardGroup>
-241
View File
@@ -1,241 +0,0 @@
---
title: "AI Agents with Knowledge"
sidebarTitle: "Knowledge"
description: "Learn how to create AI agents with custom knowledge bases"
icon: "book"
---
```mermaid
flowchart LR
subgraph In[Input]
PDF[PDF]
TXT[TXT]
MD[MD]
end
subgraph Router[Vector Store]
DB[(Vector DB)]
end
subgraph Out[Agents]
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
In --> Router
Router --> A1
Router --> A2
Router --> A3
style In fill:#8B0000,color:#fff
style Router fill:#2E8B57,color:#fff
style Out fill:#8B0000,color:#fff
```
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|---------|--------------------------------|---------------------------|
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
| Purpose | Provide static reference information | Store dynamic context and interactions |
| Storage | Read-only knowledge base | Read-write memory store |
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
## Quick Start
<Steps>
<Step title="Install Package">
Install PraisonAI Agents with knowledge support:
```bash
pip install "praisonaiagents[knowledge]"
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key:
```bash
export OPENAI_API_KEY=xxxxx
```
</Step>
<Step title="Create Script">
Create a new file `app.py`:
```python
from praisonaiagents import Agent
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"]
)
agent.start("What is KAG in one line?")
```
</Step>
</Steps>
## Basic Usage
The simplest way to create a knowledge-based agent is without any configuration:
```python
from praisonaiagents import Agent
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"]
)
agent.start("What is KAG in one line?")
```
## Advanced Configuration
For more control over the knowledge base, you can specify a configuration:
```python
from praisonaiagents import Agent
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "custom_knowledge",
"path": ".praison",
}
}
}
agent = Agent(
name="Knowledge Agent",
instructions="You answer questions based on the provided knowledge.",
knowledge=["small.pdf"],
knowledge_config=config
)
agent.start("What is KAG in one line?")
```
## Multi-Agent Knowledge System
For more complex scenarios, you can create a knowledge-based system with multiple agents:
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
import logging
import os
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Define the configuration for the Knowledge instance
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "knowledge_test",
"path": ".praison",
}
}
}
# Create an agent with knowledge capabilities
knowledge_agent = Agent(
name="KnowledgeAgent",
role="Information Specialist",
goal="Store and retrieve knowledge efficiently",
backstory="Expert in managing and utilizing stored knowledge",
knowledge=["sample.pdf"],
knowledge_config=config,
verbose=True
)
# Define a task for the agent
knowledge_task = Task(
name="knowledge_task",
description="Who is Mervin Praison?",
expected_output="Answer to the question",
agent=knowledge_agent
)
# Create and start the agents
agents = PraisonAIAgents(
agents=[knowledge_agent],
tasks=[knowledge_task],
process="sequential",
user_id="user1"
)
# Start execution
result = agents.start()
```
## Understanding Knowledge Configuration
<AccordionGroup>
<Accordion title="Vector Store Options">
- **Provider**: Choose between different vector store backends (e.g., "chroma")
- **Collection Name**: Name for your knowledge collection
- **Path**: Location to store the vector database
</Accordion>
<Accordion title="Supported File Types">
- PDF documents (*.pdf)
- Text files (*.txt)
- Markdown files (*.md, *.mdx)
- And more...
</Accordion>
<Accordion title="Multi-Agent Setup">
- **Role**: Define specialized roles for knowledge agents
- **Goal**: Set specific knowledge management objectives
- **Process**: Choose between sequential or parallel execution
</Accordion>
</AccordionGroup>
## Features
<CardGroup cols={2}>
<Card title="Custom Knowledge" icon="book">
Import your own documents and data as knowledge sources
</Card>
<Card title="Vector Storage" icon="database">
Efficient storage and retrieval of knowledge embeddings
</Card>
<Card title="Multiple Sources" icon="layer-group">
Combine multiple documents and file types
</Card>
<Card title="Persistent Storage" icon="hard-drive">
Save and reuse knowledge bases across sessions
</Card>
</CardGroup>
## Best Practices
1. **Document Preparation**
- Clean and well-formatted documents work best
- Break large documents into smaller chunks
- Use consistent formatting
2. **Knowledge Organization**
- Group related documents together
- Use meaningful file names
- Keep knowledge bases focused and relevant
3. **Performance Optimization**
- Monitor vector store size
- Clean up unused collections
- Use appropriate chunk sizes
4. **Multi-Agent Coordination**
- Define clear roles and responsibilities
- Set appropriate logging levels for debugging
- Use unique collection names for different agent groups
## Next Steps
- Learn about [Memory Management](/concepts/memory) for long-term recall
- Explore [Tool Integration](/concepts/tools) for enhanced capabilities
- Check out [Examples](/examples) for implementation ideas
-472
View File
@@ -1,472 +0,0 @@
---
title: "AI Agents with Memory"
sidebarTitle: "Memory"
description: "Learn how to create AI agents with memory capabilities for maintaining context and information across tasks."
icon: "brain"
---
```mermaid
flowchart TB
subgraph Memory
direction TB
STM[Short Term]
LTM[Long Term]
end
subgraph Store
direction TB
DB[(Vector DB)]
end
Input[Input] ---> Agents
subgraph Agents
direction LR
A1[Agent 1]
A2[Agent 2]
A3[Agent 3]
end
Agents ---> Output[Output]
Memory <--> Store
Store <--> A1
Store <--> A2
Store <--> A3
style Memory fill:#189AB4,color:#fff
style Store fill:#2E8B57,color:#fff
style Agents fill:#8B0000,color:#fff
style Input fill:#8B0000,color:#fff
style Output fill:#8B0000,color:#fff
```
| Feature | [Knowledge](/concepts/knowledge) | [Memory](/concepts/memory) |
|---------|--------------------------------|---------------------------|
| When Used | Pre-loaded before agent execution | Created and updated during runtime |
| Purpose | Provide static reference information | Store dynamic context and interactions |
| Storage | Read-only knowledge base | Read-write memory store |
| Persistence | Permanent until explicitly changed | Can be temporary (STM) or persistent (LTM) |
| Updates | Manual updates through knowledge files | Automatic updates during agent execution |
## Quick Start
<Tabs>
<Tab title="Code">
<Steps>
<Step title="Install Package">
First, install the PraisonAI Agents package:
```bash
pip install "praisonaiagents[memory]" duckduckgo_search
```
duckduckgo_search is a tool that allows agents to search the web.
It is required for the multiple agents example shown below.
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `app.py` with the basic setup:
<CodeGroup>
```python Single Agent
from praisonaiagents.agents.agents import Agent, Task, PraisonAIAgents
# Create blog writer agent
blog_agent = Agent(
role="Blog Writer",
goal="Write a blog post about AI",
backstory="Expert at writing blog posts",
llm="gpt-4o-mini"
)
# Create blog writing task
blog_task = Task(
description="Write a blog post about AI trends",
expected_output="Well-written blog post about AI trends",
agent=blog_agent
)
# Create and start the agents with memory enabled
agents = PraisonAIAgents(
agents=[blog_agent],
tasks=[blog_task],
memory=True
)
# Start execution
result = agents.start()
print(result)
```
```python Multiple Agents
from praisonaiagents.agents.agents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import duckduckgo
# Create research agent with memory
research_agent = Agent(
role="Research Analyst",
goal="Research and document key information about topics",
backstory="Expert at analyzing and storing information in memory",
llm="gpt-4o-mini",
tools=[duckduckgo]
)
# Create blog writer agent
blog_agent = Agent(
role="Blog Writer",
goal="Write a blog post about the research",
backstory="Expert at writing blog posts",
llm="gpt-4o-mini"
)
# Create research task
research_task = Task(
description="Research and document key information about AI trends",
expected_output="Detailed research findings about AI trends",
agent=research_agent
)
# Create blog writing task
blog_task = Task(
description="Write a blog post about the research findings",
expected_output="Well-written blog post based on research",
agent=blog_agent
)
# Create and start the agents with advanced memory configuration
agents = PraisonAIAgents(
agents=[research_agent, blog_agent],
tasks=[research_task, blog_task],
memory=True
)
# Start execution
result = agents.start()
print(result)
```
</CodeGroup>
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
python app.py
```
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install Package">
Install the PraisonAI package:
```bash
pip install praisonai
```
</Step>
<Step title="Set API Key">
Set your OpenAI API key as an environment variable in your terminal:
```bash
export OPENAI_API_KEY=your_api_key_here
```
</Step>
<Step title="Create a file">
Create a new file `agents.yaml` with the basic setup:
```yaml
framework: praisonai
process: sequential
memory: true
roles:
researcher:
backstory: Expert at analyzing and storing information in memory.
goal: Research and document key information about topics
role: Research Analyst
llm: gpt-4o-mini
tools:
- duckduckgo
tasks:
research_task:
description: Research and document key information about topics.
expected_output: Detailed research findings.
writer:
backstory: Expert at writing blog posts.
goal: Write a blog post about the research
role: Blog Writer
llm: gpt-4o-mini
tasks:
blog_task:
description: Write a blog post about the research.
expected_output: Well-written blog post based on research.
```
</Step>
<Step title="Start Agents">
Type this in your terminal to run your agents:
```bash
praisonai agents.yaml
```
</Step>
</Steps>
</Tab>
</Tabs>
<Note>
**Requirements**
- Python 3.10 or higher
- OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
- Basic understanding of Python
</Note>
## Understanding Memory
<Card title="What is Agent Memory?" icon="question">
Memory in AI agents enables them to:
- Maintain context across multiple tasks
- Remember previous interactions and findings
- Build upon past knowledge
- Share information between agents
- Create more coherent and contextual responses
</Card>
## Features
<CardGroup cols={2}>
<Card title="Context Retention" icon="brain">
Maintain information across multiple interactions.
</Card>
<Card title="Information Sharing" icon="share-nodes">
Share knowledge between multiple agents.
</Card>
<Card title="Long-term Storage" icon="database">
Store and retrieve information over extended periods.
</Card>
<Card title="Memory Types" icon="layer-group">
Support for different memory types (short-term, long-term).
</Card>
</CardGroup>
## Multi-Agent Memory
<Tabs>
<Tab title="Code">
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import duckduckgo
# Create first agent for research
researcher = Agent(
role="Research Analyst",
goal="Research and analyze market trends",
backstory="Expert in market research and data analysis",
tools=[duckduckgo],
verbose=True
)
# Create second agent for report writing
writer = Agent(
role="Report Writer",
goal="Create comprehensive market reports",
backstory="Expert in technical writing and report creation",
verbose=True
)
# Create research task
research_task = Task(
description="Research current market trends",
expected_output="Detailed market analysis",
agent=researcher
)
# Create writing task
report_task = Task(
description="Create a market report based on research",
expected_output="Comprehensive market report",
agent=writer
)
# Create and start the agents with memory
agents = PraisonAIAgents(
agents=[researcher, writer],
tasks=[research_task, report_task],
memory=True,
process="sequential"
)
# Start execution
result = agents.start()
```
</Tab>
<Tab title="No Code">
```yaml
framework: praisonai
process: sequential
memory: true
roles:
researcher:
backstory: Expert in market research and data analysis.
goal: Research and analyze market trends
role: Research Analyst
tools:
- duckduckgo
tasks:
research_task:
description: Research current market trends.
expected_output: Detailed market analysis.
writer:
backstory: Expert in technical writing and report creation.
goal: Create comprehensive market reports
role: Report Writer
tasks:
report_task:
description: Create a market report based on research.
expected_output: Comprehensive market report.
```
</Tab>
</Tabs>
### Configuration Options
```python
# Create an agent with memory configuration
agent = Agent(
role="Research Analyst",
goal="Research and retain information",
backstory="Expert in research and analysis",
tools=[duckduckgo],
verbose=True, # Enable detailed logging
llm="gpt-4o" # Language model to use
)
# Create agents with memory options
agents = PraisonAIAgents(
agents=[agent],
tasks=[task],
memory=True, # Enable memory
memory_config={
"provider": "rag", # Use RAG for semantic search
"use_embedding": True, # Enable embeddings for better search
"short_db": ".praison/short_term.db", # Path for short-term memory
"long_db": ".praison/long_term.db", # Path for long-term memory
"rag_db_path": ".praison/chroma_db" # Path for vector database
}
)
```
## Troubleshooting
<CardGroup cols={2}>
<Card title="Memory Issues" icon="triangle-exclamation">
If memory isn't working as expected:
- Check memory configuration
- Enable verbose mode for debugging
- Verify memory provider settings
</Card>
<Card title="Context Flow" icon="code">
If context isn't being maintained:
- Review task dependencies
- Check memory configuration
- Verify agent communication
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="AutoAgents" icon="robot" href="../features/autoagents">
Learn about automatically created and managed AI agents
</Card>
<Card title="Mini Agents" icon="microchip" href="../features/mini">
Explore lightweight, focused AI agents
</Card>
</CardGroup>
<Note>
For optimal results, configure memory settings based on your specific use case requirements and expected interaction patterns.
</Note>
### Memory Configuration Options
The memory system in PraisonAI supports various configuration options to customize how agents store and retrieve information:
```python
memory_config = {
# Memory Provider
"provider": "rag", # Options: "rag", "mem0", "none"
"use_embedding": True, # Enable semantic search with embeddings
# Storage Paths
"short_db": ".praison/short_term.db", # Short-term memory SQLite DB
"long_db": ".praison/long_term.db", # Long-term memory SQLite DB
"rag_db_path": ".praison/chroma_db", # Vector database path
# Memory Settings
"ttl": 3600, # Time to live for memory items (in seconds)
# Optional Mem0 Config (if using mem0 provider)
"config": {
"api_key": "...", # Mem0 API key
"org_id": "...", # Organization ID
"project_id": "..." # Project ID
}
}
# Create agents with memory configuration
agents = PraisonAIAgents(
agents=[agent],
tasks=[task],
memory=True,
memory_config=memory_config
)
```
### Memory Types
PraisonAI's memory system includes several types of memory:
<CardGroup cols={2}>
<Card title="Short-term Memory" icon="bolt">
- Temporary storage for current context
- Automatically cleared between sessions
- Fast access for immediate task context
</Card>
<Card title="Long-term Memory" icon="database">
- Persistent storage for important information
- Semantic search capabilities with RAG
- Quality-based storage decisions
</Card>
</CardGroup>
### Memory Quality Control
PraisonAI includes built-in quality control for memory storage:
```python
# Example of storing with quality metrics
agents.memory.store_long_term(
text="Important information to remember",
metadata={
"task_id": "task_123",
"agent": "research_agent"
},
completeness=0.9, # How complete is the information
relevance=0.85, # How relevant to the task
clarity=0.95, # How clear and well-structured
accuracy=0.9, # How accurate is the information
weights={ # Custom weights for quality score
"completeness": 0.3,
"relevance": 0.3,
"clarity": 0.2,
"accuracy": 0.2
}
)
# Search with quality filter
results = agents.memory.search_long_term(
query="search query",
min_quality=0.8, # Only return high-quality matches
limit=5 # Maximum number of results
)
-453
View File
@@ -1,453 +0,0 @@
---
title: "Process"
description: "Understanding Process Types in PraisonAI"
icon: "diagram-project"
---
# Understanding Process Types
Process types in PraisonAI define how tasks are executed and how agents collaborate. Each process type offers different patterns for task execution and agent coordination.
## Process Types Overview
<CardGroup cols={3}>
<Card
title="Sequential Process"
icon="arrow-right"
href="/sequential-process"
>
Linear task execution in a predefined order
</Card>
<Card
title="Hierarchical Process"
icon="sitemap"
href="/hierarchical-process"
>
Manager-coordinated task execution with dynamic assignment
</Card>
<Card
title="Workflow Process"
icon="diagram-project"
href="/workflow-process"
>
Complex task flows with conditional execution and state management
</Card>
</CardGroup>
## Sequential Process
```mermaid
graph LR
Input[Input] --> A1
subgraph Agents
direction LR
A1[Agent 1] --> A2[Agent 2] --> A3[Agent 3]
end
A3 --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class A1,A2,A3 process
class Agents transparent
```
The simplest form of task execution where tasks are performed one after another.
<Card>
### Characteristics
- Linear execution flow
- Predictable order
- Simple dependency management
- Direct task progression
### Usage
```python
agents = PraisonAIAgents(
agents=[agent1, agent2],
tasks=[task1, task2, task3],
process="sequential"
)
```
</Card>
## Hierarchical Process
```mermaid
graph TB
Input[Input] --> Manager
subgraph Agents
Manager[Manager Agent]
subgraph Workers
direction LR
W1[Worker 1]
W2[Worker 2]
W3[Worker 3]
end
Manager --> W1
Manager --> W2
Manager --> W3
end
W1 --> Manager
W2 --> Manager
W3 --> Manager
Manager --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Manager,W1,W2,W3 process
class Agents,Workers transparent
```
Uses a manager agent to coordinate task execution and agent assignments.
<Card>
### Characteristics
- Manager-driven coordination
- Dynamic task assignment
- Flexible execution order
- Intelligent resource allocation
### Configuration
```python
agents = PraisonAIAgents(
agents=[manager_agent, worker_agent1, worker_agent2],
tasks=[task1, task2],
process="hierarchical",
manager_llm="gpt-4o"
)
```
</Card>
## Workflow Process
```mermaid
graph LR
Input[Input] --> Start
subgraph Workflow
direction LR
Start[Start] --> C1{Condition}
C1 --> |Yes| A1[Agent 1]
C1 --> |No| A2[Agent 2]
A1 --> Join
A2 --> Join
Join --> A3[Agent 3]
end
A3 --> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef decision fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Start,A1,A2,A3,Join process
class C1 decision
class Workflow transparent
```
Advanced process type supporting complex task relationships and conditional execution.
<Card>
### Features
- Task dependencies
- Conditional branching
- Loop handling
- Context sharing
- State management
### Implementation
```python
task_workflow = {
"start_task": {
"next": ["decision_task"],
"type": "task"
},
"decision_task": {
"type": "decision",
"conditions": {
"success": ["process_task"],
"failure": ["error_task"]
}
}
}
```
</Card>
## Getting Started
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Create Agent">
Create `app.py`:
<CodeGroup>
```python Single Agent Sequential Process
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create an agent
researcher = Agent(
name="Researcher",
role="Senior Research Analyst",
goal="Uncover cutting-edge developments in AI",
backstory="You are an expert at a technology research group",
verbose=True,
llm="gpt-4o"
)
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
# Run the agents
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
verbose=False,
process="sequential"
)
result = agents.start()
```
```python Multiple Agents Hierarchical Process
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create multiple agents
researcher = Agent(
name="Researcher",
role="Senior Research Analyst",
goal="Uncover cutting-edge developments in AI",
backstory="You are an expert at a technology research group",
verbose=True,
llm="gpt-4o",
markdown=True
)
writer = Agent(
name="Writer",
role="Tech Content Strategist",
goal="Craft compelling content on tech advancements",
backstory="You are a content strategist",
llm="gpt-4o",
markdown=True
)
# Define multiple tasks
task1 = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
task2 = Task(
name="writing_task",
description="Create a blog post about AI advancements",
expected_output="A blog post",
agent=writer
)
# Run with hierarchical process
agents = PraisonAIAgents(
agents=[researcher, writer],
tasks=[task1, task2],
verbose=False,
process="hierarchical",
manager_llm="gpt-4o"
)
result = agents.start()
```
</CodeGroup>
</Step>
</Steps>
<br /><br />
<div className="relative w-full aspect-video">
<iframe
className="absolute top-0 left-0 w-full h-full"
src="https://www.youtube.com/embed/yWTH44QPl2A"
title="YouTube video player"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
></iframe>
</div>
<br />
## Advanced Features
<CardGroup cols={2}>
<Card title="State Management" icon="database" iconType="solid">
<AccordionGroup>
<Accordion title="Task State Tracking">
Monitor and manage the progress of each task in real-time
</Accordion>
<Accordion title="Context Preservation">
Maintain important information across different stages of execution
</Accordion>
<Accordion title="Data Flow Control">
Manage how data moves between tasks and agents efficiently
</Accordion>
</AccordionGroup>
</Card>
<Card title="Error Handling" icon="shield-check" iconType="solid">
<AccordionGroup>
<Accordion title="Graceful Recovery">
Automatically handle failures and continue execution
</Accordion>
<Accordion title="Alternative Paths">
Switch to backup plans when primary execution fails
</Accordion>
<Accordion title="Error Reporting">
Detailed error logs and diagnostic information
</Accordion>
</AccordionGroup>
</Card>
<Card title="Monitoring" icon="chart-line" iconType="solid">
<AccordionGroup>
<Accordion title="Progress Tracking">
Real-time visibility into task completion status
</Accordion>
<Accordion title="Performance Metrics">
Measure execution time and resource efficiency
</Accordion>
<Accordion title="Resource Usage">
Monitor system resource utilization
</Accordion>
</AccordionGroup>
</Card>
<Card title="Integration" icon="plug" iconType="solid">
<AccordionGroup>
<Accordion title="External Systems">
Connect with other services and platforms
</Accordion>
<Accordion title="API Sync">
Maintain data consistency across systems
</Accordion>
<Accordion title="Event Handling">
React to system and external events
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
## Async Processing
<Note>
All process types support asynchronous execution through async generators, enabling efficient parallel processing and non-blocking operations.
</Note>
### Core Async Methods
<CardGroup cols={3}>
<Card title="asequential" icon="arrow-right">
Async version of sequential process for non-blocking linear execution
</Card>
<Card title="aworkflow" icon="diagram-project">
Async workflow process for complex parallel task execution
</Card>
<Card title="ahierarchical" icon="sitemap">
Async hierarchical process for distributed task management
</Card>
</CardGroup>
### Process-Specific Features
<Tabs>
<Tab title="Sequential Process">
<Card>
- Tasks execute in order but don't block
- Maintains sequence while allowing async operations
- Perfect for I/O-heavy tasks
```python
async def main():
agents = PraisonAIAgents(
process="sequential",
async_mode=True
)
await agents.astart()
```
</Card>
</Tab>
<Tab title="Workflow Process">
<Card>
- Parallel execution of independent tasks
- Async branching and merging
- Dynamic task scheduling based on conditions
```python
async def main():
agents = PraisonAIAgents(
process="workflow",
async_mode=True,
parallel_tasks=True
)
await agents.astart()
```
</Card>
</Tab>
<Tab title="Hierarchical Process">
<Card>
- Async manager delegation
- Parallel subtask execution
- Dynamic worker assignment
```python
async def main():
agents = PraisonAIAgents(
process="hierarchical",
async_mode=True,
dynamic_assignment=True
)
await agents.astart()
```
</Card>
</Tab>
</Tabs>
### Key Benefits
<CardGroup cols={2}>
<Card title="Performance" icon="bolt">
- Efficient resource utilization
- Reduced waiting time
- Better throughput
</Card>
<Card title="Flexibility" icon="puzzle-piece">
- Mix sync and async tasks
- Adaptable execution patterns
- Easy scaling
</Card>
</CardGroup>
-530
View File
@@ -1,530 +0,0 @@
---
title: "Tasks"
description: "Understanding Tasks in PraisonAI"
icon: "list-check"
---
# Understanding Tasks
Tasks are units of work that agents execute. Each task has a clear goal, input requirements, and expected outputs.
```mermaid
graph LR
Input[Input] ---> Task
subgraph Task
direction LR
Role[Role]
Goal[Goal]
Story[Backstory]
Expected[Expected Output]
Role --> Goal
Goal --> Story
Story --> Expected
end
Task ---> Output[Output]
classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
classDef transparent fill:none,stroke:none
class Input,Output input
class Role,Goal,Story,Expected process
class Task transparent
```
## Core Components
<CardGroup cols={2}>
<Card title="Task Definition" icon="file-lines">
Clear description of work to be done and expected outputs
</Card>
<Card title="Agent Assignment" icon="user-check">
Matching tasks with capable agents
</Card>
<Card title="Tool Access" icon="toolbox">
Resources available for task completion
</Card>
<Card title="Output Handling" icon="file-export">
Managing and formatting task results
</Card>
</CardGroup>
## 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 Dependencies
| Relationship | Description | Example |
|:-------------|:------------|:--------|
| **Sequential** | Tasks run one after another | Research → Analysis → Report |
| **Parallel** | Independent tasks run simultaneously | Data Collection + Processing |
| **Conditional** | Tasks depend on previous results | Success → Next Task, Failure → Retry |
## Advanced Features
<CardGroup cols={2}>
<Card title="Output Handling" icon="file-code">
- Multiple output formats
- Structured data validation
- File system integration
</Card>
<Card title="Task Control" icon="sliders">
- Execution flow control
- Error recovery
- Progress tracking
</Card>
</CardGroup>
## Getting Started
<Steps>
<Step title="Install PraisonAI">
Install the core package:
```bash Terminal
pip install praisonaiagents
```
</Step>
<Step title="Configure Environment">
```bash Terminal
export OPENAI_API_KEY=your_openai_key
```
Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
</Step>
<Step title="Create Agent">
Create `app.py`:
<CodeGroup>
```python Single Agent
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create an agent
researcher = Agent(
name="Researcher",
role="Senior Research Analyst",
goal="Uncover cutting-edge developments in AI",
backstory="You are an expert at a technology research group",
verbose=True,
llm="gpt-4o"
)
# Define a task
task = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
# Run the agents
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
verbose=False
)
result = agents.start()
```
```python Multiple Agents
from praisonaiagents import Agent, Task, PraisonAIAgents
# Create multiple agents
researcher = Agent(
name="Researcher",
role="Senior Research Analyst",
goal="Uncover cutting-edge developments in AI",
backstory="You are an expert at a technology research group",
verbose=True,
llm="gpt-4o",
markdown=True
)
writer = Agent(
name="Writer",
role="Tech Content Strategist",
goal="Craft compelling content on tech advancements",
backstory="You are a content strategist",
llm="gpt-4o",
markdown=True
)
# Define multiple tasks
task1 = Task(
name="research_task",
description="Analyze 2024's AI advancements",
expected_output="A detailed report",
agent=researcher
)
task2 = Task(
name="writing_task",
description="Create a blog post about AI advancements",
expected_output="A blog post",
agent=writer
)
# Run with hierarchical process
agents = PraisonAIAgents(
agents=[researcher, writer],
tasks=[task1, task2],
verbose=False,
process="hierarchical",
manager_llm="gpt-4o"
)
result = agents.start()
```
</CodeGroup>
</Step>
</Steps>
## Best Practices
<Note>
Design tasks to be atomic and focused. Each task should have a single, clear responsibility.
</Note>
<CardGroup cols={2}>
<Card title="Task Design Principles" icon="compass-drafting" iconType="solid">
<AccordionGroup>
<Accordion title="Clear Task Descriptions">
Write precise, unambiguous task descriptions that clearly state the task's purpose and requirements.
```python
task = Task(
description=(
"Analyze Q4 2024 sales data "
"and generate growth metrics"
),
expected_output="Sales growth report"
)
```
</Accordion>
<Accordion title="Success Criteria">
Define measurable success criteria to ensure task completion can be properly evaluated.
```python
task = Task(
success_criteria={
"format": "markdown",
"metrics": [
"growth_rate",
"revenue_change"
],
"min_confidence": 0.95
}
)
```
</Accordion>
<Accordion title="Task Dependencies">
Specify any dependencies or prerequisites for the task.
```python
task = Task(
description="Generate final report",
dependencies=[
data_collection_task,
analysis_task
],
wait_for_dependencies=True
)
```
</Accordion>
</AccordionGroup>
</Card>
<Card title="Resource Management" icon="server" iconType="solid">
<AccordionGroup>
<Accordion title="Tool Selection">
Choose appropriate tools that match your task's requirements.
```python
task = Task(
tools=[
DataAnalyzer(),
ReportGenerator(),
MetricsCalculator()
],
tool_config={
"timeout": 30,
"retry": True
}
)
```
</Accordion>
<Accordion title="Error Handling">
Implement comprehensive error management strategies.
```python
task = Task(
error_strategy="retry",
max_retries=3,
fallback_handler=handler,
error_callbacks=[
log_error,
notify_admin
]
)
```
</Accordion>
<Accordion title="Resource Limits">
Set appropriate resource constraints for optimal performance.
```python
task = Task(
memory_limit="2GB",
timeout=300,
max_concurrent=5,
cpu_priority="high",
auto_scale=True
)
```
</Accordion>
<Accordion title="Performance Monitoring">
Configure monitoring and logging for task execution.
```python
task = Task(
monitoring={
"metrics": ["duration", "memory", "cpu"],
"log_level": "INFO",
"trace_enabled": True,
"alert_threshold": 0.85
}
)
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
## Async Task Execution
<CardGroup cols={1}>
<Card title="Async Task Features" icon="bolt" iconType="solid">
<Tabs>
<Tab title="Basic Configuration">
```python
async_task = Task(
description="Perform async operation",
expected_output="Async result",
agent=async_agent,
async_execution=True, # Enable async execution
callback=async_callback # Optional async callback
)
```
- Enable async execution with `async_execution=True`
- Perfect for I/O-heavy operations
- Supports parallel task execution
</Tab>
<Tab title="Async Callbacks">
```python
async def async_callback(output: TaskOutput):
await asyncio.sleep(1) # Simulate async operation
print(f"Processed output: {output.raw}")
task = Task(
description="Task with async callback",
expected_output="Result",
agent=agent,
async_execution=True,
callback=async_callback
)
```
- Support for async callbacks
- Process results asynchronously
- Handle task completion events
</Tab>
<Tab title="Mixed Execution">
```python
# Create mixed task types
sync_task = Task(
description="Synchronous operation",
async_execution=False
)
async_task = Task(
description="Asynchronous operation",
async_execution=True
)
# Run with mixed execution
agents = PraisonAIAgents(
agents=[sync_agent, async_agent],
tasks=[sync_task, async_task]
)
result = await agents.astart()
```
- Mix sync and async tasks
- Flexible execution patterns
- Optimal resource utilization
</Tab>
</Tabs>
</Card>
</CardGroup>
<Tip>
**Pro Tip**: Use async execution for tasks that involve I/O operations (like API calls or file operations) to improve overall performance. Keep CPU-intensive tasks synchronous.
</Tip>
## Next Steps
<CardGroup cols={2}>
<Card
title="Create Tasks"
icon="plus"
href="/code/quickstart"
>
Learn how to create and configure tasks
</Card>
<Card
title="Task API"
icon="code"
href="/api/praisonaiagents/task/task"
>
Explore the complete Task API documentation
</Card>
</CardGroup>
-647
View File
@@ -1,647 +0,0 @@
---
title: "AI Agents with Tools"
sidebarTitle: "Tools"
description: "Learn how to create AI agents that can use tools to interact with external systems and perform actions."
icon: "screwdriver-wrench"
---
```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
```
| Feature | [Knowledge](/concepts/knowledge) | [Tools](/concepts/tools) |
|---------|--------------------------------|---------------------------|
| Purpose | Static reference information | Dynamic interaction capabilities |
| Access | Read-only reference | Execute actions and commands |
| Updates | Manual through files | Real-time through tool calls |
| Storage | Knowledge base | Assigned to specific agents |
| Persistence | Permanent until changed | Available during agent execution |
## Quick Start
Tools are functions that agents can use to interact with external systems and perform actions. They are essential for creating agents that can do more than just process text.
## Creating Custom Tool
<Steps>
<Step>
Create any function that you want to use as a tool, that performs a specific task.
```python
from duckduckgo_search import DDGS
from typing import List, Dict
# Tool Implementation
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search using DuckDuckGo
Args:
query (str): The search query string
Returns:
List[Dict]: List of search results containing title, URL, and snippet
"""
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
```
</Step>
<Step>
Assign the tool to an agent
```python
data_agent = Agent(
name="DataCollector",
role="Search Specialist",
goal="Perform internet searches to collect relevant information.",
backstory="Expert in finding and organising internet data.",
tools=[internet_search_tool], ## Add the tool to the agent i.e the function name
)
```
</Step>
</Steps>
<Card title="That's it!">
<Check>You have created a custom tool and assigned it to an agent.</Check>
</Card>
## Implementing Tools Full Code Example
<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`
```python
from praisonaiagents import Agent, Task, PraisonAIAgents
from duckduckgo_search import DDGS
from typing import List, Dict
# 1. Tool Implementation
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search using DuckDuckGo
Args:
query (str): The search query string
Returns:
List[Dict]: List of search results containing title, URL, and snippet
"""
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
# 2. Assign the tool to an agent
data_agent = Agent(
name="DataCollector",
role="Search Specialist",
goal="Perform internet searches to collect relevant information.",
backstory="Expert in finding and organising internet data.",
tools=[internet_search_tool],
self_reflect=False
)
# 3. Task Definition
collect_task = Task(
description="Perform an internet search using the query: 'AI job trends in 2024'. Return results as a list of title, URL, and snippet.",
expected_output="List of search results with titles, URLs, and snippets.",
agent=data_agent,
name="collect_data",
)
# 4. Start Agents
agents = PraisonAIAgents(
agents=[data_agent],
tasks=[collect_task],
process="sequential"
)
agents.start()
```
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
python app.py
```
</Step>
</Steps>
</Tab>
<Tab title="No Code">
<Steps>
<Step title="Install PraisonAI">
Install the core package and duckduckgo_search package:
```bash Terminal
pip install praisonai duckduckgo_search
```
</Step>
<Step title="Create Custom Tool">
<Info>
To add additional tools/features you need some coding which can be generated using ChatGPT or any LLM
</Info>
Create a new file `tools.py` with the following content:
```python
from duckduckgo_search import DDGS
from typing import List, Dict
# 1. Tool
def internet_search_tool(query: str) -> List[Dict]:
"""
Perform Internet Search
"""
results = []
ddgs = DDGS()
for result in ddgs.text(keywords=query, max_results=5):
results.append({
"title": result.get("title", ""),
"url": result.get("href", ""),
"snippet": result.get("body", "")
})
return results
```
</Step>
<Step title="Create Agent">
Create a new file `agents.yaml` with the following content:
```yaml
framework: praisonai
topic: create movie script about cat in mars
roles:
scriptwriter:
backstory: Expert in dialogue and script structure, translating concepts into
scripts.
goal: Write a movie script about a cat in Mars
role: Scriptwriter
tools:
- internet_search_tool # <-- Tool assigned to Agent here
tasks:
scriptwriting_task:
description: Turn the story concept into a production-ready movie script,
including dialogue and scene details.
expected_output: Final movie script with dialogue and scene details.
```
</Step>
<Step title="Start Agents">
Execute your script:
```bash Terminal
praisonai agents.yaml
```
</Step>
</Steps>
</Tab>
</Tabs>
## In-build Tools in PraisonAI
<CardGroup cols={2}>
<Card title="Search Tools" icon="magnifying-glass" href="/tools/search">
Tools for searching and retrieving information from various sources
</Card>
<Card title="Python Tools" icon="python" href="/tools/python_tools">
Essential Python utilities for data manipulation and scripting
</Card>
<Card title="Spider Tools" icon="spider" href="/tools/spider_tools">
Web crawling and scraping capabilities for data extraction
</Card>
<Card title="Arxiv Tools" icon="book" href="/tools/arxiv_tools">
Access and search academic papers from arXiv repository
</Card>
<Card title="Newspaper Tools" icon="newspaper" href="/tools/newspaper_tools">
Extract and parse content from news articles and websites
</Card>
<Card title="DuckDB Tools" icon="database" href="/tools/duckdb_tools">
Fast analytical SQL database operations and queries
</Card>
<Card title="DuckDuckGo Tools" icon="duck" href="/tools/duckduckgo_tools">
Web search functionality using DuckDuckGo's API
</Card>
<Card title="Calculator Tools" icon="calculator" href="/tools/calculator_tools">
Perform mathematical calculations and conversions
</Card>
<Card title="YAML Tools" icon="file-code" href="/tools/yaml_tools">
Parse and manipulate YAML format data
</Card>
<Card title="JSON Tools" icon="brackets-curly" href="/tools/json_tools">
Handle JSON data structures and operations
</Card>
<Card title="Pandas Tools" icon="table" href="/tools/pandas_tools">
Data analysis and manipulation using Pandas
</Card>
<Card title="YFinance Tools" icon="chart-line" href="/tools/yfinance_tools">
Fetch financial market data from Yahoo Finance
</Card>
<Card title="Shell Tools" icon="terminal" href="/tools/shell_tools">
Execute shell commands and system operations
</Card>
<Card title="Wikipedia Tools" icon="book-open" href="/tools/wikipedia_tools">
Access and search Wikipedia articles and data
</Card>
<Card title="XML Tools" icon="code" href="/tools/xml_tools">
Process and manipulate XML format data
</Card>
<Card title="File Tools" icon="file" href="/tools/file_tools">
File system operations and management utilities
</Card>
<Card title="Excel Tools" icon="file-excel" href="/tools/excel_tools">
Work with Excel spreadsheets and workbooks
</Card>
<Card title="CSV Tools" icon="file-csv" href="/tools/csv_tools">
Handle CSV file operations and transformations
</Card>
</CardGroup>
## Tools Overview
<CardGroup cols={3}>
<Card
title="Search Tools"
icon="magnifying-glass"
iconType="solid"
>
Tools for searching and retrieving information from various sources
</Card>
<Card
title="File Tools"
icon="file"
iconType="solid"
>
Tools for reading, writing, and manipulating files
</Card>
<Card
title="API Tools"
icon="code"
iconType="solid"
>
Tools for interacting with external APIs and services
</Card>
</CardGroup>
## Advanced Tool Features
### Tool Configuration
<Frame>
```python
def configured_tool(
query: str,
max_results: int = 5,
timeout: int = 10
) -> List[Dict]:
"""
Example of a configurable tool
Args:
query (str): Search query
max_results (int): Maximum number of results
timeout (int): Request timeout in seconds
Returns:
List[Dict]: Search results
"""
# Tool implementation
pass
```
</Frame>
### Tool Chaining
<Frame>
```python
def chain_tools(input_data: str) -> Dict:
"""
Example of chaining multiple tools
Args:
input_data (str): Input data
Returns:
Dict: Processed results
"""
# 1. Search for data
search_results = internet_search_tool(input_data)
# 2. Process results
processed_data = process_tool(search_results)
# 3. Format output
return format_tool(processed_data)
```
</Frame>
### Tool Categories
<CardGroup cols={3}>
<Card title="Data Collection Tools">
- Web scraping
- API integration
- Database queries
</Card>
<Card title="Processing Tools">
- Data transformation
- Text analysis
- Image processing
</Card>
<Card title="Output Tools">
- File generation
- Report creation
- Data visualization
</Card>
</CardGroup>
## Tool Integration
### Adding Tools to Agents
<Frame>
```python
# Multiple tools
agent = Agent(
name="MultiTool Agent",
tools=[
internet_search_tool,
file_processing_tool,
api_integration_tool
]
)
```
</Frame>
### Tool Dependencies
<Frame>
```python
# Tool with dependencies
def advanced_tool(data: Dict) -> Dict:
"""
Tool that depends on external libraries
Args:
data (Dict): Input data
Returns:
Dict: Processed data
"""
try:
import required_library
# Tool implementation
return processed_result
except ImportError:
raise Exception("Required library not installed")
```
</Frame>
## Tool Guidelines
<CardGroup cols={2}>
<Card title="Best Practices">
1. **Type Hints**
- Use Python type hints
- Define clear input/output types
- Document complex types
2. **Documentation**
- Write clear docstrings
- Explain parameters
- Provide usage examples
3. **Error Handling**
- Handle exceptions gracefully
- Return meaningful errors
- Validate inputs
</Card>
<Card title="Tool Types">
1. **Search Tools**
- Web search
- Database queries
- Document search
2. **File Tools**
- Read/write operations
- File conversion
- Data extraction
3. **API Tools**
- REST API calls
- GraphQL queries
- Service integration
</Card>
</CardGroup>
## Best Practices Summary
<Note>
Following these best practices will help you create robust, efficient, and secure tools in PraisonAI.
</Note>
<CardGroup cols={1}>
<Card title="Design Principles" icon="compass-drafting" iconType="solid">
<AccordionGroup>
<Accordion title="Single Responsibility">
Each tool should have one clear purpose and do it well. Avoid creating tools that try to do too many things.
```python
# Good Example
def process_image(image: np.array) -> np.array:
return processed_image
# Avoid
def process_and_save_and_upload(image):
# Too many responsibilities
pass
```
</Accordion>
<Accordion title="Clear Interfaces">
Define explicit input/output types and maintain consistent parameter naming.
```python
def search_tool(
query: str,
max_results: int = 10
) -> List[Dict[str, Any]]:
"""
Search for information with clear parameters
"""
pass
```
</Accordion>
<Accordion title="Documentation">
Always include detailed docstrings and type hints.
```python
def analyze_text(
text: str,
language: str = "en"
) -> Dict[str, float]:
"""
Analyze text sentiment and emotions.
Args:
text: Input text to analyze
language: ISO language code
Returns:
Dict with sentiment scores
"""
pass
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
<br />
<CardGroup cols={1}>
<Card title="Performance Optimization" icon="bolt" iconType="solid">
<AccordionGroup>
<Accordion title="Efficient Processing">
Optimize resource usage and processing time.
```python
# Use generators for large datasets
def process_large_data():
for chunk in data_generator():
yield process_chunk(chunk)
```
</Accordion>
<Accordion title="Resource Management">
Properly handle resource allocation and cleanup.
```python
async with aiohttp.ClientSession() as session:
# Resource automatically managed
await process_data(session)
```
</Accordion>
<Accordion title="Caching">
Implement caching for frequently accessed data.
```python
@cache.memoize(timeout=300)
def expensive_operation(data: str) -> Dict:
return process_expensive(data)
```
</Accordion>
<Accordion title="Async Operations">
Use async/await for I/O-bound operations.
```python
async def fetch_data(urls: List[str]):
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
return await asyncio.gather(*tasks)
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
<br />
<CardGroup cols={1}>
<Card title="Security Best Practices" icon="shield-check" iconType="solid">
<AccordionGroup>
<Accordion title="Input Validation">
Always validate and sanitize inputs to prevent security vulnerabilities.
```python
def process_user_input(data: str) -> str:
if not isinstance(data, str):
raise ValueError("Input must be string")
return sanitize_input(data.strip())
```
</Accordion>
<Accordion title="Rate Limiting">
Implement rate limiting for API calls to prevent abuse.
```python
@rate_limit(calls=100, period=60)
async def api_call():
return await make_request()
```
</Accordion>
<Accordion title="API Key Management">
Securely handle API keys and credentials using environment variables.
```python
# Use environment variables
api_key = os.getenv('API_KEY')
if not api_key:
raise ConfigError("API key not found")
```
</Accordion>
<Accordion title="Error Masking">
Hide sensitive information in error messages to prevent information leakage.
```python
try:
result = process_sensitive_data()
except Exception as e:
# Log detailed error internally
logger.error(f"Detailed error: {str(e)}")
# Return sanitized error to user
raise PublicError("Processing failed")
```
</Accordion>
</AccordionGroup>
</Card>
</CardGroup>
<br />
<Tip>
**Pro Tip**: Start with these practices from the beginning of your project. It's easier to maintain good practices than to retrofit them later.
</Tip>
-28
View File
@@ -1,28 +0,0 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = 'PraisonAI'
copyright = '2024, Mervin Praison'
author = 'Mervin Praison'
release = '7'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx_rtd_theme']
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
-14
View File
@@ -1,14 +0,0 @@
---
title: "Contributing"
description: "Guide for contributing to PraisonAI through GitHub, including forking, cloning, and submitting pull requests"
icon: "code-branch"
---
- Fork on GitHub: Use the "Fork" button on the repository page.
- Clone your fork: `git clone https://github.com/yourusername/praisonAI.git`
- Create a branch: `git checkout -b new-feature`
- Make changes and commit: `git commit -am "Add some feature"`
- Push to your fork: `git push origin new-feature`
- Submit a pull request via GitHub's web interface.
- Await feedback from project maintainers.
-71
View File
@@ -1,71 +0,0 @@
---
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
@@ -1,113 +0,0 @@
---
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>
@@ -1,157 +0,0 @@
---
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.
@@ -1,187 +0,0 @@
---
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
@@ -1,183 +0,0 @@
---
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
@@ -1,167 +0,0 @@
---
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.
@@ -1,171 +0,0 @@
---
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
@@ -1,152 +0,0 @@
---
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
@@ -1,190 +0,0 @@
---
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
@@ -1,274 +0,0 @@
---
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.
@@ -1,172 +0,0 @@
---
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.
@@ -1,275 +0,0 @@
---
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.
@@ -1,218 +0,0 @@
---
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.
@@ -1,193 +0,0 @@
---
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
@@ -1,216 +0,0 @@
---
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.
@@ -1,252 +0,0 @@
---
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.
@@ -1,333 +0,0 @@
---
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.
@@ -1,260 +0,0 @@
---
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.
@@ -1,270 +0,0 @@
---
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
@@ -1,342 +0,0 @@
---
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.

Before

Width:  |  Height:  |  Size: 134 KiB

-35
View File
@@ -1,35 +0,0 @@
---
title: "Deploy"
description: "Guide for deploying PraisonAI to cloud platforms, with detailed instructions for Google Cloud deployment"
icon: "cloud"
---
## Google Cloud
```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}
```
-416
View File
@@ -1,416 +0,0 @@
---
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
@@ -1,223 +0,0 @@
---
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
@@ -1,248 +0,0 @@
---
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}
```
Loaded 100 of 489 files, more files were not shown because too many files have changed in this diff. Show more