Compare commits

...
370 Commits
Author SHA1 Message Date
Mervin Praison 77ab361d64 refactor: reorganize test files and update package versions to 2.2.66 2025-07-16 14:12:45 +01:00
Mervin Praison a276a610a0 Merge pull request #951 from MervinPraison/claude/issue-950-20250716-1207
feat: Enable imports from PraisonAI package for issue #950
2025-07-16 14:08:34 +01:00
github-actions[bot]andMervin Praison e8f4eff173 refactor: Use dynamic approach for praisonaiagents imports
- Replace manual symbol list with dynamic import using
- Use  for automatic maintenance
- Remove manual tracking of imported symbols
- Reduce code from 49 to 17 lines
- Future-proof: automatically inherits new exports from praisonaiagents

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 12:56:29 +00:00
Mervin Praison 464cc128db Merge pull request #953 from MervinPraison/revert-945-claude/issue-940-20250716-0711
Revert "fix: prevent premature termination in Ollama sequential tool execution"
2025-07-16 13:46:12 +01:00
Mervin Praison f44bb7fa39 Revert "fix: prevent premature termination in Ollama sequential tool execution" 2025-07-16 13:46:01 +01:00
Mervin Praison 5b70f4b34d Merge pull request #945 from MervinPraison/claude/issue-940-20250716-0711
fix: prevent premature termination in Ollama sequential tool execution
2025-07-16 13:45:16 +01:00
github-actions[bot]andMervin Praison 5514f17346 fix: Resolve unconditional __all__ list issue causing import errors
- Fixed critical bug where __all__ list included symbols from praisonaiagents
  even when import failed due to missing dependencies
- Implemented dynamic __all__ construction based on successfully imported symbols
- Maintained backward compatibility while fixing the cursor review issue
- Added comprehensive test files to verify fix and backward compatibility

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 12:38:33 +00:00
github-actions[bot]andMervin Praison 8e7323c484 refactor: replace hardcoded patterns with dynamic tool usage detection
- Replace hardcoded acknowledgment_patterns and status_patterns with intelligent context analysis
- Implement _analyze_tool_chain_context() for dynamic tool execution pattern detection
- Add _assess_response_quality() for content-based response evaluation
- Replace iteration_count >= 5 threshold with _should_generate_tool_summary() dynamic logic
- Improve tool chain completion detection with confidence scoring
- Increase safety fallback threshold from 5 to 7 iterations
- Maintain backward compatibility with existing providers

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 12:28:18 +00:00
github-actions[bot]andMervin Praison 658a2397fc feat: Enable imports from PraisonAI package for issue #950
This change allows users to import from the main PraisonAI package instead of
just from praisonaiagents, while maintaining full backward compatibility.

Changes:
- Modified src/praisonai/praisonai/__init__.py to re-export all classes from praisonaiagents
- Added comprehensive __all__ list for proper exports
- Maintained backward compatibility - all existing imports continue to work

New usage patterns now supported:
- from praisonai import Agent, Task, PraisonAIAgents
- from praisonai import Tools, Memory, Knowledge, etc.

Backward compatibility maintained:
- from praisonaiagents import Agent, Task, PraisonAIAgents (still works)

Tests added:
- test_import_conversion.py: Comprehensive test suite
- test_issue_950.py: Specific test for the issue requirements

Resolves #950

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 12:14:45 +00:00
github-actions[bot]andMervin Praison a743f4b68c fix: prevent premature termination in Ollama sequential tool execution
- Added iteration count threshold (>=5) before generating Ollama tool summary
- Prevents premature termination after first tool call in sequential execution
- Maintains infinite loop prevention for truly stuck scenarios
- Applied fix to both sync and async methods in llm.py
- Preserves backward compatibility with other LLM providers

Fixes issue where Ollama would terminate after first tool call instead of
continuing with sequential execution (e.g., get_stock_price -> multiply)

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 07:28:09 +00:00
Mervin Praison 77b7c3b1ce Merge pull request #944 from MervinPraison/claude/fix-ollama-response-overwrite-20250715-2344
fix: prevent Ollama tool summary from being overwritten by empty response
2025-07-16 01:08:51 +01:00
Mervin Praison 48c65a742c Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-16 00:56:06 +01:00
Mervin Praison 35295ad167 refactor: move test files to src/praisonai-agents directory 2025-07-16 00:56:05 +01:00
Mervin Praison 1a6078d7eb Delete test_ollama_response_fix.py 2025-07-16 00:50:14 +01:00
github-actions[bot]andMervin Praison fbd4c53796 fix: prevent Ollama tool summary from being overwritten by empty response
- Add condition to check if final_response_text is already set before overwriting
- Fix applies to both sync (get_response) and async (get_response_async) methods
- Prevents tool summary from being lost when Ollama returns empty response after tool execution
- Maintains backward compatibility for non-Ollama providers
- Resolves issue where agent.start() returns None despite successful tool execution

Fixes the remaining issue from PR #943 where tool summary was generated but overwritten

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 23:48:51 +00:00
Mervin Praison 55e70d521e Merge pull request #942 from MervinPraison/claude/issue-939-20250715-2248
feat: Add 7 comprehensive examples for advanced PraisonAI agent features
2025-07-16 00:47:52 +01:00
github-actions[bot]andMervin Praison d4023c0484 feat: Organize advanced examples into appropriate folders
- Move callback systems to general/
- Move memory examples to memory/
- Move state management to stateful/
- Move hierarchical agents to agents/
- Move guardrails to guardrails/
- Move self-reflection to concepts/

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 23:46:29 +00:00
Mervin Praison d88200e258 Merge pull request #943 from MervinPraison/claude/issue-940-20250715-2304
fix: Resolve Ollama infinite tool call loops by improving response handling
2025-07-16 00:35:29 +01:00
github-actions[bot]andMervin Praison beac0b47a2 refactor: eliminate code duplication and improve test quality in Ollama fix
- Extract duplicated Ollama tool summary logic into _generate_ollama_tool_summary() helper method
- Replace magic number 10 with OLLAMA_MIN_RESPONSE_LENGTH constant
- Fix test_tool_summary_generation() to call production code instead of reimplementing logic
- Add comprehensive test scenarios for different response types and provider types
- Maintain backward compatibility and fix functionality

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 23:26:15 +00:00
github-actions[bot]andClaude 6d6c44e7ca fix: Convert advanced examples to flat format with minimal code
Simplified all 7 advanced examples to follow flat format requirements:
- Removed 20+ custom classes across all examples
- Reduced total lines from 2,829 to 514 (82% reduction)
- Limited to 1-2 agents max per example
- Focused on core functionality demonstration
- Maintained advanced feature examples while making them accessible

Changes per file:
- advanced-callback-systems.py: 404→59 lines, removed 3 classes
- advanced-graph-memory-integration.py: 226→75 lines, reduced to 1 agent
- advanced-memory-search-optimization.py: 568→76 lines, removed 4 classes
- advanced-state-management-patterns.py: 437→80 lines, removed 3 classes
- autoagents-hierarchical-generation.py: 158→73 lines, removed custom class
- production-guardrails-patterns.py: 480→65 lines, removed 5 classes
- self-reflection-optimization-patterns.py: 556→46 lines, removed 4 classes

All examples now follow the established flat format pattern with simple,
direct agent/task creation and minimal code complexity.

🤖 Generated with Claude Code

Co-Authored-By: Claude <[email protected]>
2025-07-15 23:22:16 +00:00
Mervin Praison 1cd838f691 chore: bump praisonai version to 2.2.65 and add autogen-v4 dependencies 2025-07-16 00:12:42 +01:00
Mervin Praison 319944e012 Merge pull request #941 from MervinPraison/claude/issue-938-20250715-2246
fix: Ensure agent names are valid Python identifiers for AutoGen v0.4
2025-07-16 00:10:52 +01:00
github-actions[bot]andMervin Praison b53162aa9e fix: Improve sanitization to preserve double underscores
- Fixed aggressive underscore collapsing that broke dunder names like __init__
- Now only collapses 5+ consecutive underscores instead of any consecutive underscores
- Preserves trailing underscores in double underscore patterns (__name__)
- Handles edge case where purely invalid characters become single underscore
- All 15 test cases now pass including magic method names
- Maintains backward compatibility for AutoGen v0.2, CrewAI, PraisonAI

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 23:09:41 +00:00
github-actions[bot]andClaude 7d42e31e0a feat: Add comprehensive examples for advanced PraisonAI agent features
Added 7 new example files demonstrating advanced functionality:
- autoagents-hierarchical-generation.py: Hierarchical agent generation patterns
- advanced-graph-memory-integration.py: Graph-based memory systems
- advanced-callback-systems.py: Custom callback implementations
- production-guardrails-patterns.py: Production safety and guardrails
- advanced-state-management-patterns.py: Complex state handling
- advanced-memory-search-optimization.py: Memory search optimizations
- self-reflection-optimization-patterns.py: Self-improvement patterns

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

Co-Authored-By: Claude <[email protected]>
2025-07-15 23:09:07 +00:00
github-actions[bot]andMervin Praison 9c96a838a8 fix: Resolve Ollama infinite tool call loops by improving response handling
- Add special handling for Ollama models in both sync and async tool execution loops
- When Ollama returns empty/minimal response after tool execution, generate summary from tool results
- Prevents infinite loops while maintaining functionality for other LLM providers
- Add comprehensive test suite to validate fix and ensure backward compatibility
- Fixes issue where Ollama models would repeat tool calls indefinitely

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 23:08:01 +00:00
github-actions[bot]andMervin Praison 52c249fde0 fix: Ensure agent names are valid Python identifiers for AutoGen v0.4
AutoGen v0.4 requires agent names to be valid Python identifiers,
but role names like ''Narrative Designer'' contain spaces which are invalid.

- Added sanitize_agent_name_for_autogen_v4() function to convert any
  string to a valid Python identifier
- Applied sanitization only in AutoGen v0.4 code path for backward compatibility
- AutoGen v0.2 and other frameworks remain unchanged
- Handles spaces, special characters, Python keywords, and edge cases

Resolves issue where ''Narrative Designer'' role causes error:
''The agent name must be a valid Python identifier''

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 22:51:54 +00:00
Mervin Praison 7607df753f Merge pull request #937 from MervinPraison/claude/issue-934-20250715_165720
fix: Replace deprecated Pydantic .dict() with .model_dump() in example files
2025-07-15 22:04:30 +01:00
Mervin Praison 8fa181bc55 Merge pull request #936 from MervinPraison/claude/issue-935-20250715_170032
feat: Add AutoGen v0.4 support with backward compatibility
2025-07-15 22:03:55 +01:00
github-actions[bot]andMervin Praison ccbf0ebebb fix: Ensure backward compatibility for Pydantic v1/v2 in hasattr checks
- Fix inconsistent hasattr checks in ZeroScript_AI_TestExecutor.ipynb
- Update fix_notebook.py to handle both method call and hasattr replacement
- Add comprehensive backward compatibility test suite
- Ensure Pydantic v1 models fallback to str() when model_dump() unavailable

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 17:19:41 +00:00
Mervin Praison d3f0c217ca feat: update default model from gpt-4o to gpt-4o-mini and bump version to 2.2.64 2025-07-15 18:09:57 +01:00
github-actions[bot]andMervin Praison 6995a446e1 feat: Add AutoGen v0.4 support with backward compatibility
- Add optional dependency ''autogen-v4'' with autogen-agentchat>=0.4.0, autogen-ext[openai]>=0.4.0, autogen-core>=0.4.0
- Implement async _run_autogen_v4() method with RoundRobinGroupChat for parallel multi-agent execution
- Add AUTOGEN_VERSION environment variable for version control (auto/v0.2/v0.4)
- Maintain full backward compatibility with existing v0.2 implementation
- Auto-detect available versions with intelligent fallback logic
- Simplify tool integration for v0.4 (single AssistantAgent vs dual-agent pattern)
- Add proper termination conditions and error handling for v0.4

Resolves #935

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 17:08:28 +00:00
github-actions[bot]andMervin Praison 72c70ce050 fix: Replace deprecated Pydantic .dict() with .model_dump() in example files
- Fixed examples/python/api/secondary-market-research-api.py:443
- Fixed examples/python/concepts/reasoning-extraction.py:34
- Fixed ZeroScript_AI_TestExecutor.ipynb notebook
- Added test script to verify fixes work correctly
- Maintains backward compatibility with Pydantic v2
- Resolves PydanticDeprecatedSince20 warnings

Resolves #934

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 17:07:16 +00:00
Mervin Praison 6a13d2b971 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-15 17:57:12 +01:00
Mervin PraisonandMervin Praison fdc747a9c9 fix: Enhance session memory persistence and improve chat history management
- Improved session memory persistence for agent chat history
- Optimised methods for saving and restoring agent chat histories
- Ensured compatibility with existing code while enhancing functionality
- Addressed issues related to chat history loss during session transitions

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 17:57:11 +01:00
Mervin Praison f381b93ae9 Merge pull request #933 from MervinPraison/claude/issue-931-20250715_160543
feat: add comprehensive examples for missing PraisonAI features
2025-07-15 17:52:35 +01:00
Mervin Praison 9c44945123 chore: update numpy and scipy version constraints in dependency files 2025-07-15 17:50:01 +01:00
Mervin Praison a19748902d Merge pull request #932 from MervinPraison/claude/issue-930-20250715_141043
fix: Add session memory persistence for agent chat history
2025-07-15 17:48:02 +01:00
Mervin Praison fa1061a7aa Rename SESSION_MEMORY_FIX_REVIEW.md to examples/python/session/SESSION_MEMORY_FIX_REVIEW.md 2025-07-15 17:47:26 +01:00
github-actions[bot]andClaude 775d97671f fix: Fix session memory persistence by disabling embeddings and correcting search queries
- Fixed session memory persistence issue where state was not being restored correctly
- Disabled embeddings in default memory config to avoid OpenAI API key requirement
- Changed search queries from metadata-based to content-based for SQLite compatibility
- Fixed search query from "type:session_state" to "Session state:" to match stored content
- Fixed agent chat history search from "type:agent_chat_history" to "Agent chat history for"
- Session state persistence now works correctly across session save/restore cycles
- Agent chat history persistence now works correctly across session save/restore cycles
- Maintains backward compatibility with existing code
- Fixes #930

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

Co-authored-by: Claude <[email protected]>
2025-07-15 16:31:10 +00:00
github-actions[bot]andMervin Praison 6c4f4d981d fix: Add missing increment_state method and improve chat history persistence
- Fix f-string issues on lines 275, 300 (remove unnecessary f prefixes)
- Fix chat history initialization to always set agent.chat_history even if empty
- Fix critical data loss bug in _save_agent_chat_histories method
- Now prioritizes live agent history but falls back to restored history
- Prevents chat history loss when agents aren''t re-instantiated after restore

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 16:19:19 +00:00
github-actions[bot]andMervin Praison 72395efd32 feat: add comprehensive examples for missing PraisonAI features
- Add hierarchical process orchestration examples
- Add RouterAgent cost optimization patterns
- Add advanced knowledge management with semantic chunking
- Add comprehensive guardrails with validation workflows
- Add advanced task management with conditional execution
- Add session management with persistence and recovery
- Add production telemetry with OpenTelemetry integration
- Add advanced workflow patterns with decision trees

Resolves #931: Create missing examples where features exist

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 16:16:49 +00:00
efa29de346 fix: Add missing increment_state method and improve chat history persistence
- Add increment_state method (lines 356-359) for numeric state management
- Fix empty chat history save condition to track agent existence properly
- Improve robustness by checking agent is not None before accessing chat_history
- Enhance memory persistence by saving even empty chat histories to track agent state

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

Co-Authored-By: Mervin Praison <[email protected]>
Co-Authored-By: Claude <[email protected]>
2025-07-15 16:13:36 +00:00
github-actions[bot]andMervin Praison 75462584b3 fix: Add session memory persistence for agent chat history
- Agent chat history now persists across session save/restore cycles
- Added _agents dictionary to track agent instances and chat histories
- Enhanced Agent() method to restore chat history in restored sessions
- Added helper methods for saving/restoring agent chat histories
- Modified save_state() to automatically save agent chat histories
- Modified restore_state() to automatically restore agent chat histories
- Backward compatible - existing code continues to work unchanged
- Fixes #930

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 14:31:24 +00:00
Mervin Praison d352adbdac chore: bump praisonai to v2.2.62 and praisonaiagents to v0.0.135 across all files 2025-07-15 15:11:32 +01:00
Mervin Praison 68664fdd55 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-15 15:04:19 +01:00
Mervin Praison bcda52cc44 chore: bump praisonai version from 2.2.60 to 2.2.61 across Docker and deployment files 2025-07-15 15:04:17 +01:00
Mervin Praison 4888dfb993 Merge pull request #928 from MervinPraison/claude/issue-926-20250715_112808
refactor: inline Gemini internal tools detection logic
2025-07-15 14:36:45 +01:00
github-actions[bot]andMervin Praison c5a3fc89cc refactor: inline Gemini internal tools detection logic
- Remove import dependency on is_gemini_internal_tool helper function
- Inline logic directly in llm.py and openai_client.py
- Maintain identical functionality and debug logging
- Handle valid tools: googleSearch, urlContext, codeExecution
- Properly skip unknown tools with appropriate logging
- Preserve backward compatibility

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 11:33:22 +00:00
Mervin Praison ca33559d4c Merge pull request #922 from MervinPraison/claude/issue-918-20250715_061404
fix: resolve Ollama sequential tool calling argument mixing issue
2025-07-15 12:24:28 +01:00
Mervin Praison b02449dfdb chore: bump praisonai to v2.2.60 and praisonaiagents to v0.0.134 2025-07-15 09:55:35 +01:00
Mervin Praison c4c0c1c146 Merge pull request #923 from MervinPraison/claude/issue-919-20250715_061529
fix: Add support for Gemini internal tools in tool formatting
2025-07-15 09:52:47 +01:00
Mervin Praison aa2d7e4c31 Merge pull request #924 from Dhivya-Bharathy/kimi2-agents-final
Add Kimi2_Intelligent_Agents: 10 specialized AI agents
2025-07-15 09:51:35 +01:00
Dhivya-Bharathy b339c5b3aa Add Kimi2_Intelligent_Agents: 10 specialized AI agents 2025-07-15 12:57:48 +05:30
github-actions[bot]andMervin Praison e535f98f4e refactor: optimize Gemini tools handling with shared utilities
- Extract GEMINI_INTERNAL_TOOLS constant to eliminate loop recreation
- Create shared is_gemini_internal_tool() utility function
- Remove code duplication between llm.py and openai_client.py
- Improve maintainability and performance based on reviewer feedback

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 06:40:42 +00:00
Mervin Praison bc349ad09f feat: restrict review comments to PRs only and update Claude bot instructions 2025-07-15 07:38:32 +01:00
Mervin Praison 5b8da1180e chore: clarify Claude review instructions to specify branch context 2025-07-15 07:29:21 +01:00
github-actions[bot]andMervin Praison 8f6d8f0a48 fix: Add support for Gemini internal tools in tool formatting
- Add explicit handling for Gemini internal tools (googleSearch, urlContext, codeExecution)
- Update docstrings to document new capability
- Resolves issue where Gemini internal tools were skipped with ''unsupported type'' error
- Maintains backward compatibility with existing tool formats

Closes #919

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 06:23:32 +00:00
github-actions[bot]andMervin Praison 3730b4d094 fix: resolve Ollama sequential tool calling argument mixing issue
- Add parameter validation method _validate_and_filter_ollama_arguments()
- Filter invalid parameters before tool execution for Ollama providers
- Prevent functions from receiving unexpected keyword arguments
- Add comprehensive test suite for validation functionality
- Maintain backward compatibility and graceful error handling

Fixes #918: Ollama sequential failing 3

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-15 06:21:08 +00:00
Mervin Praison 7f3810ed98 chore: add gh tool permission and update claude review comment with PR creation request 2025-07-15 07:19:48 +01:00
Mervin Praison c84a59ab4d feat: implement PostHog event tracking in telemetry module 2025-07-15 07:13:38 +01:00
Mervin Praison c6a6bfa827 Merge pull request #917 from MervinPraison/claude/issue-867-20250714_201010
feat: Add Gemini internal tools examples
2025-07-14 22:22:48 +01:00
github-actions[bot]andMervin Praison a604cd9584 fix: Replace eval() with safe AST-based expression evaluator and remove unused imports
- Replace insecure eval() usage with ast-based safe expression evaluator in README and combined examples
- Remove unused os imports from all Python example files
- Update comments to show import os inline for API key setup
- Addresses security vulnerabilities identified in code review

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 20:38:04 +00:00
github-actions[bot]andMervin Praison cb043da19c feat: Add Gemini internal tools examples
- Add Google Search tool example (gemini-google-search.py)
- Add URL Context tool example (gemini-url-context.py)
- Add Code Execution tool example (gemini-code-execution.py)
- Add combined tools example (gemini-internal-tools-combined.py)
- Add comprehensive documentation (README_GEMINI_INTERNAL_TOOLS.md)

These examples demonstrate how to use Gemini''s built-in internal tools
through PraisonAI''s existing tool system without any code changes.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 20:17:41 +00:00
Mervin Praison 7b41444aad refactor: move test files into src/praisonai-agents directory for better organization 2025-07-14 21:13:34 +01:00
Mervin Praison 7c8b77063f chore: bump praisonai to v2.2.58 and praisonaiagents to v0.0.132 across all files 2025-07-14 21:12:31 +01:00
Mervin Praison 59eb8d6356 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-14 21:07:47 +01:00
Mervin Praison 89bddc31c6 feat: add allowed tools configuration for Claude GitHub action workflow 2025-07-14 21:07:45 +01:00
Mervin Praison e6e908298b Merge pull request #916 from MervinPraison/claude/issue-878-20250714_190400
Fix: resolve duplicate callback execution in LLM interaction handling
2025-07-14 20:53:39 +01:00
Mervin Praison 2b3509c1d1 Delete reproduce_issue_878.py 2025-07-14 20:52:36 +01:00
Mervin Praison 6e8029055a Delete ISSUE_878_REPRODUCTION_GUIDE.md 2025-07-14 20:52:15 +01:00
Mervin Praison d2c9e8825a Merge pull request #915 from MervinPraison/claude/issue-911-20250714_190025
fix: add execute and aexecute methods to Agent class
2025-07-14 20:44:41 +01:00
Mervin Praison cd9816e218 Merge pull request #914 from MervinPraison/claude/issue-901-20250714_143624
Issue #901: Fix self-reflection with tools
2025-07-14 20:43:29 +01:00
Mervin Praison d400149075 chore: update claude review request message to include follow-up action 2025-07-14 20:42:15 +01:00
Mervin Praison 73b08e6b76 feat: add PR creation permissions and request in auto-issue workflow 2025-07-14 20:32:59 +01:00
github-actions[bot]andClaude 19c3a1f6a7 fix: address code review issues in test files
- Add missing sys.path setup to test_self_reflection_with_tools_verification.py
- Remove unnecessary f-string prefixes from print statements
- Add missing newlines at end of files for PEP 8 compliance

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

Co-Authored-By: Claude <[email protected]>
2025-07-14 19:24:12 +00:00
71a7968318 fix: resolve duplicate callback execution in LLM interaction handling
- Fixed duplicate callback issue in src/praisonai-agents/praisonaiagents/llm/llm.py where callbacks were executed multiple times
- Added callback_executed flag to track and prevent duplicate callback invocations
- Ensured callbacks are only executed once per interaction, either through display_interaction or direct execute_sync_callback calls
- Improved generation_time consistency by calculating once and reusing the value
- Added comprehensive test files and reproduction scripts to verify the fix
- Added ISSUE_878_REPRODUCTION_GUIDE.md documenting the issue and solution

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

Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Mervin Praison <[email protected]>
2025-07-14 19:15:39 +00:00
Mervin Praison 1b258229c1 Merge pull request #913 from MervinPraison/claude/issue-906-20250714_175631
fix: Add callback execution to synchronous display functions
2025-07-14 20:12:26 +01:00
github-actions[bot]andMervin Praison d0e09f51f3 fix: Ensure consistent callback execution across all display functions
- Fix async functions to use execute_callback() instead of direct async_display_callbacks access
- Add missing execute_sync_callback() calls to sync display functions (instruction, tool_call, error, generating)
- Ensures both sync and async callbacks are triggered consistently for all display types
- Maintains backward compatibility through existing parameter filtering

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 19:04:19 +00:00
github-actions[bot]andMervin Praison 5adc862ead fix: add execute and aexecute methods to Agent class for backward compatibility
Resolves AttributeError: type object ''Agent'' has no attribute ''execute''

- Added execute(task, context=None) method that delegates to chat()
- Added aexecute(task, context=None) method that delegates to achat()
- Both methods handle task objects with description attribute or string inputs
- Maintains complete backward compatibility with existing code
- Fixes issue #911

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 19:03:24 +00:00
Mervin Praison 856db54334 Merge pull request #912 from MervinPraison/claude/issue-904-20250714_171858
Fix issue #904: Loop task callback inheritance and enhanced metadata support
2025-07-14 19:58:26 +01:00
github-actions[bot]andMervin Praison f94e5bb3d6 fix: Add callback execution to synchronous display functions
Fixes the duplicate callback issue by:

- Adding execute_sync_callback calls to display_interaction and display_self_reflection
- Fixing test to patch the correct function location
- Ensuring backward compatibility by maintaining existing function signatures
- Adding comprehensive tests for callback system verification

This ensures that callbacks are called exactly once per LLM response while maintaining full backward compatibility.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 18:06:08 +00:00
Mervin Praison 1cece603ec Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-14 18:59:38 +01:00
Mervin Praison 9e2bbb9bbb refactor: update tool imports in test files from calculator to evaluate for improved clarity and consistency 2025-07-14 18:59:36 +01:00
Mervin Praison 35b4cff7f7 Merge pull request #910 from MervinPraison/claude/issue-905-20250714_163222
fix: resolve litellm.BadRequestError with unrecognized output_json/output_pydantic parameters
2025-07-14 18:44:18 +01:00
Mervin Praison a094d1ff30 Merge pull request #908 from MervinPraison/claude/issue-907-20250714_165230
fix: add string LLM support to LLMGuardrail for Gemini models
2025-07-14 18:43:11 +01:00
Mervin Praison 000bdf3418 refactor: move test files to src/praisonai-agents and bump version to 2.2.57 2025-07-14 18:40:18 +01:00
github-actions[bot]andMervin Praison 826ff56fc5 refactor: simplify LLMGuardrail string handling and consolidate imports
- Remove redundant if/else logic in string LLM initialization
- Consolidate duplicate LLM imports using _get_llm_class helper
- Maintain all functionality while improving code clarity
- Addresses code review feedback for cleaner, more maintainable code

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 17:31:52 +00:00
github-actions[bot]andClaude 4bd0195d5d Fix issue #904: Loop task callback inheritance and enhanced metadata support
- Add callback inheritance in all 6 locations where loop tasks create subtasks in process.py
- Implement enhanced callback metadata support in task.py with run_context tracking
- Ensure backward compatibility with existing callback implementations
- Maintain proper callback chain for nested loop executions

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

Co-Authored-By: Claude <[email protected]>
2025-07-14 17:28:28 +00:00
Mervin Praison 812abec2eb Merge pull request #897 from MervinPraison/claude/issue-896-20250714_104106
feat: enhance callbacks with agent and task context (fixes #896)
2025-07-14 18:27:25 +01:00
github-actions[bot]andMervin Praison e58f6deb4b fix: resolve critical runtime issues in callback enhancement
- Fix undefined variables in llm.py response() and aresponse() methods
  by adding missing parameters to method signatures
- Fix backward compatibility by adding signature checking to callbacks
  in display_interaction(), execute_callback(), and execute_sync_callback()
- Ensure consistent parameter propagation in agent.py get_response calls
- Legacy callbacks now work without TypeError, new callbacks get full context

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 17:21:11 +00:00
Mervin Praison f23680c121 Merge pull request #903 from MervinPraison/claude/issue-899-20250714_122107
fix: exclude response_format parameter for Gemini image models
2025-07-14 18:01:38 +01:00
Mervin Praison e569400260 Merge pull request #902 from MervinPraison/claude/issue-901-20250714_140528
Issue #901: Changes from Claude
2025-07-14 17:57:58 +01:00
github-actions[bot]andMervin Praison 75c4d8432c fix: add string LLM support to LLMGuardrail for Gemini models
- Add _initialize_llm method to convert string identifiers to LLM instances
- Update __init__ to handle string LLM identifiers like ''gemini/gemini-2.5-flash-lite-preview-06-17''
- Maintain backward compatibility with existing LLM instances, dict configs, and None values
- Use same LLM initialization logic as Agent class for consistency
- Fixes issue #907 where LLMGuardrail failed with ''Unsupported LLM type'' error

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 16:57:24 +00:00
Mervin Praison 6249d14d3f Merge pull request #895 from MervinPraison/claude/issue-893-20250714_084251
fix: resolve Ollama sequential tool calling redundant execution issue
2025-07-14 17:55:05 +01:00
github-actions[bot]andMervin Praison 32537a227e fix: resolve litellm.BadRequestError with unrecognized output_json/output_pydantic parameters
- Fixed bug in _build_completion_params method where output_json and output_pydantic
  parameters were conditionally removed only when not None
- These custom parameters are now always removed before LiteLLM calls to prevent
  "Unrecognized request arguments supplied" errors
- Maintains backward compatibility and preserves all existing functionality
- Addresses issue #905

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 16:43:03 +00:00
Mervin Praison f83ffcdafe Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-14 17:27:52 +01:00
Mervin Praison 519aebd271 chore: bump praisonai to v2.2.56 and praisonaiagents to v0.0.130 across all files 2025-07-14 17:27:51 +01:00
github-actions[bot]andMervin Praison fb4ecf1893 fix: Address reviewer feedback on self-reflection test files
- Move test files from src/praisonai-agents/ to tests/ directory per repository guidelines
- Replace print statements and return values with proper assert statements
- Fix f-string issues without placeholders
- Add comprehensive exception handling for test failures
- Create improved test structure following repository patterns

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 14:55:27 +00:00
github-actions[bot]andMervin Praison 5a4cbf8aeb fix: improve robustness of Gemini model detection in ImageAgent
- Use self.llm_model property instead of self.llm for more robust model name resolution
- Handles all LLM configuration types (strings, dicts, custom instances, base_url configs)
- Fixes potential AttributeError when self.llm is not set
- Maintains backward compatibility for all existing configurations

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 14:54:16 +00:00
github-actions[bot]andMervin Praison 885a73f697 fix: add intelligent final answer detection to async method
Apply the same intelligent final answer detection logic that was added to the sync method (get_response) to the async method (get_response_async). This ensures consistent behavior between sync and async methods when detecting substantive final answers alongside tool calls.

The fix prevents redundant tool execution loops in async contexts by checking if the LLM provides substantive content (>10 characters) after tool execution, breaking the loop when appropriate.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 14:48:03 +00:00
Mervin Praison 9336f15e67 Merge pull request #900 from Dhivya-Bharathy/add-Notion_Workspace_Assistant
feat: Add Notion_Workspace_Assistant notebook
2025-07-14 15:47:31 +01:00
Mervin Praison 6d55cfa87e Merge branch 'main' into claude/issue-896-20250714_104106 2025-07-14 15:46:44 +01:00
Mervin Praison 0b431b1fe1 Merge pull request #894 from MervinPraison/claude/issue-876-20250714_062122
fix: handle single function as tools parameter to prevent iteration error
2025-07-14 15:43:51 +01:00
github-actions[bot]andMervin Praison e252f86ac9 fix: self-reflection now works with tools
- Fixed issue where self-reflection failed when tools were present
- Added tools=formatted_tools parameter to reflection regeneration calls
- Ensures tools remain available throughout the reflection process
- Maintains backward compatibility with existing code
- Resolves issue #901

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 14:43:12 +00:00
Mervin Praison ed395de6f3 Merge pull request #898 from Dhivya-Bharathy/add-Natural_Language_Codebase
Add Natural_Language_Codebase notebook
2025-07-14 15:42:26 +01:00
Mervin Praison 633469d12e Merge pull request #886 from MervinPraison/claude/issue-877-20250714_005101
fix: ensure callbacks work regardless of verbose setting
2025-07-14 15:41:40 +01:00
Mervin Praison c5c57dff26 Merge pull request #891 from MervinPraison/claude/issue-870-20250714_062116
feat: add support for Gemini embedding models
2025-07-14 15:40:47 +01:00
Mervin Praison 573b9efcc1 Rename docs/gemini-embeddings.md to examples/python/memory/gemini-embeddings.md 2025-07-14 15:40:21 +01:00
Mervin Praison dc4e51ac81 Merge pull request #883 from MervinPraison/claude/issue-872-20250714_005257
fix: enable true parallel execution for async tasks in sequential mode
2025-07-14 15:38:00 +01:00
Mervin Praison 08e211c693 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-14 15:33:32 +01:00
Mervin Praison abd8021925 chore: increase GitHub action comment delay from 20s to 30s 2025-07-14 15:33:32 +01:00
Mervin Praison 8a6c4eec7f Rename examples/python/tools/searxng-search.py to examples/python/tools/searxng/searxng-search.py 2025-07-14 15:31:47 +01:00
Mervin Praison 4e77a6a019 Rename examples/python/tools/trafilatura_example.py to examples/python/tools/trafilatura/trafilatura_example.py 2025-07-14 15:31:03 +01:00
Mervin Praison 41e33c09e0 Rename examples/python/tools/custom_trafilatura_tools.py to examples/python/tools/trafilatura/custom_trafilatura_tools.py 2025-07-14 15:30:54 +01:00
Mervin Praison 96f00e2172 Merge pull request #881 from MervinPraison/claude/issue-869-20250713_205041
feat: integrate Trafilatura for high-quality URL content extraction
2025-07-14 15:29:39 +01:00
github-actions[bot]andMervin Praison e858cebed9 fix: Enable self-reflection with tools in LLM class
- Fixed issue where self-reflection was not working when tools were present
- Added tools=formatted_tools parameter to completion calls during reflection regeneration
- Self-reflection now maintains tool access throughout the reflection process
- Backward compatibility maintained, no existing features removed
- Resolves issue #901

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 14:17:28 +00:00
Dhivya-Bharathy cca79bd9fc Add Notion_Workspace_Assistant notebook 2025-07-14 12:56:32 +00:00
github-actions[bot]andMervin Praison 4ffbc1b52a fix: exclude response_format parameter for Gemini image models
- Add detection logic to identify Gemini models (case-insensitive)
- Exclude response_format parameter for Gemini models to prevent litellm.UnsupportedParamsError
- Maintain backward compatibility for non-Gemini models
- Fixes #899

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 12:24:35 +00:00
DhivyaBharathy b948151a14 Update Natural_Language_Codebase.ipynb 2025-07-14 17:51:41 +05:30
Dhivya-Bharathy 11eee70d9a Add Natural_Language_Codebase notebook 2025-07-14 12:18:39 +00:00
github-actions[bot]andClaude da6a2c1c04 fix: improve tools parameter backward compatibility handling
Refactor tools parameter initialization to better handle falsy values while
maintaining single function support. Changed from explicit None check to
using ''tools or []'' pattern, which properly handles all falsy values
(None, False, 0, "", etc.) without breaking existing functionality.

This resolves backward compatibility regression where falsy values other
than None were not handled correctly in the tools parameter.

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

Co-Authored-By: Claude <[email protected]>
2025-07-14 11:59:51 +00:00
Mervin Praison 731268df5c Merge branch 'main' into claude/issue-877-20250714_005101 2025-07-14 12:55:28 +01:00
github-actions[bot]andMervin Praison d60021cb40 refactor: move Trafilatura from core to custom tool example
- Remove Trafilatura from core praisonaiagents package
- Create custom tool implementation in examples/python/tools/
- Update example to demonstrate custom tool usage with agents
- Remove dependencies from pyproject.toml
- Remove from tools __init__.py and README.md
- Keep all functionality as standalone custom tool

This change follows the request to not integrate into core package
but provide as custom tool example instead.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 11:55:10 +00:00
Mervin Praison 75894f26c1 Merge pull request #884 from MervinPraison/claude/issue-874-20250714_005622
fix: prevent infinite loop in parallel task execution
2025-07-14 12:52:35 +01:00
Mervin Praison c53e09480a Rename test_async_sequential.py to src/praisonai-agents/test_async_sequential.py 2025-07-14 12:51:46 +01:00
2ef506fa8a feat: enhance callbacks with agent and task context (fixes #896)
- Add agent_name, agent_role, agent_tools, task_name, task_description, task_id to callbacks
- Update display_interaction() and adisplay_interaction() to accept new parameters
- Enhance LLM.get_response() to accept and pass task context
- Modify Agent.chat() to accept task parameters
- Update task execution in agents.py to pass task information
- Maintain backward compatibility with existing callbacks
- Add test scripts to verify functionality

Co-authored-by: Mervin Praison <[email protected]>

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

Co-Authored-By: Claude <[email protected]>
2025-07-14 10:53:46 +00:00
Mervin Praison 7ce783e59b Merge branch 'main' into claude/issue-893-20250714_084251 2025-07-14 11:11:05 +01:00
Mervin Praison 95ffd0c53f chore: bump PraisonAI to 2.2.55 and PraisonAI Agents to 0.0.129 across all files 2025-07-14 11:09:35 +01:00
Mervin Praison e1c90bf569 Merge pull request #880 from MervinPraison/claude/issue-866-20250713_204435
feat: Add multi-provider/multi-model support with intelligent routing
2025-07-14 11:07:02 +01:00
Mervin Praison 5fbd8aa783 Merge pull request #892 from MervinPraison/claude/pr-879-20250714_063758
fix: Improve Ollama sequential tool calling handling
2025-07-14 11:02:12 +01:00
381c86de79 fix: resolve callback duplication and validation timing issues
- Add callback_executed tracking in llm.py to prevent duplicate callbacks
- Fix validation timing in agent.py for output_json/output_pydantic flows
- Ensure guardrail validation runs even for JSON outputs
- Improve interaction display logic to avoid redundant callbacks

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

Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Mervin Praison <[email protected]>
2025-07-14 08:52:55 +00:00
github-actions[bot]andClaude 35250e429e fix: clean up redundant conditionals and improve tool execution logic in llm.py
- Remove redundant conditional expressions that were causing unnecessary repetition
- Add intelligent final answer detection after tool execution
- Prevent unnecessary tool execution loops when LLM provides substantive response

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

Co-Authored-By: Claude <[email protected]>
2025-07-14 08:51:02 +00:00
github-actions[bot]andClaude 3027937057 fix: prevent event loop blocking and refactor async task handling
- Replace deprecated asyncio.get_event_loop() with asyncio.get_running_loop()
- Fix event loop blocking issues in API and MCP server implementations
- Improve async handling consistency across the codebase

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

Co-Authored-By: Claude <[email protected]>
2025-07-14 08:50:15 +00:00
github-actions[bot]andMervin Praison d79443868f refactor: Rename MultiModelAgent to RouterAgent for better clarity
- Renamed MultiModelAgent class to RouterAgent throughout codebase
- Updated multi_model_agent.py -> router_agent.py
- Updated all imports, exports, and references in:
  - src/praisonai-agents/praisonaiagents/agent/__init__.py
  - examples/python/agents/multi-provider-agent.py
  - examples/python/agents/MULTI_PROVIDER_README.md
  - src/praisonai-agents/test_multi_provider.py
- RouterAgent better reflects the primary purpose of intelligent model routing
- Maintains all existing functionality and backward compatibility

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 08:50:14 +00:00
github-actions[bot]andMervin Praison 6705e753e8 fix: Remove hardcoded regex logic from Ollama tool calling
- Remove explicitly prohibited hardcoded regex patterns
- Move import re to top of file (PEP 8 compliance)
- Extract duplicated message-building logic into helper method
- Define prompt constants at class level for maintainability
- Simplify tool result formatting without numeric extraction
- Maintain backward compatibility and existing functionality

Fixes code quality issues identified by automated review tools
while ensuring compliance with explicit PR requirements.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 08:49:03 +00:00
Mervin Praison b4d1532512 ci: prevent bot accounts from triggering Claude workflow action 2025-07-14 08:51:51 +01:00
Mervin Praison 4b5d3b2eda ci: remove max_turns limit from Claude code review workflow 2025-07-14 08:50:09 +01:00
Mervin Praison a1d4f3ee43 feat: add repository checkout step with fetch history in Claude workflow 2025-07-14 08:23:09 +01:00
Mervin Praison b5e930ff2e Merge pull request #889 from MervinPraison/claude/issue-873-20250714_005616
fix: use LLM abstraction instead of hardcoded OpenAI in hierarchical process
2025-07-14 08:13:08 +01:00
Mervin Praison 1a6a14f8f2 Merge pull request #887 from MervinPraison/claude/issue-878-20250714_005448
fix: prevent duplicate callback invocations in LLM response generation
2025-07-14 08:11:52 +01:00
Mervin Praison ca69de4c6a Merge pull request #885 from MervinPraison/claude/issue-875-20250714_005802
fix: Support GuardrailResult return type in guardrail functions (#875)
2025-07-14 08:09:05 +01:00
Mervin Praison 9b3d36e6d7 ci: remove redundant repository checkout step from Claude workflow 2025-07-14 08:07:07 +01:00
Mervin Praison a9359a0785 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-14 08:05:10 +01:00
Mervin Praison 4cb016c3ca feat: add Gemini structured output agent and enhance Claude workflow checkout 2025-07-14 08:05:08 +01:00
Mervin Praison d2e4776884 Merge pull request #888 from MervinPraison/claude/issue-871-20250714_005124
feat: Add Gemini structured output support
2025-07-14 07:52:18 +01:00
claude[bot]andMervin Praison 193b82aeba fix: Improve Ollama sequential tool calling handling
- Extract numeric values from tool results for better clarity
- Add explicit prompting for final answers after tool execution
- Handle empty initial responses from Ollama with retry logic
- Fix duplicate strip calls in response handling

This improves Ollama's ability to:
1. Understand numeric values from tool results
2. Generate proper final answers instead of returning None
3. Avoid getting stuck in infinite loops

Fixes the issue where Ollama was unable to properly chain tool calls
for sequential operations like getting a stock price and multiplying it.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:42:14 +00:00
claude[bot]andMervin Praison 029de283c4 refactor: extract duplicate workflow completion logic into helper method
- Created _check_all_tasks_completed() helper method to eliminate code duplication
- Both async and sync workflow methods now use the same completion check logic
- No functional changes, pure refactoring for better maintainability

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:40:00 +00:00
Mervin Praison 26376a77af Merge pull request #890 from Dhivya-Bharathy/grok4-agents-batch-upload
feat: Add 10 Grok4 Intelligent Agent Examples
2025-07-14 07:31:17 +01:00
claude[bot]andMervin Praison 7cb580bb12 fix: handle single function as tools parameter to prevent iteration error
- Fix LLM._log_llm_config to properly check if tools is a list/tuple before iterating
- Fix Agent.__init__ to wrap single callable tools in a list automatically
- Resolves "'function' object is not iterable" error when using LLMGuardrail
- Maintains full backward compatibility

Fixes #876

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:30:54 +00:00
claude[bot]andMervin Praison 06b458cc54 test: add test script for async task parallel execution
- Tests that async tasks run in parallel in sequential mode
- Verifies sync tasks wait for async tasks to complete
- Measures execution times to confirm parallel execution
- Helps validate the async task execution fix

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:28:30 +00:00
claude[bot]andMervin Praison e29c2fbe90 fix: prevent event loop blocking and refactor async task handling
- Use run_in_executor for sync tasks in both sequential and hierarchical processes
- Refactor duplicated async task gathering logic into flush_async_tasks helper
- Update to asyncio.get_running_loop() from deprecated get_event_loop()
- Maintains backward compatibility while fixing performance issues

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:28:21 +00:00
claude[bot]andMervin Praison 76032be618 feat: add support for Gemini embedding models
- Extract embedding model from embedder configuration in Memory class
- Replace hardcoded "text-embedding-3-small" with configurable model
- Support any embedding model available through LiteLLM
- Maintain backward compatibility (defaults to OpenAI model)
- Add documentation and examples for Gemini embeddings
- Update memory_example.py to show configuration options

Fixes #870

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:27:18 +00:00
claude[bot]andMervin Praison 80f5ba940b fix: address code review issues for Trafilatura integration
- Fix asyncio blocking by using asyncio.to_thread() for all synchronous calls in async functions
- Remove dead code: module-level __call__ function that would never be invoked
- Replace global variable with module-level trafilatura import for cleaner code
- Remove unused json import in test file
- Improve error detection from fragile string check to robust pattern
- Add clarifying comments about safe circular imports due to lazy loading

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:26:49 +00:00
devops-vestradata 65791781e2 Add 10 grok4 intelligent agent files 2025-07-14 11:56:23 +05:30
claude[bot]andMervin Praison ee66154b73 fix: ensure interaction_displayed flag prevents all duplicate callbacks
- Added missing interaction_displayed checks to reasoning steps display
- Added missing checks to self-reflection display logic
- Ensured flag is set after each display interaction
- Fixed both sync and async methods
- Added comprehensive test to verify the fix

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:24:34 +00:00
claude[bot]andMervin Praison 0dc51060d8 fix: resolve callback duplication and validation timing issues
- Remove callback execution from display functions to prevent duplication when verbose=True
- Add missing callback execution after streaming completes when verbose=False
- Move callbacks to execute AFTER guardrail validation to prevent inconsistent state
- Add _execute_callback_and_display helper method to reduce code duplication
- Ensure callbacks work consistently regardless of verbose setting

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:23:51 +00:00
claude[bot]andMervin Praison 2daae1f464 fix: Address critical issues with Gemini structured output implementation
- Add hasattr check before calling model_json_schema() to prevent AttributeError
- Centralize Gemini model detection logic with new _is_gemini_model() method
- Fix critical bug: Always remove output_json/output_pydantic from params before passing to litellm
- Fix model recognition to handle provider-prefixed models (e.g., 'google/gemini-1.5-pro')
- Ensure backward compatibility for all existing models

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:23:29 +00:00
claude[bot]andMervin Praison 81bcda0440 fix: correct LLM interface usage and improve code quality
- Remove duplicate output_json=True when using output_pydantic
- Add helper methods to reduce code duplication
- Improve test file to use proper assertions instead of sys.exit()
- Add unit tests for the new helper methods
- Fix TypeError handling in JSON parsing

This ensures the hierarchical workflow works correctly with all LLM providers.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:23:13 +00:00
claude[bot]andMervin Praison e269cc7bf2 fix: Improve guardrail validation and add missing type hints
- Fixed critical bug: validation now properly checks for GuardrailResult type instead of accepting any class with the same name
- Added missing TaskOutput type hints in example file
- Refactored conditional logic for better readability
- Maintains full backward compatibility

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 06:21:30 +00:00
Mervin Praison 66e5dfcb41 refactor: update Claude GitHub Action with simplified OAuth authentication and improved triggers 2025-07-14 03:08:02 +01:00
Mervin Praison ae3e69a286 feat: exclude @gemini triage command from issue review workflow 2025-07-14 02:48:11 +01:00
Mervin Praison 40ea6fe1aa ci: simplify Gemini trigger command from '@gemini review' to '@gemini' 2025-07-14 02:46:58 +01:00
Mervin Praison e30a7564be Merge pull request #879 from MervinPraison/claude/issue-854-20250713_205120
fix: Implement Ollama sequential tool calling fix
2025-07-14 02:20:07 +01:00
claude[bot]andMervin Praison fbd0a736f0 fix: Fix critical issues in multi-provider implementation
- Changed TaskComplexity from string Enum to IntEnum for proper ordering comparisons
- Fixed manual routing logic to use llm_model property correctly
- Removed private attribute access by storing api_key and base_url locally
- Improved context size estimation from char count to token approximation
- Removed unused imports (Callable, TaskComplexity, ModelProfile)
- Fixed unnecessary f-string in error message
- Added TODO for token tracking implementation
- Fixed inconsistent model names in documentation

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 01:16:18 +00:00
claude[bot]andMervin Praison eea9f757af fix: use LLM abstraction instead of hardcoded OpenAI in hierarchical process
- Replace direct OpenAI client instantiation with LLM class
- Support all LLM providers (Gemini, Anthropic, etc.) in manager tasks
- Remove unused OpenAI imports from process.py
- Fix issue #873 where hierarchical workflow required OpenAI API key

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 01:08:57 +00:00
claude[bot]andMervin Praison 02a8f075a6 fix: prevent duplicate callback invocations in LLM response generation
- Add interaction_displayed flag to track display_interaction calls
- Prevent duplicate callbacks in both sync and async get_response methods
- Fix addresses issue where callbacks fired twice for single task execution
- Maintain backward compatibility with no API changes

Fixes #878

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 01:08:54 +00:00
claude[bot]andMervin Praison 57c39653d6 feat: Add Gemini structured output support
- Add Gemini models to MODELS_SUPPORTING_STRUCTURED_OUTPUTS
- Implement native Gemini structured output using response_schema
- Maintain backward compatibility for OpenAI and other models
- Update _build_messages to skip prompt modification for Gemini
- Add response_mime_type and response_schema parameters for Gemini
- Pass output_json/output_pydantic through all completion calls

Fixes #871

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 01:06:59 +00:00
claude[bot]andMervin Praison 2f21d0f907 fix: Support GuardrailResult return type in guardrail functions (#875)
- Modified task.py to accept both GuardrailResult and Tuple[bool, Any] return types
- Updated _process_guardrail to handle GuardrailResult directly without conversion
- Added comprehensive test cases for both return types
- Updated documentation with GuardrailResult examples
- Maintains backward compatibility with existing Tuple[bool, Any] guardrails

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 01:05:39 +00:00
claude[bot]andMervin Praison e0caaf8421 fix: enable true parallel execution for async tasks in sequential mode
Previously, async tasks in sequential mode were awaited one-by-one, defeating 
the purpose of async execution. This fix collects async tasks and runs them 
in parallel using asyncio.gather(), ensuring:

- Async tasks run concurrently as intended
- Sync tasks still execute in order after async tasks complete
- Proper task completion and dependency handling

Fixes #872

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 01:05:27 +00:00
claude[bot]andMervin Praison 4bc35c3b6e test: add test scripts for callback fix verification
- test_callback_fix.py: Simple test to verify callbacks work with verbose=False
- test_issue_877.py: Comprehensive test reproducing the exact issue scenario
- Both tests verify that callbacks are executed regardless of verbose setting

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 01:05:20 +00:00
claude[bot]andMervin Praison 4fd9b863a6 fix: ensure callbacks work regardless of verbose setting
- Added execute_sync_callback helper function to trigger callbacks without display
- Updated LLM class to always execute interaction callbacks when responses are generated
- Updated Agent class to ensure callbacks work for direct OpenAI client usage
- Maintains backward compatibility - display output still controlled by verbose flag
- Fixes issue #877 where callbacks only worked when verbose=True

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 01:05:13 +00:00
claude[bot]andMervin Praison fc02392ddb fix: prevent infinite loop in parallel task execution by exiting workflow when all tasks complete
When all tasks are completed and workflow_finished is set to True, the workflow now immediately exits to prevent tasks from being reset to "not started" state. This fixes the issue where parallel tasks would repeat in a loop and the aggregator task would never run.

Fixes #874

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 01:03:39 +00:00
claude[bot]andMervin Praison 4564639f18 enhance: Improve Ollama provider detection
- Add check for "ollama" in base_url for custom configurations
- Support detection of custom Ollama ports beyond 11434
- More robust detection for various deployment scenarios

Co-authored-by: Mervin Praison <[email protected]>
2025-07-14 00:58:57 +00:00
claude[bot]andMervin Praison 16598104ab feat: integrate Trafilatura for high-quality URL content extraction
- Add trafilatura_tools.py with extract_content, extract_metadata, extract_text_only, and compare_extraction functions
- Register Trafilatura tools in __init__.py for easy imports
- Add trafilatura and newspaper3k as optional [web] dependencies
- Include comprehensive URL validation to prevent SSRF attacks
- Update tools README with Trafilatura documentation
- Add detailed example file showing various usage patterns
- Create test script for verification
- Maintain backward compatibility with existing URL extraction tools

Resolves #869

Co-authored-by: Mervin Praison <[email protected]>
2025-07-13 21:05:30 +00:00
claude[bot]andMervin Praison b5d13a2b7f fix: Implement Ollama sequential tool calling fix
Modified conversation format for Ollama to handle tool results properly:
- Assistant messages no longer include 'tool_calls' field for Ollama
- Tool results are passed as user messages with natural language format
- Prevents infinite loop of repeated tool calls

This allows Ollama to properly execute sequential tool calls as intended.

Fixes #854

Co-authored-by: Mervin Praison <[email protected]>
2025-07-13 20:55:34 +00:00
claude[bot]andMervin Praison 4622bcda43 feat: Add multi-provider/multi-model support with intelligent routing
- Add ModelRouter for intelligent model selection based on task complexity
- Create MultiModelAgent class supporting multiple models per agent
- Implement routing strategies: auto, cost-optimized, performance-optimized
- Add pre-configured profiles for 8+ popular models
- Include usage tracking and cost estimation
- Maintain full backward compatibility
- Add comprehensive examples and documentation

Fixes #866

Co-authored-by: Mervin Praison <[email protected]>
2025-07-13 20:53:06 +00:00
Mervin Praison 31bae3a231 chore: bump PraisonAI to 2.2.54 and update Gemini workflows 2025-07-13 21:49:21 +01:00
Mervin Praison 466bcfedd7 Merge pull request #863 from MervinPraison/gemini/issue-862-fix-async-loop
Fix #862: Agent gets stuck in infinite loop when running multiple async tasks
2025-07-13 20:46:57 +01:00
Mervin Praison c24bf80314 Merge pull request #858 from MervinPraison/gemini/issue-854-fix-ollama-sequential-1690000000
Fix #854: Ollama sequential still failing
2025-07-13 20:46:21 +01:00
Mervin Praison c36b3aee6e Merge pull request #865 from MervinPraison/gemini/issue-864-fix-parallel-task-loop
Fix #864: Fix parallel task loop
2025-07-13 20:45:55 +01:00
Mervin Praison 08512ba6d3 Merge pull request #861 from MervinPraison/gemini/issue-860-fix-hierarchical-llm-fallback
Fix #860: Hierarchical Process LLM Fallback
2025-07-13 20:43:53 +01:00
claude[bot]andMervin Praison 63ebfc0b54 fix: Complete removal of Ollama special handling for async method
This completes the fix for issue #854 by removing the Ollama special
handling from the async method (get_response_async) to match the sync
method fix. Also removes the now-unused _handle_ollama_model method.

The special handling was causing infinite loops in sequential tool
calling. By removing it, Ollama models now work correctly through
the standard litellm interface.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-13 19:21:40 +00:00
claude[bot]andMervin Praison b29269071d fix: properly handle parallel task reset logic to prevent infinite loops
- Uncommented the task reset logic that was causing issue #864
- Added check for async_execution to prevent resetting parallel tasks
- Preserves backward compatibility for non-parallel tasks that need rerun
- Fixes infinite loop issue while maintaining existing functionality

Co-authored-by: Mervin Praison <[email protected]>
2025-07-13 19:14:59 +00:00
Gemini Bot b6a86bf348 Gemini: [Issue #864] Fix parallel task loop 2025-07-13 12:49:40 +00:00
Gemini Bot 02ba71be3d Gemini: [Issue #862] Fix infinite loop in async workflow 2025-07-13 12:17:37 +00:00
Gemini Bot e60f1c1aa1 Gemini: [Issue #860] Fix hierarchical process LLM fallback 2025-07-13 11:31:08 +00:00
Mervin Praison 450f237805 feat: add description field to TaskOutput in validation feedback tests 2025-07-13 01:17:26 +01:00
Mervin Praison 66e53fc82e refactor: move validation test files to src directory and update LLM model references 2025-07-13 01:09:52 +01:00
Mervin Praison 7e6ee5f9f2 chore: enhance variable handling in PR review workflow for improved clarity 2025-07-13 01:04:41 +01:00
Mervin Praison b669b9815d fix: correct variable interpolation syntax in PR review workflow 2025-07-13 00:50:39 +01:00
Mervin Praison 6d89cd603e chore: remove debug workflow trigger step from Gemini PR review action 2025-07-13 00:44:38 +01:00
Mervin Praison 6e955b5941 feat: restrict Gemini PR review to repo owners, members and collaborators 2025-07-13 00:34:48 +01:00
Mervin Praison 87a67b5f5d refactor: improve PR checkout logic in Gemini review workflow using dedicated step 2025-07-13 00:25:08 +01:00
Mervin Praison baec9cd0a4 fix: update checkout ref to handle both PR and issue comment triggers 2025-07-13 00:23:16 +01:00
Mervin Praison e144dc497d feat: allow all users to trigger Gemini PR review and add debug logging 2025-07-13 00:19:06 +01:00
Gemini Bot 8a77ab0ab5 Gemini: [Issue #854] Fix Ollama sequential tool calling loop 2025-07-12 23:10:23 +00:00
Mervin Praison 0034b5c964 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-13 00:04:14 +01:00
Mervin Praison 543c627374 feat: expand GitHub Actions permissions to include PR list and granular git commands 2025-07-13 00:04:13 +01:00
Mervin Praison 93154adf9e Merge pull request #857 from MervinPraison/gemini/issue-854-fix-ollama-sequential-fail
Fix #854: Ollama sequential tool calling failing
2025-07-13 00:03:55 +01:00
Gemini Bot 3ab2462d96 Gemini: [Issue #854] Fix Ollama sequential tool calling loop 2025-07-12 23:00:05 +00:00
Mervin Praison aecf65a130 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-12 23:52:47 +01:00
Mervin Praison 0a453d30a2 chore: add .gemini and issue_details.json to gitignore 2025-07-12 23:52:46 +01:00
Mervin Praison 354a2c717b Merge pull request #856 from MervinPraison/gemini/issue-854-fix-ollama-sequential
Fix #854: Ollama sequential tool calling failing
2025-07-12 23:52:38 +01:00
Mervin Praison 62514fbef4 Delete issue_details.json 2025-07-12 23:51:43 +01:00
Mervin Praison f3c77a2e8b Delete .gemini/settings.json 2025-07-12 23:51:32 +01:00
Gemini Bot 50dde4fa02 Gemini: [Issue #854] Fix Ollama sequential tool calling 2025-07-12 22:45:09 +00:00
Mervin Praison bbc4530329 chore: bump version to 2.2.53 and update dependencies across package files 2025-07-12 23:43:01 +01:00
Mervin Praison aab975bec7 Merge pull request #851 from MervinPraison/claude/issue-846-20250712_220811
fix: handle None response_text in Ollama sequential tool calls
2025-07-12 23:28:38 +01:00
Mervin Praison 50c50fa567 Merge pull request #849 from MervinPraison/claude/issue-845-20250712_183232
fix: enable sequential tool execution in OpenAI client
2025-07-12 23:27:54 +01:00
claude[bot]andMervin Praison 68f280634a refactor: remove dead code from sequential tool execution logic
- Remove unused should_continue variable and related logic
- Simplify code by removing special handling for sequentialthinking tool
- Add clear comments explaining the sequential execution behavior

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 22:16:05 +00:00
Mervin Praison 346488fbec Delete test_sequential_fix.py 2025-07-12 23:15:10 +01:00
claude[bot]andMervin Praison 57b5a1fd8d fix: handle None response_text in Ollama sequential tool calls
- Add None checks before calling .strip() on response_text
- Fixes 'NoneType' object has no attribute 'strip' error with Ollama models
- Applied pattern: response_text.strip() if response_text else ""
- Fixed 14 locations where .strip() was called without None checks
- Ensures backward compatibility by returning empty string instead of None

Fixes issue #846

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 22:11:55 +00:00
claude[bot]andMervin Praison d75a5bb728 test: add assertions to test_sequential_fix.py for automated testing
- Add proper assertions to verify sequential tool execution results
- Improve multiply function docstring with complete Args and Returns sections
- Add success message when all assertions pass

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 22:10:09 +00:00
Mervin Praison 519ecc025a feat: update allowed commands in GitHub workflow files for Gemini reviews 2025-07-12 21:21:23 +01:00
Mervin Praison 8290b95132 refactor: update issue review prompt with clearer instructions and dynamic commands 2025-07-12 21:01:13 +01:00
Mervin Praison 3d95e1ff0e feat: add read_file permission to Gemini PR review workflow 2025-07-12 20:55:41 +01:00
Mervin Praison 74405d1bbe feat: add read_file permission to Gemini issue review workflow 2025-07-12 20:54:59 +01:00
Mervin Praison d307c3857c feat: add environment variables for Gemini CLI action in GitHub workflow 2025-07-12 20:54:31 +01:00
Mervin Praison fbe5dddaae chore: disable telemetry in GitHub workflow configurations 2025-07-12 20:45:20 +01:00
Mervin Praison 7e4108918d fix: move GH_TOKEN to local env scope in GitHub workflow 2025-07-12 20:40:04 +01:00
Mervin Praison da7e38100e feat: add GitHub workflow for automated issue review using Gemini AI 2025-07-12 20:36:37 +01:00
Mervin Praison 848459b816 feat: add edit, web-fetch, web-search and memoryTool permissions while removing telemetry setup 2025-07-12 20:35:19 +01:00
Mervin Praison cd63845398 feat: add git command to allowed shell commands in PR review workflow 2025-07-12 20:31:18 +01:00
Mervin Praison 7827427dc0 feat: move Gemini PR review action to dedicated directory with configuration 2025-07-12 20:16:47 +01:00
Mervin Praison 0e378d0754 feat: add GitHub workflows for Gemini issue triage and PR review automation 2025-07-12 20:03:05 +01:00
Mervin Praison 206022eb9c refactor: simplify auto-comment workflows by removing multi-agent review requirement 2025-07-12 19:48:23 +01:00
Mervin Praison 901ba8074d Delete test_sequential_fix.py 2025-07-12 19:40:42 +01:00
claude[bot]andMervin Praison 953ee6e7bd fix: enable sequential tool execution in OpenAI client
Removes premature loop termination after tool execution to allow
sequential tool calls. The model can now see tool results and make
additional tool calls as needed.

Fixes #845

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 18:36:00 +00:00
Mervin Praison 181d7e1ede feat: bump PraisonAI to v2.2.52 and add sequential agent examples for OpenAI/Ollama 2025-07-12 19:12:05 +01:00
Mervin Praison 4039878422 Merge pull request #842 from MervinPraison/claude/issue-839-20250712_075350
fix: allow agents to continue with sequential tool calls
2025-07-12 19:04:25 +01:00
Mervin Praison 461eba18d5 Delete src/praisonai/tests/unit/test_sequential_tool_calling.py 2025-07-12 19:03:44 +01:00
claude[bot]andMervin Praison 331a1de610 test: add comprehensive test suite for sequential tool calling
This test file validates the fix for issue #839, ensuring agents can:
- Execute multiple tools in sequence
- Pass results between tool calls
- Return final combined results without empty responses

Tests include:
- Sequential execution of 2 and 3 tools
- Multiple agents with sequential tools
- Mocked LLM responses
- Edge case prevention for empty responses

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 18:00:27 +00:00
claude[bot]andMervin Praison 91632eb5e4 fix: correct Ollama return statement and variable reference for sequential tool calling
- Replace early return with loop continuation in Ollama handling to match async behavior
- Fix variable reference from reasoning_content to stored_reasoning_content
- Ensures agents can perform sequential tool calls as intended

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 17:54:53 +00:00
Mervin Praison ad46225483 Rename src/praisonai/tests/unit/test_fix_comprehensive.py to src/praisonai-agents/tests/test_fix_comprehensive.py 2025-07-12 18:50:30 +01:00
Mervin Praison 9af6758eb6 Delete test_fix.py 2025-07-12 18:48:37 +01:00
Mervin Praison aac67a6572 Rename test_fix_comprehensive.py to src/praisonai/tests/unit/test_fix_comprehensive.py 2025-07-12 18:47:35 +01:00
claude[bot]andMervin Praison 2ceff9bfae fix: correct indentation error in async streaming code
Fixed SyntaxError caused by incorrect indentation in the async version of get_response_async method. The if/else blocks for streaming vs non-streaming approaches now have proper indentation.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 17:41:09 +00:00
claude[bot]andMervin Praison 3b7af02bea fix: correct indentation error in async streaming code
Fixed IndentationError at line 1325 where the async for loop was not properly
indented under the if verbose: block. Also corrected the indentation of the
else block for non-verbose streaming.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 17:33:23 +00:00
Mervin Praison 1ee7cfa2ef Merge pull request #844 from MervinPraison/claude/issue-840-20250712_172354
docs: add OLLAMA_HANDLING.md to explain ollama_handled flag usage
2025-07-12 18:32:16 +01:00
claude[bot]andMervin Praison b01bd41574 fix: add sequential tool calling support to async get_response_async method
- Add while loop structure with max_iterations and iteration_count
- Replace return statements with loop continuation after tool execution
- Store reasoning content across iterations for proper display
- Update final response handling to use stored values from iterations
- Ensure async behavior matches sync version for issue #839

This resolves the inconsistency where async agents would return empty
responses after first tool call instead of continuing with additional
required tool calls.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 17:27:37 +00:00
claude[bot]andMervin Praison 6570e445b8 docs: add OLLAMA_HANDLING.md to explain ollama_handled flag usage
Add documentation to clarify that ollama handling is correctly implemented
in llm.py and not in agent.py, addressing issue #840

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 17:25:07 +00:00
Mervin Praison b421bcf925 Merge pull request #843 from MervinPraison/claude/issue-841-20250712_080725
fix: add return_dict=True to fix TypeError in prompt_chaining tests
2025-07-12 18:24:24 +01:00
claude[bot]andMervin Praison 41d0998b76 fix: preserve reasoning_steps functionality with sequential tool calling
- Add stored_reasoning_content to capture reasoning after tool execution
- Restore reasoning_steps handling after tools while keeping loop continuation
- Update final response display to include stored reasoning when available
- Return reasoning content when reasoning_steps=True and content exists

This ensures backward compatibility while maintaining the sequential tool calling fix

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 08:41:06 +00:00
claude[bot]andMervin Praison 393e0ee33d fix: document async limitation and ensure consistent behavior
- Added clear documentation that async version doesn't support sequential tool calling
- Reverted incomplete async implementation to avoid breaking existing functionality
- Sync version retains the fix for sequential tool calling (issue #839)
- Created a known limitation that needs to be addressed in a future PR

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 08:40:25 +00:00
claude[bot]andMervin Praison 0dce4de4a4 fix: add return_dict=True to fix TypeError in prompt_chaining tests
The workflow.start() method returns a string by default (for backward compatibility),
but the test files were expecting a dictionary. Fixed by adding return_dict=True
parameter to get the expected dictionary format with task_results and task_status keys.

Fixes #841

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 08:23:56 +00:00
Mervin Praison 7fe4b48c6e fix: update LLM model and refine agent instruction
Changed the LLM model from "openai/gpt-4o-mini" to "gemini/gemini-2.5-pro" for improved performance. Updated the agent's instruction to provide clearer context for the task, enhancing user interaction.

Also, optimised the suggest_fixes function to handle both dictionary and string inputs, improving its flexibility in suggesting fixes based on issue type.

This minimal change aims to enhance the functionality while maintaining existing code integrity.
2025-07-12 09:22:33 +01:00
claude[bot]andMervin Praison 5286912f34 test: add test scripts for sequential tool calling fix
Add test scripts to verify the fix for issue #839 works correctly
with both Gemini and GPT-4 models.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 08:01:18 +00:00
claude[bot]andMervin Praison d6cb1c0165 fix: allow agents to continue with sequential tool calls
After executing tool calls, the agent now continues the iteration loop
instead of immediately trying to get a final response. This allows the
LLM to decide if more tools are needed to complete the task.

Fixes issue where agents would return empty responses after the first
tool call instead of continuing with additional required tool calls.

Resolves #839

Co-authored-by: Mervin Praison <[email protected]>
2025-07-12 08:01:10 +00:00
Mervin Praison 08ed3f94dc Merge pull request #836 from MervinPraison/claude/issue-835-20250711_234446
fix: capture final response after tool execution in LLM
2025-07-12 01:10:32 +01:00
Mervin Praison d3bfbc4b92 Delete test_issue_835.py 2025-07-12 01:00:19 +01:00
claude[bot]andMervin Praison af7081d294 fix: capture final response after tool execution in LLM
When an agent executes tools and the final iteration contains the answer
without additional tool calls, ensure the response text is properly captured
and returned instead of returning empty/None.

This fixes the issue where agents with multiple tools would return empty
responses after successfully executing tools.

Fixes #835

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 23:52:25 +00:00
Mervin Praison 3b2f26699e Merge pull request #834 from MervinPraison/claude/pr-832-20250711_232348
PR #832: Changes from Claude
2025-07-12 00:42:58 +01:00
claude[bot]andMervin Praison 7aa61b9155 fix: pass stream parameter from Agent to LLM
The Agent class was not passing the stream parameter to the LLM's get_response() method, causing the LLM to always use its default stream=True behavior regardless of the Agent's configuration.

This fix ensures that when an Agent is created with stream=False or when chat() is called with stream=False, this preference is properly passed to the LLM.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 23:31:50 +00:00
Mervin Praison 7e37c940d4 feat: upgrade praisonai to v2.2.51 and add aiohttp dependency to praisonaiagents v0.0.125 2025-07-12 00:28:17 +01:00
Mervin Praison 2199a57dfe Merge pull request #832 from MervinPraison/claude/issue-824-20250711_155141
fix: sequential tool calling for non-streaming responses
2025-07-12 00:19:42 +01:00
Mervin Praison d49f046322 Rename test_sequential_tool_calling.py to src/praisonai-agents/test_sequential_tool_calling.py 2025-07-12 00:14:28 +01:00
claude[bot]andMervin Praison c16c2e38af fix: improve sequential tool calling for non-streaming responses
- Fixed Ollama handling to properly separate streaming/non-streaming modes
- Added robust error handling for response extraction
- Fixed test file to use correct stream parameter
- Ensures tool outputs are processed by LLM in non-streaming mode

Addresses review feedback on PR #832

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 18:24:18 +00:00
Mervin Praison b5df9f323c Merge pull request #833 from MervinPraison/claude/issue-831-20250711_173321
fix: centralize logging configuration to respect LOGLEVEL environment variable
2025-07-11 19:05:06 +01:00
claude[bot]andMervin Praison 6e4abeef52 fix: ensure consistent logger levels across modules
- Change third-party logger levels from ERROR to WARNING in llm/__init__.py
  to match the centralized configuration
- Remove root logger override in knowledge.py that was ignoring LOGLEVEL
  environment variable

This ensures the LOGLEVEL environment variable is properly respected
throughout the application.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 17:58:02 +00:00
claude[bot] 5656570172 chore: remove test_logging.py from root - should be in tests directory
The test script was helpful for verifying the fix but should not be in the package root.
2025-07-11 17:44:52 +00:00
claude[bot]andMervin Praison c08c7cfedf fix: centralize logging configuration to respect LOGLEVEL environment variable
- Move logging configuration to top of __init__.py to ensure it runs before any imports
- Remove duplicate logging.basicConfig from llm/__init__.py that was overriding settings
- Clean up main.py to remove redundant logging configuration
- Add test_logging.py script to verify the fix works correctly

This ensures that the LOGLEVEL environment variable (DEBUG, INFO, WARNING, ERROR) properly controls logging verbosity throughout the package.

Fixes #831

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 17:44:18 +00:00
Mervin Praison fbbe80fd4d Merge pull request #829 from MervinPraison/claude/issue-827-20250711_151456
fix: add validation feedback to workflow retry logic
2025-07-11 17:27:46 +01:00
claude[bot]andMervin Praison cabddd9a22 refactor: extract validation failure decisions to class constant
- Add VALIDATION_FAILURE_DECISIONS constant to avoid duplication
- Update all references to use the constant
- Improve maintainability for future additions

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 16:05:19 +00:00
claude[bot]andMervin Praison 20b838f36a fix: handle non-streaming responses after tool execution for sequential tool calling
- Fixed issue where tool outputs were returned directly to user when stream=False
- Added proper handling for non-streaming responses after tool calls
- Maintains backward compatibility with existing streaming behavior

Fixes #824

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 15:59:04 +00:00
claude[bot]andMervin Praison cf149a3c2d fix: add validation feedback to workflow retry logic
When validation fails, retry tasks now receive:
- The validation failure reason
- The rejected output that failed validation  
- Clear instructions to try a different approach

This allows context-dependent tasks to improve on retry instead of
repeating the same invalid output.

Fixes #827

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 15:24:52 +00:00
Mervin Praison 30f6f5706c Merge pull request #826 from MervinPraison/claude/issue-823-20250711_111524
feat: Implement MCP HTTP Stream transport
2025-07-11 16:05:43 +01:00
claude[bot]andMervin Praison 0423c9c4af fix: address code review issues in HTTP Stream implementation
- Fix error propagation in write_stream method
- Add proper shutdown handling in SSE listener to prevent resource leaks
- Implement proper type annotations based on schema types
- Add _closing flag to gracefully stop SSE listener
- Create basic test to verify transport selection logic

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 14:08:58 +00:00
claude[bot]andMervin Praison be82abfac3 feat: Implement MCP HTTP Stream transport
- Add HTTP Stream transport implementation with single endpoint architecture
- Support both batch (JSON) and stream (SSE) response modes
- Implement session management with Mcp-Session-Id header
- Maintain full backward compatibility with SSE transport
- Add aiohttp dependency for HTTP client functionality
- Create usage examples and test file

Closes #823

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 11:27:37 +00:00
Mervin Praison 4af6228f89 feat: add automated PR review comment workflow for Claude integration 2025-07-11 11:59:45 +01:00
Mervin Praison 33eaf34ffb feat: bump PraisonAI to v2.2.50 and add Gemini agent tools implementation 2025-07-11 11:50:25 +01:00
Mervin Praison e2512b38c0 Merge pull request #814 from Dhivya-Bharathy/grok4-10-new-agents
Add 10 New Grok4 Intelligent Agents Covering Diverse Domains
2025-07-11 11:46:42 +01:00
Mervin Praison b02cda252d Merge pull request #819 from MervinPraison/claude/issue-818-20250711_091438
fix: enable tool calling for Gemini models
2025-07-11 11:42:43 +01:00
Mervin Praison 2a4b369e15 Rename test_tool_fix_improved.py to src/praisonai/tests/unit/test_tool_fix_improved.py 2025-07-11 11:42:29 +01:00
Mervin Praison c0a9e55f6a Rename test_tool_fix_example.py to src/praisonai/tests/unit/test_tool_fix_example.py 2025-07-11 11:42:12 +01:00
Mervin Praison 7c4b28885d Rename test_tool_fix_documentation.md to src/praisonai/tests/unit/test_tool_fix_documentation.md 2025-07-11 11:41:56 +01:00
Mervin Praison b0ec8b9a22 Rename test_gemini_tool_choice.py to src/praisonai/tests/unit/test_gemini_tool_choice.py 2025-07-11 11:41:32 +01:00
Mervin Praison 1b5cf2baea Rename test_async_gemini_fix.py to src/praisonai/tests/unit/test_async_gemini_fix.py 2025-07-11 11:41:19 +01:00
claude[bot]andMervin Praison b1cc2c31ce fix: enable tool calling for async agents with Gemini models
- Created _build_system_prompt method to centralize system prompt generation
- Fixed async achat to use correct tools parameter (was always using self.tools)
- Both sync and async now use enhanced system prompt with tool information
- Added comprehensive async agent test to verify the fix

This resolves the issue where async agents would claim no internet access
even when tools were available.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 10:15:56 +00:00
claude[bot]andMervin Praison 2a40c57033 feat: enhance Gemini tool calling fix with improved error handling
- Add comprehensive error handling for tool name extraction
- Support MCP tools with to_openai_tool method
- Improve Gemini model detection to handle variants
- Add litellm.supports_function_calling check
- Fix potential TypeError with nested dictionary access
- Update documentation with improvements
- Add comprehensive test example

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 09:59:39 +00:00
claude[bot]andMervin Praison 350d6e6488 fix: improve Gemini tool calling implementation
- Fix model prefix inconsistency (add 'gemini-' prefix check)
- Add debug logging when tool_choice='auto' is set for Gemini models
- Add error handling for tool name extraction
- Add test to verify tool_choice behavior for different models

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 09:54:05 +00:00
Mervin Praison 20a49ffd70 refactor: optimise test_autoagents.py for clarity and consistency
- Updated tool configurations to use string names instead of Mock objects for better clarity.
- Simplified the test for custom API key and base URL, ensuring parameters are stored correctly.
- Enhanced comments to improve understanding of the test setup and expected behaviour.

These changes improve the readability and maintainability of the test suite while ensuring accurate validation of configurations.
2025-07-11 10:42:57 +01:00
Mervin Praison 4bf9916c5f refactor: update test_autoagents.py to improve validation scenarios
- Introduced an invalid configuration to simulate validation failures in tests.
- Updated the first response to reflect the new invalid config structure.
- Simplified mock client configuration by using a sample valid config for structured output.

These changes enhance the robustness of the test cases while ensuring clarity in error handling scenarios.
2025-07-11 10:36:17 +01:00
claude[bot]andMervin Praison 9764483f36 fix: enable tool calling for Gemini models
- Enhanced system prompt to explicitly mention available tools
- Added tool_choice='auto' for Gemini models to encourage tool usage
- Maintains full backward compatibility
- Added test example and documentation

Fixes #818 where agents using Gemini models were not calling tools

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 09:27:37 +00:00
Mervin Praison ff405be834 refactor: enhance test_autoagents.py with improved mock configuration
- Updated the first response to use a malformed JSON string for clarity in error simulation.
- Introduced a serializable configuration for the mock client to ensure valid data handling in tests.
- Enhanced comments for better understanding of the test setup and scenarios.

These changes improve the clarity and robustness of the test cases while maintaining the integrity of the testing framework.
2025-07-11 10:23:21 +01:00
Mervin Praison 6d384a96ca refactor: improve test_autoagents.py for clarity and validation
- Updated comments for better understanding of test cases.
- Modified task configuration to create a valid config before simulating error conditions.
- Changed patch references from 'praisonaiagents.agents.autoagents.supports_structured_outputs' to 'praisonaiagents.llm.supports_structured_outputs' for consistency across tests.

These changes enhance the readability and maintainability of the test suite while ensuring accurate validation scenarios.
2025-07-11 10:18:13 +01:00
Mervin Praison 6770996c8b Merge pull request #812 from MervinPraison/claude/issue-795-20250710_222918
Claude/issue 795 20250710 222918
2025-07-11 10:06:12 +01:00
claude[bot]andMervin Praison 93c7731ccb fix: resolve code quality issues and unreachable code in agent.py
- Remove unused variable final_response_text
- Fix multimodal prompt normalization fallback to use empty string instead of str(prompt)
- Fix inconsistent variable usage: use original_prompt instead of prompt in display_interaction and _apply_guardrail_with_retry calls
- Remove unnecessary f-string where no interpolation is needed
- Fix unused exception variable by removing 'as e' where e is not used

These changes improve code quality while maintaining backward compatibility and ensuring the handoff fix continues to work correctly.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 08:29:20 +00:00
Mervin Praison 2057c68a20 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI into pr-812-handoff-fix 2025-07-11 09:16:11 +01:00
Mervin Praison 1ca928a2e4 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-11 09:09:32 +01:00
Mervin Praison 66ea9d7148 fix: enhance unit tests for AutoAgents class
- Added dynamic import handling for AutoAgents and related classes to prevent ImportError.
- Refactored test cases to create AutoAgents instances without invoking __init__ to avoid unnecessary API calls.
- Improved mock handling in tests to ensure proper validation and response checks.
- Ensured structured output support is correctly mocked across various test scenarios.
- Maintained existing functionality while optimising test structure for clarity and maintainability.
2025-07-11 09:09:31 +01:00
Mervin Praison 74a71807a6 Merge pull request #816 from MervinPraison/claude/issue-813-20250711_070340
fix: add missing HostedMCPServer class for MCP server implementations
2025-07-11 09:06:39 +01:00
Mervin Praison 9e92e85a72 Update pyproject.toml 2025-07-11 08:53:35 +01:00
Mervin Praison 6d827a45c8 Update pyproject.toml 2025-07-11 08:53:01 +01:00
Mervin Praison aabaaa6318 Update pyproject.toml 2025-07-11 08:52:38 +01:00
Mervin Praison f518bd301a Update pyproject.toml 2025-07-11 08:52:14 +01:00
Mervin Praison 834f710cf6 chore: update PraisonAI and related package versions to 2.2.49 and 0.0.123
- Updated PraisonAI version from 2.2.48 to 2.2.49 across Dockerfiles, README, and Ruby formula.
- Incremented praisonaiagents version from 0.0.122 to 0.0.123 in relevant files.
- Ensured consistency in package versions for improved stability and functionality.
2025-07-11 08:50:14 +01:00
Mervin Praison ede71a7fbe Merge pull request #817 from MervinPraison/claude/issue-815-20250711_070741
fix: resolve SyntaxError in autoagents.py
2025-07-11 08:47:11 +01:00
claude[bot]andMervin Praison 7c751c88a3 fix: resolve test failures in autoagents.py
- Use client.parse_structured_output instead of client.beta.chat.completions.parse
- Change llm_instance.response to llm_instance.get_response for structured output support
- Fixes AttributeError: 'OpenAIClient' object has no attribute 'beta'
- Fixes TypeError: Object of type ModelMetaclass is not JSON serializable

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:42:53 +00:00
claude[bot]andMervin Praison 17f3aab1e1 refactor: complete moving HostedMCPServer to examples folder
- Add hosted_server.py to examples/python/custom_tools/
- Update documentation to clarify this is an example implementation
- Keep starlette dependency as it's still used by Agent.launch() for MCP

This makes HostedMCPServer an example implementation rather than
a core package component.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:41:27 +00:00
claude[bot]andMervin Praison 028fa8158d refactor: move HostedMCPServer from core package to examples folder
- Move hosted_server.py to examples/python/custom_tools/
- Update import in mcp_server_latency_example.py to use local file
- Remove HostedMCPServer from core package exports

This keeps HostedMCPServer as an example implementation rather than
a core package component, as requested.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:39:24 +00:00
claude[bot]andMervin Praison c62685adc5 fix: remove dead code and add missing reflection continuation logic
- Remove unreachable code after while True loop (lines 1414-1429)
- Add missing reflection continuation code for non-satisfactory reflections
- Fix unnecessary f-string prefix in error message
- Fixes syntax error preventing test imports

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:29:52 +00:00
claude[bot]andMervin Praison 60d6178310 fix: add missing newline at end of autoagents.py to prevent parser errors
Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:26:59 +00:00
claude[bot]andMervin Praison b198154b71 fix: resolve SyntaxError and improve code structure in autoagents.py
- Fixed incorrect indentation causing SyntaxError on line 436
- Removed duplicate llm_instance creation and OpenAI detection logic
- Cleaned up nested try-except blocks for better readability
- Preserved backward compatibility with OpenAI structured outputs
- Maintained all error handling and retry mechanisms
- Fixed logic flow to properly check for OpenAI support once per retry

This minimal fix addresses the critical syntax issues while maintaining
all existing functionality.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:26:44 +00:00
claude[bot]andMervin Praison 205de2ba0b fix: improve HostedMCPServer implementation
- Remove unnecessary ABC inheritance and unused imports
- Add proper error handling for uninitialized MCP server
- Improve error messages for better debugging

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:23:48 +00:00
claude[bot]andMervin Praison ee668b2711 fix: resolve code quality issues and unreachable code in agent.py
- Fix unreachable reflection continuation code by moving it outside max reflections if block
- Remove unused variable final_response_text
- Fix unnecessary f-string without placeholders
- Correct prompt normalization: use original_prompt instead of prompt in display/guardrail calls
- Maintain backward compatibility while fixing handoff functionality

These changes address issues identified by multiple code reviewers while preserving
the core fix for handoff functionality (issue #795).

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:23:34 +00:00
claude[bot]andMervin Praison a5bbb65017 fix: resolve IndentationError in autoagents.py
- Fixed indentation issues that caused SyntaxError on line 360
- Removed duplicate OpenAI client initialization logic
- Properly indented the LLM instance creation and response parsing code
- Maintained backward compatibility with existing functionality

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:23:30 +00:00
claude[bot]andMervin Praison 6296755ebb fix: add missing newline at end of autoagents.py to prevent parser errors
Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:21:07 +00:00
claude[bot]andMervin Praison 4b6c847260 fix: resolve SyntaxError in autoagents.py by fixing indentation and uninitialized variables
- Fixed incorrect indentation from line 347 onwards that caused the SyntaxError
- All code from line 347-435 is now properly indented inside the else block
- Added initialization of `use_openai_structured` and `client` variables at the start of each retry loop to prevent NameError
- Preserved duplicate OpenAI detection logic for backward compatibility

Fixes #815

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:19:17 +00:00
Mervin Praison 2fc459fe05 chore: correct string escape sequences in test-core.yml
- Adjusted escape sequences for environment variable retrieval and print statements to ensure proper formatting and clarity in the workflow file.
2025-07-11 08:18:05 +01:00
Mervin Praison 1c3c2941cc chore: enhance review comments in automated workflows for clarity
- Updated the body of comments in auto-issue-comment.yml and auto-pr-comment.yml to include a note on minimal code changes, ensuring clarity while maintaining guidance for backward compatibility and testing.
2025-07-11 08:15:20 +01:00
Mervin Praison 6e38a88cd3 chore: optimise variable initialisation in autoagents.py
- Removed unnecessary initialisation of variables and streamlined the handling of OpenAI client instances to enhance code clarity and maintainability while ensuring backward compatibility.
2025-07-11 08:12:51 +01:00
claude[bot]andMervin Praison f0f22bb13d fix: add missing HostedMCPServer class for MCP server implementations
- Created HostedMCPServer base class in mcp/hosted_server.py
- Added HostedMCPServer to module exports in __init__.py
- Added starlette>=0.27.0 to MCP optional dependencies
- Fixes ImportError when using mcp_server_latency_example.py

Resolves #813

Co-authored-by: Mervin Praison <[email protected]>
2025-07-11 07:12:31 +00:00
Mervin Praison a8fa70c455 chore: refine review comment in automated issue workflow
- Adjusted the body of the comment in auto-issue-comment.yml to enhance clarity by removing redundant phrases while ensuring guidance for backward compatibility and testing remains intact.
2025-07-11 08:11:37 +01:00
Mervin Praison 1b4b4a10b5 chore: update review comment in automated PR workflow for multi-agent analysis
- Modified the body of the comment in auto-pr-comment.yml to include instructions for reviewing pull requests with multiple parallel running agents, ensuring clarity while maintaining guidance for backward compatibility and testing.
2025-07-11 08:11:20 +01:00
devops-vestradata 1efdaac18f Add 10 new Grok4 intelligent agents 2025-07-11 12:29:26 +05:30
Mervin Praison 1b2182968f chore: simplify review comment in automated PR workflow
- Revised the body of the comment in auto-pr-comment.yml to streamline instructions for review, removing redundant phrases while maintaining clarity and guidance for backward compatibility and testing.
2025-07-11 01:16:13 +01:00
claude[bot]andMervin Praison 5e5a10589e fix: correct syntax error - fix indentation of lines 1404-1411 to be inside try block
The code from lines 1404-1411 was incorrectly outside the try block that starts at line 1325, causing a syntax error when the except block at line 1413 tried to match with it. This fix properly indents these lines to be inside the try block.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:59:40 +00:00
claude[bot]andMervin Praison 6c5e42762f fix: comprehensive fix for all try-except block indentation issues
- Fixed indentation of except block at line 1413 to match its try block
- Moved except block at line 1419 and subsequent code inside the while loop
- Properly structured all nested try-except blocks to prevent syntax errors
- Ensured the handoff fix (user message added before LLM call) is preserved

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:55:28 +00:00
claude[bot]andMervin Praison afb7e47080 fix: correct syntax error - fix indentation of except block at line 1413
The except block was indented with 28 spaces instead of 24 spaces to match its corresponding try block, causing a SyntaxError

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:50:32 +00:00
claude[bot]andMervin Praison e674a2ae84 fix: correct syntax errors and add missing guardrail validation to achat()
- Fix indentation of except block at line 1413 (20 spaces -> 24 spaces)
- Add guardrail validation to achat() method for both custom LLM and OpenAI paths
- Ensure feature parity between sync chat() and async achat() methods

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:46:10 +00:00
Mervin Praison d471d9754a chore: enhance automated comment workflows with additional guidance
- Updated the body of comments in both auto-issue-comment.yml and auto-pr-comment.yml to include instructions for using @web for information retrieval and testing code execution if necessary.
2025-07-11 00:39:27 +01:00
claude[bot]andMervin Praison 9d25b1ed3d fix: correct syntax error in agent.py - add missing except block
The try block at line 1249 (inside the while loop) was missing its 
corresponding except block. Added proper exception handling to close
the try block and re-raise exceptions to the outer handler.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:37:43 +00:00
claude[bot]andMervin Praison d0d04bc17e fix: add missing guardrail validation and error handling to achat() async method
- Add guardrail validation to all return points in achat() method (except JSON/Pydantic outputs)
- Add try-except wrapper around while loop in OpenAI path for proper error recovery
- Ensure chat history rollback on all failure paths in async method
- Maintain feature parity between sync chat() and async achat() methods

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:36:32 +00:00
Mervin Praison 1f4e2b1c5a chore: update github-token in automated comment workflows
- Changed the token reference from GITHUB_TOKEN to GH_TOKEN in both auto-issue-comment.yml and auto-pr-comment.yml for consistency in authentication.
2025-07-11 00:32:09 +01:00
claude[bot]andMervin Praison 88d4241121 fix: correct syntax error in agent.py - proper indentation for try-except block
Fixed syntax error at line 1361 where code was not properly indented inside the try block.
The code from lines 1361-1412 needed to be indented by 4 spaces to be inside the try
block that starts at line 1325.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:31:31 +00:00
Mervin Praison 9e081e9413 chore: add github-token to automated comment workflows
- Included github-token in both auto-issue-comment.yml and auto-pr-comment.yml to ensure proper authentication for comment creation.
2025-07-11 00:30:18 +01:00
Mervin Praison bc0449b8de Merge pull request #803 from MervinPraison/claude/issue-792-20250710_221133
fix: replace prefix-based model detection with capability-based detection
2025-07-11 00:26:33 +01:00
Mervin Praison c262942ba7 Merge branch 'main' into claude/issue-792-20250710_221133 2025-07-11 00:26:18 +01:00
Mervin Praison 40e5c13f47 chore: update PraisonAI version to 2.2.48 in Dockerfiles, README, and related files 2025-07-11 00:23:41 +01:00
Mervin Praison 5eea991a60 Merge pull request #801 from MervinPraison/claude/issue-798-20250710_224150
fix: update AutoAgents prompt to generate proper TaskConfig objects
2025-07-11 00:19:27 +01:00
claude[bot]andMervin Praison 209c2a42ae fix: correct syntax errors in try-except block indentation
- Fix indentation of reflection prompt code block (lines 1316-1323)
- Fix indentation of try-except blocks for self-reflection (lines 1325-1418)
- Fix indentation of code inside if-else statements for custom LLM vs OpenAI
- Fix indentation of final logging and guardrail validation code

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:18:25 +00:00
Mervin Praison efb927137f refactor: remove unused autoagents-tools.py file
- Deleted the autoagents-tools.py file as it contained redundant code and instances of AutoAgents that are no longer needed.
2025-07-11 00:17:10 +01:00
claude[bot]andMervin Praison 162223162f test: add comprehensive unit tests for AutoAgents validation and retry logic
- Add test coverage for _validate_config method
- Test successful config generation via OpenAI and LLM paths
- Test retry mechanism with validation failures
- Test edge cases like max_agents truncation and warnings
- Mock LLM responses to avoid API calls in tests

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:15:15 +00:00
claude[bot]andMervin Praison 75c856b948 fix: correct syntax errors in try-except block indentation
- Fixed indentation issues in chat() method where code was not properly indented inside try blocks
- Fixed duplicate except block that was causing syntax errors
- Added missing chat history management to async achat() method for OpenAI client path
- Ensured all try-except blocks are properly structured and closed

This resolves the SyntaxError preventing module import and test execution.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:11:36 +00:00
claude[bot]andMervin Praison 85fefac429 fix: add missing duplicate prevention and error rollback in achat() OpenAI path
- Add duplicate message prevention for async OpenAI client path
- Add chat history rollback on errors in achat() method
- Ensure consistent behavior between sync and async methods
- Handle edge case where chat_history_length might not be defined

This completes the fix by ensuring both sync and async methods have
identical error handling and duplicate prevention logic.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:10:39 +00:00
claude[bot]andMervin Praison 35b9d46bdf feat: add validation and retry mechanism for AutoAgents config generation
- Add _validate_config method to ensure tasks are proper TaskConfig objects
- Implement retry logic with up to 3 attempts
- Include previous response and error in retry prompt for better context
- Add explicit task structure reminder on validation failures

This ensures more robust configuration generation and better error recovery
when LLMs generate incorrect task formats.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:09:16 +00:00
claude[bot]andMervin Praison 5bd3e45be4 fix: add error handling, duplicate prevention, and multimodal normalization for chat_history
- Add chat history rollback on LLM call failures to prevent inconsistent state
- Prevent duplicate user messages in chat history
- Normalize multimodal prompts to store only text content in chat history
- Add thread safety documentation for future consideration
- Apply fixes to both sync (chat) and async (achat) methods
- Handle all error paths including guardrail failures

This ensures chat_history remains consistent even when errors occur, preventing
unpaired user/assistant messages that could break handoff functionality.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:01:57 +00:00
Mervin Praison 4c62731e81 Merge branch 'main' into claude/issue-795-20250710_222918 2025-07-10 23:56:44 +01:00
Mervin Praison 544672edea Merge pull request #800 from MervinPraison/claude/issue-796-20250710_222402
fix: handle JSON parsing for Gemini self-reflection
2025-07-10 23:51:12 +01:00
Mervin Praison 72dcc91b3a Rename test_gemini_fix.py to gemini_self_reflection.py 2025-07-10 23:50:51 +01:00
claude[bot]andMervin Praison 75e728f7d7 fix: update AutoAgents prompt to generate proper TaskConfig objects
The validation error was occurring because the LLM was generating tasks as simple strings instead of proper TaskConfig objects. This commit updates the prompt in the _generate_config method to:

1. Include an explicit JSON schema example showing the correct structure
2. Add a clear warning that tasks must be objects with specific fields
3. Provide a concrete example of the task object structure

This ensures tasks are generated with the required fields: name, description, expected_output, and tools.

Fixes #798

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 22:44:30 +00:00
claude[bot]andMervin Praison 7ddbf98794 fix: add user message to chat_history before LLM call to fix handoff issue
This fix ensures that handoff tools can access the current user message
during execution. Previously, chat_history was updated after the LLM call,
causing handoffs to fail with "no specific task was provided" message.

The fix adds the user message to chat_history before LLM processing in both:
- Custom LLM path
- Standard OpenAI client path

This maintains backward compatibility while fixing the handoff functionality.

Fixes #795

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 22:36:33 +00:00
Mervin Praison 0213dea12b chore: update PraisonAI version to 2.2.47 in Dockerfiles, README, and related files 2025-07-10 23:30:27 +01:00
claude[bot]andMervin Praison 841a7b52c4 fix: handle JSON parsing for Gemini self-reflection
- Disable streaming for custom LLMs during self-reflection to avoid incomplete JSON chunks
- Add manual JSON parsing for custom LLM reflection responses
- Use clean_json_output method to handle markdown-wrapped JSON
- Ensure reflection regeneration also uses non-streaming for custom LLMs

This fixes the "Expecting property name enclosed in double quotes" error
when using Gemini models with self-reflection enabled.

Fixes #796

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 22:29:42 +00:00
claude[bot]andMervin Praison 99506e80cf fix: replace prefix-based model detection with capability-based detection
- Created model_capabilities.py with comprehensive lists of models supporting structured outputs
- Updated llm.py to use supports_streaming_with_tools() instead of prefix checks
- Updated autoagents.py to use supports_structured_outputs() instead of prefix checks
- Added proper imports/exports in __init__.py
- Maintains backward compatibility for all existing functionality
- More accurate and maintainable approach than hardcoded prefixes

Fixes #792

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 22:21:30 +00:00
Mervin Praison c0d495fd48 Merge pull request #781 from MervinPraison/claude/issue-754-20250709_155906
refactor: eliminate sync/async duplication in llm.py
2025-07-10 23:21:04 +01:00
Mervin Praison 0e51ed0d6c Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-10 23:20:50 +01:00
Mervin Praison 32dce14f96 chore: update version to 0.0.120 in pyproject.toml and uv.lock 2025-07-10 23:20:48 +01:00
Mervin Praison 27aaac80c6 Merge branch 'main' into claude/issue-754-20250709_155906 2025-07-10 23:20:17 +01:00
Mervin Praison 5a0a3983e4 Merge pull request #794 from MervinPraison/claude/pr-791-20250710_214815
PR #791: Changes from Claude
2025-07-10 23:19:03 +01:00
claude[bot]andMervin Praison 400a4c934e fix: properly pass base_url and api_key parameters to OpenAI client and agents
- Create new OpenAIClient instance when custom base_url or api_key are provided
- Pass base_url and api_key to Agent instances for consistency
- Maintain backward compatibility by falling back to singleton client when no custom parameters

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 22:13:29 +00:00
Mervin Praison e88b0fd47b Merge pull request #793 from MervinPraison/claude/issue-754-20250709_155933
refactor: extract debug logging into centralized method
2025-07-10 23:11:57 +01:00
claude[bot]andMervin Praison e6c1c0679f fix: address review comments for debug logging refactor
- Restore backward compatibility for verbose parameter (verbose >= 10 now works)
- Fix condition ordering bug (check "parameters" before "_async")
- Fix API key masking for empty strings
- Add type check for system_prompt truncation
- Add iterable check for tools parameter
- Restore original prompt logging behavior for non-string prompts

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 22:03:01 +00:00
claude[bot]andMervin Praison 108aee0a54 fix: remove duplicate _handle_ollama_model method and fix double tool call processing
- Remove duplicate _handle_ollama_model method definition
- Fix bug where tool calls were processed twice in verbose streaming
- Keep the method with better type hints (Union[str, List[Dict]])
- Remove redundant _process_tool_calls_from_stream calls after _process_stream_delta

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 22:02:58 +00:00
Mervin Praison cb017aad70 Merge branch 'main' into claude/issue-754-20250709_155906 2025-07-10 22:53:33 +01:00
claude[bot]andMervin Praison ea29d3181b fix: properly handle OpenAI client API and store base_url/api_key
- Use OpenAIClient's parse_structured_output method instead of accessing client.beta directly
- Store base_url and api_key as instance variables to support custom endpoints
- This fixes the AttributeError when using AutoAgents with non-OpenAI providers

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 21:50:39 +00:00
claude[bot]andMervin Praison 7f0f265671 refactor: eliminate sync/async duplication in llm.py
- Extract common logic into shared helper methods
- Fix variable reference errors for ollama_params
- Reduce code duplication between get_response/get_response_async
- Reduce code duplication between response/aresponse
- Maintain 100% backward compatibility
- No API changes or breaking changes

Fixes #754

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 21:42:47 +00:00
Mervin Praison bc1c508419 Merge pull request #789 from MervinPraison/claude/issue-787-20250710_205703
fix: prevent double output when using litellm models
2025-07-10 22:37:16 +01:00
Mervin Praison bd108ba3e7 Merge pull request #791 from MervinPraison/claude/issue-788-20250710_210226
fix: add multi-provider support for AutoAgents
2025-07-10 22:34:58 +01:00
claude[bot]andMervin Praison ac5f2649df refactor: resolve merge conflicts with main branch
- Renamed _prepare_ollama_followup to _handle_ollama_model to match main branch
- Updated method signature to (response_text, tool_results, messages, original_prompt)
- Modified return value to dict with follow_up_messages and original_prompt
- Updated all call sites to use the new interface
- Maintained backward compatibility and refactoring benefits

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 21:34:28 +00:00
claude[bot]andMervin Praison 1b64762d54 fix: add verbose checks to all display_interaction calls for consistency
- Applied consistent pattern to all 4 display_interaction calls
- Now all checks follow pattern: if self.verbose and not self._using_custom_llm
- Ensures display is only shown when verbose mode is enabled AND not using custom LLM
- Maintains backward compatibility while fixing the inconsistency

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 21:29:45 +00:00
claude[bot]andMervin Praison df402bcfdb fix: correct indentation error in aresponse method
Fixed incorrect indentation in the async Ollama follow-up handling code
that was causing a syntax error at line 1364.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 21:20:39 +00:00
claude[bot]andMervin Praison 061c8d58b4 fix: add multi-provider support for AutoAgents
- Replace OpenAI-specific beta.chat.completions.parse() with cross-provider LLM class
- Maintain backward compatibility by using structured output for OpenAI models
- Add support for all LiteLLM providers (Gemini, Anthropic, etc.)
- Include robust JSON parsing to handle markdown-wrapped responses
- Fixes #788: AttributeError when using AutoAgent with Gemini provider

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 21:18:52 +00:00
Mervin Praison 117c02cf30 chore: update PraisonAI and related package versions to 2.2.46 and 0.0.119
- Updated PraisonAI version in Dockerfiles and README to 2.2.46
- Updated version in pyproject.toml and uv.lock for PraisonAI and PraisonAI agents to 0.0.119
- Adjusted deployment script to reflect the new PraisonAI version
2025-07-10 22:16:47 +01:00
claude[bot]andMervin Praison 82c9ff80a7 fix: correct indentation error in get_response method
Fixed incorrect indentation in lines 779-804 of the get_response method
that was causing IndentationError. The code block for Ollama follow-up
handling is now properly nested within the if follow_up_prompt block.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 21:15:53 +00:00
Mervin Praison f44b15d73b Merge pull request #782 from MervinPraison/claude/issue-754-20250709_155935
refactor: extract streaming chunk processor to eliminate code duplication
2025-07-10 22:13:29 +01:00
claude[bot]andMervin Praison f2c89c2012 fix: prevent double output when using litellm models
- Check for self._using_custom_llm before calling display_interaction
- Custom LLM already handles display in its get_response method
- Fixes issue #787 where task/response printed twice with litellm

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 21:12:41 +00:00
claude[bot]andMervin Praison f3f5f63b22 refactor: eliminate sync/async duplication in llm.py
- Extract common logic into shared helper methods
- Reduce code duplication between get_response/get_response_async
- Reduce code duplication between response/aresponse
- Maintain 100% backward compatibility
- No API changes or breaking changes

Addresses issue #754

Co-authored-by: Mervin Praison <[email protected]>
2025-07-09 16:07:51 +00:00
claude[bot]andMervin Praison ccf9470f41 refactor: extract debug logging into centralized _log_llm_config method
- Created private _log_llm_config method to handle all debug logging
- Eliminated ~116 lines of duplicated debug logging code
- Maintains 100% backward compatibility (no API changes)
- Centralizes security measures (API key masking)
- Consistent formatting across all logging calls
- No functional changes, only code organization

Addresses code duplication issue #754

Co-authored-by: Mervin Praison <[email protected]>
2025-07-09 16:05:59 +00:00
claude[bot]andMervin Praison d228a742b7 refactor: extract streaming chunk processor to eliminate code duplication
- Add _process_stream_delta() helper method to consolidate duplicate logic
- Refactor 4 duplicated streaming sections (sync/async, verbose/non-verbose)
- Eliminates ~50 lines of duplicated code
- Maintains 100% backward compatibility with no API changes
- Addresses original issue #754 about streaming code duplication

Co-authored-by: Mervin Praison <[email protected]>
2025-07-09 16:03:24 +00:00
191 changed files with 21279 additions and 4511 deletions

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
name: 'Gemini CLI Action'
description: 'Uses the Gemini CLI to automate software development tasks.'
author: 'Gemini'
inputs:
prompt:
description: 'A specific prompt to guide Gemini.'
required: false
default: 'You are a helpful assistant.'
GEMINI_API_KEY:
description: 'Your Gemini API key.'
required: true
OTLP_GCP_WIF_PROVIDER:
description: 'The workload identity provider for GCP authentication.'
required: false
OTLP_GOOGLE_CLOUD_PROJECT:
description: 'The Google Cloud project for telemetry.'
required: false
settings_json:
description: |
A JSON string to configure the Gemini CLI. This will be written to .gemini/settings.json.
To enable observability with Google Cloud, include:
{"telemetry": {"enabled": true, "target": "gcp"}, "sandbox": false}
required: false
version:
description: |
The version of @google/gemini-cli to execute.
Can be a specific version from npm (e.g., '0.1.0', 'latest'), a branch name (e.g., 'main'), or a commit hash.
required: false
default: 'latest'
runs:
using: "composite"
steps:
- name: Configure Gemini CLI
if: inputs.settings_json != ''
run: |
mkdir -p .gemini
echo "$SETTINGS_JSON" > .gemini/settings.json
shell: bash
env:
SETTINGS_JSON: ${{ inputs.settings_json }}
- name: Authenticate to Google Cloud for Telemetry
if: inputs.OTLP_GCP_WIF_PROVIDER != ''
id: auth
uses: 'google-github-actions/auth@v2'
with:
project_id: ${{ inputs.OTLP_GOOGLE_CLOUD_PROJECT }}
workload_identity_provider: ${{ inputs.OTLP_GCP_WIF_PROVIDER }}
- name: Install Gemini CLI
id: install
run: |
if [[ "${{ inputs.version }}" == "latest" || "${{ inputs.version }}" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9\.-]+)?(\+[a-zA-Z0-9\.-]+)?$ ]]; then
echo "Installing Gemini CLI from npm: @google/gemini-cli@${{ inputs.version }}"
npm install -g @google/gemini-cli@${{ inputs.version }}
else
echo "Installing Gemini CLI from GitHub: github:google-gemini/gemini-cli#${{ inputs.version }}"
npm install -g github:google-gemini/gemini-cli#${{ inputs.version }}
fi
echo "Verifying installation:"
if command -v gemini >/dev/null 2>&1; then
gemini --version || echo "Gemini CLI installed successfully (version command not available)"
else
echo "Error: Gemini CLI not found in PATH"
exit 1
fi
shell: bash
- name: Run Gemini CLI
run: |
gemini --yolo --prompt "$PROMPT"
shell: bash
env:
GEMINI_API_KEY: ${{ inputs.GEMINI_API_KEY }}
PROMPT: ${{ inputs.prompt }}
branding:
icon: 'terminal'
color: 'blue'
+26
View File
@@ -0,0 +1,26 @@
name: Auto Issue Comment with PR Creation
on:
issues:
types: [opened]
jobs:
add-comment:
runs-on: ubuntu-latest
permissions:
issues: write
contents: write
pull-requests: write
actions: read
steps:
- name: Add automated comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GH_TOKEN }}
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '@claude review this issue and do a detailed analysis and fix this if the existing code doesn\'t have the solution implemented. Making sure it has backward compatibility, no existing features removed. After making those changes, again review the applied changes. Use @web to search if you dont know any information or to find the latest documentation or to find the latest version. Run the code if you think you need to run it to test it. Minimal code change to start with if required any changes. **Please create a PR using gh tool with your changes**.'
})
+23
View File
@@ -0,0 +1,23 @@
name: Auto PR Comment
on:
pull_request:
types: [opened]
jobs:
add-comment:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- name: Add automated comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GH_TOKEN }}
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '@claude review this pull request and do a detailed analysis and fix this if the existing code doesn\'t have the solution implemented. Making sure it has backward compatibility, no existing features removed. After making those changes, again review the applied changes. Use @web to search if you dont know any information or to find the latest documentation or to find the latest version. Run the code if you think you need to run it to test it. Minimal code change to start with if required any changes.'
})
+142 -20
View File
@@ -1,4 +1,4 @@
name: Claude Code
name: Claude Assistant
on:
issue_comment:
@@ -6,34 +6,156 @@ on:
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
types: [opened, assigned, labeled]
pull_request_review:
types: [submitted]
jobs:
claude:
claude-response:
# Prevent bots from triggering this action
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
github.actor != 'dependabot[bot]' &&
github.actor != 'github-actions[bot]' &&
github.actor != 'cursor[bot]' &&
!contains(github.actor, '[bot]') &&
github.actor != 'renovate[bot]'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
contents: write
pull-requests: write
issues: write
actions: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude Code (OAuth)
id: claude
uses: grll/claude-code-action@beta
fetch-depth: 0
- uses: anthropics/claude-code-action@beta
with:
use_oauth: true
claude_access_token: ${{ secrets.CLAUDE_ACCESS_TOKEN }}
claude_refresh_token: ${{ secrets.CLAUDE_REFRESH_TOKEN }}
claude_expires_at: ${{ secrets.CLAUDE_EXPIRES_AT }}
claude_code_oauth_token: ${{ secrets.CLAUDE_ACCESS_TOKEN }}
github_token: ${{ secrets.GITHUB_TOKEN }}
trigger_phrase: "@claude"
allowed_tools: |
Bash(git:*)
Bash(python:*)
Bash(pip:*)
Bash(conda:*)
Bash(pytest:*)
Bash(gh:*)
Bash(python -m pytest:*)
Bash(python -m pip:*)
Bash(poetry:*)
View
GlobTool
GrepTool
BatchTool
Edit
Replace
mcp__github__get_issue
mcp__github__get_issue_comments
mcp__github__update_issue
timeout_minutes: 30
post-review-comment:
needs: claude-response
if: success() && needs.claude-response.result == 'success'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
issues: write
steps:
- name: Check for existing review comment
id: check-comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GH_TOKEN }}
script: |
const reviewText = '@claude review if the changes made in the above branch are as per the requirements and make changes to the above branch if issues still exist.';
let comments = [];
let issueNumber;
try {
// Determine issue/PR number based on event type
if (context.eventName === 'pull_request_review_comment' || context.eventName === 'pull_request_review') {
issueNumber = context.payload.pull_request?.number || context.issue.number;
} else if (context.eventName === 'issue_comment' && context.payload.issue.pull_request) {
// This is a comment on a PR (not an issue)
issueNumber = context.payload.issue.number;
} else {
// This is a regular issue
issueNumber = context.issue.number;
}
comments = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber
});
// Look for Claude's completed review comments
const claudeReviewComments = comments.data.filter(comment =>
(comment.user.login === 'claude[bot]' || comment.body.includes('✅') || comment.body.includes('## Summary')) &&
!comment.body.includes('⏳') &&
!comment.body.includes('🔄') &&
!comment.body.includes('Loading...')
);
// Check if our review request comment already exists
const existingReviewRequest = comments.data.find(comment =>
comment.body.includes(reviewText)
);
// Post if Claude has completed a review AND we haven't posted the review request yet
const shouldPost = claudeReviewComments.length > 0 && !existingReviewRequest;
core.setOutput('should-post', shouldPost);
console.log(`Claude review completed: ${claudeReviewComments.length > 0}`);
console.log(`Review request exists: ${!!existingReviewRequest}`);
console.log(`Should post comment: ${shouldPost}`);
} catch (error) {
console.log('Error checking comments:', error);
core.setOutput('should-post', false); // If we can't check, don't post
}
- name: Wait 30 seconds before posting comment
if: steps.check-comment.outputs.should-post == 'true'
run: sleep 30
- name: Post review comment
if: steps.check-comment.outputs.should-post == 'true'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GH_TOKEN }}
script: |
let issueNumber;
let isPR = false;
// Determine issue/PR number and type based on event type
if (context.eventName === 'pull_request_review_comment' || context.eventName === 'pull_request_review') {
issueNumber = context.payload.pull_request?.number || context.issue.number;
isPR = true;
} else if (context.eventName === 'issue_comment' && context.payload.issue.pull_request) {
// This is a comment on a PR (not an issue)
issueNumber = context.payload.issue.number;
isPR = true;
} else {
// This is a regular issue - don't post review comment
issueNumber = context.issue.number;
isPR = false;
}
// Only post review comment on PRs, not regular issues
if (isPR) {
console.log(`Posting review comment on PR #${issueNumber}`);
await github.rest.issues.createComment({
issue_number: issueNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: '@claude review if the changes made in the above branch are as per the requirements and make changes to the above branch if issues still exist.'
});
} else {
console.log(`Skipping review comment for regular issue #${issueNumber}`);
}
+1
View File
@@ -40,5 +40,6 @@ jobs:
uses: docker/build-push-action@v2
with:
context: .
file: ./docker/Dockerfile
push: true
tags: ghcr.io/mervinpraison/praisonai:latest
@@ -0,0 +1,76 @@
name: Gemini Automated Issue Triage
on:
issue_comment:
types: [created]
jobs:
triage-issue:
if: >
github.event_name == 'issue_comment' &&
!github.event.issue.pull_request &&
contains(github.event.comment.body, '@gemini triage') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR')
timeout-minutes: 5
permissions:
issues: write
contents: read
id-token: write
concurrency:
group: ${{ github.workflow }}-${{ github.event.issue.number }}
cancel-in-progress: true
runs-on: ubuntu-latest
steps:
- name: Generate GitHub App Token
id: generate_token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ steps.generate_token.outputs.token }}
- name: Run Gemini Issue Triage
uses: google-gemini/gemini-cli-action@main
env:
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
ISSUE_TITLE: ${{ github.event.issue.title }}
ISSUE_BODY: ${{ github.event.issue.body }}
ISSUE_NUMBER: ${{ github.event.issue.number }}
REPOSITORY: ${{ github.repository }}
with:
version: 0.1.8-rc.0
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
OTLP_GCP_WIF_PROVIDER: ${{ secrets.OTLP_GCP_WIF_PROVIDER }}
OTLP_GOOGLE_CLOUD_PROJECT: ${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}
settings_json: |
{
"coreTools": [
"run_shell_command(gh label list)",
"run_shell_command(gh issue edit)"
],
"telemetry": {
"enabled": true,
"target": "gcp"
},
"sandbox": false
}
prompt: |
You are an issue triage assistant. Analyze the current GitHub issue and apply the most appropriate existing labels.
Steps:
1. Run: `gh label list --limit 100` to get all available labels.
2. Review the issue title and body provided in the environment variables.
3. Select the most relevant labels from the existing labels, focusing on kind/*, area/*, and priority/*.
4. Apply the selected labels to this issue using: `gh issue edit ISSUE_NUMBER --add-label "label1,label2"`
Guidelines:
- Only use labels that already exist in the repository.
- Do not add comments or modify the issue content.
- Triage only the current issue.
- Assign all applicable kind/*, area/*, and priority/* labels based on the issue content.
+198
View File
@@ -0,0 +1,198 @@
name: Gemini Issue Review
on:
workflow_dispatch:
issue_comment:
types: [created]
permissions:
contents: write
issues: write
pull-requests: read
jobs:
review-issue:
if: >
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'issue_comment' &&
!github.event.issue.pull_request &&
contains(github.event.comment.body, '@gemini') &&
!contains(github.event.comment.body, '@gemini triage') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR'))
runs-on: ubuntu-latest
env:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
steps:
- name: Generate token
id: generate_token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ steps.generate_token.outputs.token }}
- name: Set up Git
run: |
git config --local user.email "[email protected]"
git config --local user.name "Gemini Bot"
- name: Get issue data
id: issue_data
env:
GH_TOKEN: ${{ steps.generate_token.outputs.token }}
run: |
# Get issue number from event or context
if [ "${{ github.event_name }}" = "issue_comment" ]; then
ISSUE_NUMBER="${{ github.event.issue.number }}"
elif [ "${{ github.event_name }}" = "issues" ]; then
ISSUE_NUMBER="${{ github.event.issue.number }}"
else
echo "Unable to determine issue number"
exit 1
fi
# Get issue details
gh issue view $ISSUE_NUMBER --json title,body,labels,assignees > issue_details.json
# Extract additional instructions from comment if triggered by comment
ADDITIONAL_INSTRUCTIONS=""
if [ "${{ github.event_name }}" = "issue_comment" ]; then
COMMENT_BODY="${{ github.event.comment.body }}"
ADDITIONAL_INSTRUCTIONS=$(echo "$COMMENT_BODY" | sed -n 's/.*@gemini[[:space:]]*\(.*\)/\1/p' | head -1)
fi
echo "ISSUE_NUMBER=$ISSUE_NUMBER" >> $GITHUB_OUTPUT
echo "ADDITIONAL_INSTRUCTIONS=$ADDITIONAL_INSTRUCTIONS" >> $GITHUB_OUTPUT
- name: Run Gemini CLI
uses: ./.github/actions/gemini
env:
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
ISSUE_NUMBER: ${{ steps.issue_data.outputs.ISSUE_NUMBER }}
ADDITIONAL_INSTRUCTIONS: ${{ steps.issue_data.outputs.ADDITIONAL_INSTRUCTIONS }}
REPOSITORY: ${{ github.repository }}
with:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
OTLP_GCP_WIF_PROVIDER: ${{ secrets.OTLP_GCP_WIF_PROVIDER }}
OTLP_GOOGLE_CLOUD_PROJECT: ${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}
prompt: |
You are a helpful GitHub issue assistant. Your task is to analyze and help with GitHub issues.
**Issue Details:**
- Issue Number: #${ISSUE_NUMBER}
- Repository: ${REPOSITORY}
- Issue URL: ${{ github.event.issue.html_url }}
**Additional Instructions:** ${ADDITIONAL_INSTRUCTIONS}
**CRITICAL: When making code modifications, follow this EXACT workflow:**
**STEP 1: Analyze the Issue**
- Use: `gh issue view ${ISSUE_NUMBER} --json title,body,labels,assignees`
- Analyze issue content thoroughly
- Search codebase for related files using `glob`, `search_file_content`, `list_directory`
**STEP 2: If Code Changes Are Needed**
Create a new branch with 'gemini/' prefix:
- Use: `git checkout -b gemini/issue-${ISSUE_NUMBER}-description`
- Example: `git checkout -b gemini/issue-123-fix-sequential-tools`
**STEP 3: Make Code Modifications**
- Use `read_file` to examine existing code
- Use `write_file` or `replace` to make changes
- Use `search_file_content` to find related code
- Make focused, targeted changes to fix the issue
**STEP 4: Test Changes (if applicable)**
- Run relevant tests if test files exist
- Use `run_shell_command` to execute test commands
**STEP 5: Commit and Push Changes**
- Use: `git add .` (or specific files)
- Use: `git commit -m "Gemini: [Issue #${ISSUE_NUMBER}] Brief description of fix"`
- Use: `git push -u origin gemini/issue-${ISSUE_NUMBER}-description`
**STEP 6: Create Pull Request**
- Use: `gh pr create --title "Fix #${ISSUE_NUMBER}: Issue description" --body "Fixes #${ISSUE_NUMBER}\n\nSummary of changes:\n- Change 1\n- Change 2" --head gemini/issue-${ISSUE_NUMBER}-description --base main`
- This will return a PR URL like: https://github.com/repo/pull/123
**STEP 7: Comment on Issue with Results**
Use: `gh issue comment ${ISSUE_NUMBER} -b "MESSAGE"`
**Your final comment MUST include:**
- Summary of what was analyzed
- What changes were made (if any)
- Link to the created PR (if applicable)
- Brief explanation of the solution
**Example final comment:**
```
Hi! I've analyzed and fixed this issue.
**Problem:** Sequential tool calling was getting stuck after first tool call.
**Solution:** Added proper prompt handling after each tool call in the Ollama model integration.
**Changes Made:**
- Modified `src/praisonai-agents/ollama-sequential.py`
- Added continuation prompts for multi-step tool execution
**Pull Request:** https://github.com/MervinPraison/PraisonAI/pull/856
The fix is ready for review. Please test and let me know if you encounter any issues!
```
**IMPORTANT NOTES:**
- Always create branches with 'gemini/' prefix
- Always include issue number in branch name and commit message
- Always create PR that references the issue
- Always provide PR link in your final response
- Use the GITHUB_TOKEN environment variable for authentication
Please proceed with helping resolve this issue following this exact workflow.
settings_json: |
{
"coreTools": [
"run_shell_command(echo)",
"run_shell_command(gh issue view)",
"run_shell_command(gh issue comment)",
"run_shell_command(gh issue list)",
"run_shell_command(gh issue edit)",
"run_shell_command(gh pr create)",
"run_shell_command(gh pr view)",
"run_shell_command(gh pr list)",
"run_shell_command(cat)",
"run_shell_command(head)",
"run_shell_command(tail)",
"run_shell_command(grep)",
"run_shell_command(find)",
"run_shell_command(git checkout)",
"run_shell_command(git add)",
"run_shell_command(git commit)",
"run_shell_command(git push)",
"run_shell_command(git status)",
"run_shell_command(git branch)",
"list_directory",
"read_file",
"read_many_files",
"write_file",
"replace",
"glob",
"search_file_content",
"web_fetch",
"google_web_search",
"save_memory"
],
"telemetry": {
"enabled": false,
"otlpGcpWifProvider": "${{ secrets.OTLP_GCP_WIF_PROVIDER }}",
"googleCloudProject": "${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}"
}
}
+242
View File
@@ -0,0 +1,242 @@
name: Gemini PR Review
on:
issue_comment:
types: [created]
workflow_dispatch:
inputs:
pr_number:
description: 'PR number to review'
required: true
type: number
jobs:
review-pr:
if: >
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
contains(github.event.comment.body, '@gemini') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR'))
timeout-minutes: 15
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
pull-requests: write
issues: write
steps:
- name: Generate GitHub App Token
id: generate_token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
- name: Determine checkout ref
id: checkout_ref
run: |
if [ "${{ github.event_name }}" = "issue_comment" ]; then
echo "ref=refs/pull/${{ github.event.issue.number }}/head" >> "$GITHUB_OUTPUT"
else
echo "ref=${{ github.event.pull_request.head.sha }}" >> "$GITHUB_OUTPUT"
fi
- name: Checkout PR code
uses: actions/checkout@v4
with:
token: ${{ steps.generate_token.outputs.token }}
ref: ${{ steps.checkout_ref.outputs.ref }}
fetch-depth: 0
- name: Get PR details
id: get_pr
env:
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
PR_NUMBER=${{ github.event.inputs.pr_number }}
elif [ "${{ github.event_name }}" = "issue_comment" ]; then
PR_NUMBER=${{ github.event.issue.number }}
else
PR_NUMBER=${{ github.event.pull_request.number }}
fi
echo "pr_number=$PR_NUMBER" >> "$GITHUB_OUTPUT"
# Extract additional instructions from comment (if triggered by comment)
ADDITIONAL_INSTRUCTIONS=""
if [ "${{ github.event_name }}" = "issue_comment" ]; then
COMMENT_BODY="${{ github.event.comment.body }}"
ADDITIONAL_INSTRUCTIONS=$(echo "$COMMENT_BODY" | sed 's/.*@gemini//' | xargs)
fi
echo "additional_instructions=$ADDITIONAL_INSTRUCTIONS" >> "$GITHUB_OUTPUT"
# Get PR details
PR_DATA=$(gh pr view $PR_NUMBER --json title,body,additions,deletions,changedFiles,baseRefName,headRefName)
echo "pr_data=$PR_DATA" >> "$GITHUB_OUTPUT"
# Get file changes
CHANGED_FILES=$(gh pr diff $PR_NUMBER --name-only)
echo "changed_files<<EOF" >> "$GITHUB_OUTPUT"
echo "$CHANGED_FILES" >> "$GITHUB_OUTPUT"
echo "EOF" >> "$GITHUB_OUTPUT"
- name: Run Gemini PR Review
uses: ./.github/actions/gemini
env:
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
PR_NUMBER: ${{ steps.get_pr.outputs.pr_number }}
PR_DATA: ${{ steps.get_pr.outputs.pr_data }}
CHANGED_FILES: ${{ steps.get_pr.outputs.changed_files }}
ADDITIONAL_INSTRUCTIONS: ${{ steps.get_pr.outputs.additional_instructions }}
REPOSITORY: ${{ github.repository }}
with:
version: 0.1.8-rc.0
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
OTLP_GCP_WIF_PROVIDER: ${{ secrets.OTLP_GCP_WIF_PROVIDER }}
OTLP_GOOGLE_CLOUD_PROJECT: ${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}
settings_json: |
{
"coreTools": [
"run_shell_command(echo)",
"run_shell_command(gh pr view)",
"run_shell_command(gh pr diff)",
"run_shell_command(gh pr comment)",
"run_shell_command(gh pr list)",
"run_shell_command(cat)",
"run_shell_command(head)",
"run_shell_command(tail)",
"run_shell_command(grep)",
"run_shell_command(find)",
"run_shell_command(git checkout)",
"run_shell_command(git add)",
"run_shell_command(git commit)",
"run_shell_command(git push)",
"run_shell_command(git status)",
"run_shell_command(git branch)",
"run_shell_command(git fetch)",
"list_directory",
"read_file",
"read_many_files",
"write_file",
"replace",
"glob",
"search_file_content",
"web_fetch",
"google_web_search",
"save_memory"
],
"telemetry": {
"enabled": false,
"target": "gcp"
},
"sandbox": false
}
prompt: |
You are an expert code reviewer and AI assistant for Pull Requests. You can review code AND make modifications to improve the PR.
**PR Details:**
- PR Number: #$PR_NUMBER
- Repository: $REPOSITORY
- Additional Instructions: $ADDITIONAL_INSTRUCTIONS
**CRITICAL: When making code modifications, follow this EXACT workflow:**
**STEP 1: Analyze the PR**
- Use: `echo "$PR_DATA"` to get PR details (JSON format)
- Use: `echo "$CHANGED_FILES"` to get changed files list
- Use: `gh pr diff ${PR_NUMBER}` to see the full diff
- Use: `gh pr view ${PR_NUMBER} --json title,body,headRefName` to get PR info
- Analyze the code changes thoroughly
**STEP 2: If Code Improvements Are Needed**
**IMPORTANT:** DO NOT create a new branch! Work on the EXISTING PR branch.
- Use: `git fetch origin` to get latest changes
- Get PR branch name: `gh pr view ${PR_NUMBER} --json headRefName`
- Switch to PR branch: `git checkout BRANCH_NAME` (use actual branch name from PR)
- Use: `git pull origin BRANCH_NAME` to get latest PR changes
**STEP 3: Make Code Modifications**
- Use `read_file` to examine existing code
- Use `write_file` or `replace` to make improvements
- Use `search_file_content` to find related code
- Make focused, targeted improvements to the PR
**STEP 4: Test Changes (if applicable)**
- Run relevant tests if test files exist
- Use `run_shell_command` to execute test commands
**STEP 5: Commit and Push Changes to EXISTING PR Branch**
- Use: `git add .` (or specific files)
- Use: `git commit -m "Gemini: [PR #${PR_NUMBER}] Brief description of improvements"`
- Use: `git push origin BRANCH_NAME` (push to EXISTING PR branch)
**STEP 6: Review and Comment on PR**
Write comprehensive review and post comment with your analysis and any improvements made.
Use: `gh pr comment ${PR_NUMBER} -b "MESSAGE"`
Review Guidelines:
- Focus on code quality, security, performance, and maintainability
- Check for common issues: potential bugs, security vulnerabilities, performance bottlenecks
- Verify error handling and edge cases
- Look for code style and best practices
- Comment on architecture and design decisions if significant
- Be constructive and specific in feedback
- Highlight both issues and positive aspects
- Suggest improvements with examples when possible
Review Areas:
- **Security**: Authentication, authorization, input validation, data sanitization
- **Performance**: Algorithms, database queries, caching, resource usage
- **Reliability**: Error handling, logging, testing coverage, edge cases
- **Maintainability**: Code structure, documentation, naming conventions
- **Functionality**: Logic correctness, requirements fulfillment
Output Format:
Structure your review using this exact format with markdown:
## 📋 Review Summary
Provide a brief 2-3 sentence overview of the PR and overall assessment.
## 🔍 General Feedback
- List general observations about code quality
- Mention overall patterns or architectural decisions
- Highlight positive aspects of the implementation
- Note any recurring themes across files
## 🎯 Specific Feedback
Only include sections below that have actual issues. If there are no issues in a priority category, omit that entire section.
### 🔴 Critical
(Only include this section if there are critical issues)
Issues that must be addressed before merging (security vulnerabilities, breaking changes, major bugs):
- **File: `filename:line`** - Description of critical issue with specific recommendation
### 🟡 High
(Only include this section if there are high priority issues)
Important issues that should be addressed (performance problems, design flaws, significant bugs):
- **File: `filename:line`** - Description of high priority issue with suggested fix
### 🟢 Medium
(Only include this section if there are medium priority issues)
Improvements that would enhance code quality (style issues, minor optimizations, better practices):
- **File: `filename:line`** - Description of medium priority improvement
### 🔵 Low
(Only include this section if there are suggestions)
Nice-to-have improvements and suggestions (documentation, naming, minor refactoring):
- **File: `filename:line`** - Description of suggestion or enhancement
**Note**: If no specific issues are found in any category, simply state "No specific issues identified in this review."
## ✅ Highlights
(Only include this section if there are positive aspects to highlight)
- Mention specific good practices or implementations
- Acknowledge well-written code sections
- Note improvements from previous versions
---
*Review completed by Gemini CLI*
+2 -2
View File
@@ -151,7 +151,7 @@ jobs:
return 'INVALID_TYPE'
print('🔧 Direct PraisonAI API Key Check:')
env_api_key = os.environ.get(\\"OPENAI_API_KEY\\", \\"NOT_SET\\")
env_api_key = os.environ.get(\"OPENAI_API_KEY\", \"NOT_SET\")
print(f'Environment OPENAI_API_KEY: {get_key_display_value(env_api_key)}...')
from praisonai import PraisonAI
@@ -163,7 +163,7 @@ jobs:
from praisonai.inc.models import PraisonAIModel
print('\\\\n🧪 Testing PraisonAIModel with explicit API key (CrewAI method):')
print('\\n🧪 Testing PraisonAIModel with explicit API key (CrewAI method):')
model_with_explicit_key = PraisonAIModel(
model='openai/gpt-4o-mini',
base_url=praisonai.config_list[0].get('base_url'),
+3 -1
View File
@@ -75,4 +75,6 @@ agents/praisonaiagents/praisonaiagents.egg-info
# Local Netlify folder
.netlify
.qodo
CopilotKit*
CopilotKit*
.gemini
issue_details.json
+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.45" \
"praisonai>=2.2.66" \
"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.45" \
"praisonai>=2.2.66" \
"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.45" \
"praisonai>=2.2.66" \
"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.45" \
"praisonai>=2.2.66" \
"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.45`
- PraisonAI: `>=2.2.66`
- 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.45" "praisonaiagents==0.0.92"
RUN pip install "praisonai==2.2.66" "praisonaiagents==0.0.92"
```
## 🌐 Production Deployment
@@ -0,0 +1,293 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "ZOWgx2fYqW8T"
},
"source": [
"# GitHub Repository Insights with PraisonAIAgents"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XgJdLRiIqZ2L"
},
"source": [
"This notebook demonstrates how to explore and analyze GitHub repositories using PraisonAIAgents in Google Colab. You can query repository issues, pull requests, and activity patterns with natural language, leveraging the power of agentic tools—all without leaving your notebook."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Y_koMT6qzxne"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Programming_Code_Analysis_Agents/GitHub_Repository_Insights.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2ey7zWAJrIPx"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"id": "_xFH-iLTxzd8"
},
"outputs": [],
"source": [
"!pip install praisonaiagents openai requests --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Kzty0zxzsbZ_"
},
"source": [
"# Set Up Key"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"id": "HCVP5fmvx2hH"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Set your GitHub token here\n",
"GITHUB_TOKEN = \"your-github-token\" # <-- Replace with your actual token\n",
"\n",
"# Set your OpenAI API key here (required by PraisonAIAgents, even if not used for LLM)\n",
"OPENAI_API_KEY = \"your-openai-api-key\" # <-- Replace with your actual OpenAI API key\n",
"\n",
"# Set environment variable for OpenAI\n",
"os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "10BTLbF4s_f-"
},
"source": [
"# Import Libraries"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"id": "_sLahvfXyEb0"
},
"outputs": [],
"source": [
"from praisonaiagents import Agent\n",
"import requests\n",
"from IPython.display import display, Markdown"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "GRftdghxtUDs"
},
"source": [
"# Custom Tool"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"id": "nT11EFNNyIHl"
},
"outputs": [],
"source": [
"def github_query_tool(query: str, repo: str, github_token: str) -> str:\n",
" \"\"\"\n",
" Custom tool to query GitHub repository data using the GitHub API.\n",
" Supports basic queries for issues, pull requests, and repository info.\n",
" \"\"\"\n",
" headers = {\n",
" \"Authorization\": f\"token {github_token}\",\n",
" \"Accept\": \"application/vnd.github.v3+json\"\n",
" }\n",
" base_url = f\"https://api.github.com/repos/{repo}\"\n",
" result = \"\"\n",
"\n",
" if \"issue\" in query.lower():\n",
" url = f\"{base_url}/issues\"\n",
" response = requests.get(url, headers=headers)\n",
" if response.ok:\n",
" issues = response.json()\n",
" result = f\"Found {len(issues)} issues in {repo}.\\n\"\n",
" for issue in issues[:5]:\n",
" result += f\"- #{issue['number']}: {issue['title']} (State: {issue['state']})\\n\"\n",
" else:\n",
" result = f\"Failed to fetch issues: {response.text}\"\n",
"\n",
" elif \"pull request\" in query.lower() or \"pr\" in query.lower():\n",
" url = f\"{base_url}/pulls\"\n",
" response = requests.get(url, headers=headers)\n",
" if response.ok:\n",
" pulls = response.json()\n",
" result = f\"Found {len(pulls)} pull requests in {repo}.\\n\"\n",
" for pr in pulls[:5]:\n",
" result += f\"- #{pr['number']}: {pr['title']} (State: {pr['state']})\\n\"\n",
" else:\n",
" result = f\"Failed to fetch pull requests: {response.text}\"\n",
"\n",
" elif \"activity\" in query.lower() or \"stats\" in query.lower():\n",
" url = f\"{base_url}/stats/contributors\"\n",
" response = requests.get(url, headers=headers)\n",
" if response.ok:\n",
" stats = response.json()\n",
" result = f\"Repository activity for {repo}:\\n\"\n",
" for contributor in stats[:5]:\n",
" result += f\"- {contributor['author']['login']}: {contributor['total']} commits\\n\"\n",
" else:\n",
" result = f\"Failed to fetch activity stats: {response.text}\"\n",
"\n",
" else:\n",
" # Default: basic repo info\n",
" response = requests.get(base_url, headers=headers)\n",
" if response.ok:\n",
" info = response.json()\n",
" result = (\n",
" f\"Repository: {info['full_name']}\\n\"\n",
" f\"Description: {info.get('description', 'No description')}\\n\"\n",
" f\"Stars: {info['stargazers_count']}\\n\"\n",
" f\"Forks: {info['forks_count']}\\n\"\n",
" f\"Open Issues: {info['open_issues_count']}\\n\"\n",
" )\n",
" else:\n",
" result = f\"Failed to fetch repository info: {response.text}\"\n",
"\n",
" return result"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "mAFg5SW-tacD"
},
"source": [
"# Register Tool and Create Agent"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"id": "x_MmUc_AyMaB"
},
"outputs": [],
"source": [
"def github_tool_wrapper(inputs):\n",
" query = inputs.get(\"query\", \"\")\n",
" repo = inputs.get(\"repo\", \"\")\n",
" github_token = inputs.get(\"github_token\", \"\")\n",
" return github_query_tool(query, repo, github_token)\n",
"\n",
"agent = Agent(\n",
" instructions=\"\"\"\n",
" You are a GitHub assistant. Help users explore repositories and their activity.\n",
" - Provide organized, concise insights about the repository.\n",
" - Focus on facts and data from the GitHub API.\n",
" - Use markdown formatting for better readability.\n",
" - Present numerical data in tables when appropriate.\n",
" - Include links to relevant GitHub pages when helpful.\n",
" \"\"\",\n",
" tools={\n",
" \"github_query_tool\": github_tool_wrapper\n",
" }\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lPstz7bbtr0k"
},
"source": [
"# User Input and Run Agent"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 118
},
"id": "MymtRmlnyQqd",
"outputId": "33a23810-4a67-4615-f9e9-146b3030fcbf"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the GitHub repository (owner/repo): Dhivya-Bharathy/PraisonAI\n",
"Enter your question (e.g., Show me open issues): Show me open issues\n"
]
},
{
"data": {
"text/markdown": [
"### Results\n",
"Found 0 issues in Dhivya-Bharathy/PraisonAI.\n"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# User input\n",
"repo = input(\"Enter the GitHub repository (owner/repo): \")\n",
"query = input(\"Enter your question (e.g., Show me open issues): \")\n",
"\n",
"# Call the tool directly (since agent.chat expects an LLM, but we want tool output)\n",
"response = agent.execute_tool(\"github_query_tool\", {\n",
" \"query\": query,\n",
" \"repo\": repo,\n",
" \"github_token\": GITHUB_TOKEN\n",
"})\n",
"\n",
"# Display the result\n",
"display(Markdown(f\"### Results\\n{response}\"))"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,309 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "vmQmHoy-5cAh"
},
"source": [
"# Notion Workspace Assistant with PraisonAIAgents"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WOow52NM5dmh"
},
"source": [
"This notebook demonstrates how to interact with your Notion workspace using PraisonAIAgents in Google Colab. You can read, search, and update Notion pages with natural language queries, leveraging agentic tools for seamless document management—all within a notebook environment."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TlnFAv9P_lGL"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Programming_Code_Analysis_Agents/Notion_Workspace_Assistant.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zMn7hUGZ5hn5"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "U6X3lKAu6iU3"
},
"outputs": [],
"source": [
"!pip install praisonaiagents openai requests --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4_96-D7z6lrC"
},
"source": [
"# Set Up Key"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"id": "kltUFVIW6rEO"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Set your Notion and OpenAI API keys here\n",
"NOTION_API_KEY = \"ntn_..\" # <-- Replace with your actual Notion integration token\n",
"OPENAI_API_KEY = \"sk-proj-_..\" # <-- Replace with your actual OpenAI API key\n",
"\n",
"# Set environment variables for downstream libraries\n",
"os.environ[\"NOTION_API_KEY\"] = NOTION_API_KEY\n",
"os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FOLTBEXu635I"
},
"source": [
"# Tools"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "fLWxSASM5jlU"
},
"outputs": [],
"source": [
"from praisonaiagents import Agent\n",
"import requests\n",
"from IPython.display import display, Markdown"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KN_Sxha37EQ0"
},
"source": [
"# Custom Tool"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"id": "WWxcfO9L7Fsu"
},
"outputs": [],
"source": [
"def notion_read_page_tool(page_id: str, notion_token: str) -> str:\n",
" \"\"\"\n",
" Custom tool to read the content of a Notion page using the Notion API.\n",
" \"\"\"\n",
" url = f\"https://api.notion.com/v1/blocks/{page_id}/children\"\n",
" headers = {\n",
" \"Authorization\": f\"Bearer {notion_token}\",\n",
" \"Notion-Version\": \"2022-06-28\"\n",
" }\n",
" response = requests.get(url, headers=headers)\n",
" if response.ok:\n",
" data = response.json()\n",
" blocks = data.get(\"results\", [])\n",
" content = []\n",
" for block in blocks:\n",
" block_type = block.get(\"type\", \"\")\n",
" text = \"\"\n",
" if block_type == \"paragraph\":\n",
" text = block.get(\"paragraph\", {}).get(\"text\", [])\n",
" if text:\n",
" text = text[0].get(\"plain_text\", \"\")\n",
" elif block_type == \"heading_1\":\n",
" text = block.get(\"heading_1\", {}).get(\"text\", [])\n",
" if text:\n",
" text = \"# \" + text[0].get(\"plain_text\", \"\")\n",
" elif block_type == \"heading_2\":\n",
" text = block.get(\"heading_2\", {}).get(\"text\", [])\n",
" if text:\n",
" text = \"## \" + text[0].get(\"plain_text\", \"\")\n",
" elif block_type == \"heading_3\":\n",
" text = block.get(\"heading_3\", {}).get(\"text\", [])\n",
" if text:\n",
" text = \"### \" + text[0].get(\"plain_text\", \"\")\n",
" if text:\n",
" content.append(text)\n",
" return \"\\n\".join(content) if content else \"No readable content found on this page.\"\n",
" else:\n",
" return f\"Failed to fetch page content: {response.text}\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ebuhw9z27Nae"
},
"source": [
"# YAML Prompt"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "eMjDDjzO7Pf3",
"outputId": "b935f96d-f147-44de-80ea-7f75d23f9e7b"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"agent_instructions: |\n",
" You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
" - Provide clear, organized summaries of page content.\n",
" - Use the Notion API to fetch and display information.\n",
" - If a page cannot be read, explain the issue clearly.\n",
"\n",
"tools:\n",
" - name: notion_read_page_tool\n",
" description: >\n",
" Reads the content of a Notion page using its page ID and the user's Notion integration token.\n",
" parameters:\n",
" - name: page_id\n",
" type: string\n",
" description: The Notion page ID to read.\n",
" - name: notion_token\n",
" type: string\n",
" description: The user's Notion integration token.\n",
"\n"
]
}
],
"source": [
"yaml_prompt = \"\"\"\n",
"agent_instructions: |\n",
" You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
" - Provide clear, organized summaries of page content.\n",
" - Use the Notion API to fetch and display information.\n",
" - If a page cannot be read, explain the issue clearly.\n",
"\n",
"tools:\n",
" - name: notion_read_page_tool\n",
" description: >\n",
" Reads the content of a Notion page using its page ID and the user's Notion integration token.\n",
" parameters:\n",
" - name: page_id\n",
" type: string\n",
" description: The Notion page ID to read.\n",
" - name: notion_token\n",
" type: string\n",
" description: The user's Notion integration token.\n",
"\"\"\"\n",
"print(yaml_prompt)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1ozm6Z467WQK"
},
"source": [
"# Main"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 83
},
"id": "eNg-jwpx7X5s",
"outputId": "4440b52a-46b3-4683-9183-13cd21596e25"
},
"outputs": [
{
"data": {
"text/markdown": [
"### Notion Page Content\n",
"*No content found or page is not accessible. Please check your page ID and sharing settings.*"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Define a wrapper to match the agent's expected tool signature\n",
"def notion_tool_wrapper(inputs):\n",
" page_id = inputs.get(\"page_id\", \"\")\n",
" notion_token = inputs.get(\"notion_token\", \"\")\n",
" return notion_read_page_tool(page_id, notion_token)\n",
"\n",
"# Create the agent and register the tool\n",
"agent = Agent(\n",
" instructions=\"\"\"\n",
" You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
" - Provide clear, organized summaries of page content.\n",
" - Use the Notion API to fetch and display information.\n",
" - If a page cannot be read, explain the issue clearly.\n",
" \"\"\",\n",
" tools={\n",
" \"notion_read_page_tool\": notion_tool_wrapper\n",
" }\n",
")\n",
"\n",
"# Call the tool directly (since agent.chat expects an LLM, but we want tool output)\n",
"response = agent.execute_tool(\"notion_read_page_tool\", {\n",
" \"page_id\": page_id,\n",
" \"notion_token\": NOTION_API_KEY\n",
"})\n",
"\n",
"# Check for error pattern and display a friendly message\n",
"if response.startswith(\"Failed to fetch page content:\"):\n",
" display(Markdown(\"### Notion Page Content\\n*No content found or page is not accessible. Please check your page ID and sharing settings.*\"))\n",
"else:\n",
" display(Markdown(f\"### Notion Page Content\\n{response}\"))"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -1,355 +1,355 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "_T4g3t5sLoag"
},
"source": [
"# ZeroScript: AI-Powered Browser Test Automation using PraisonAI Agent & OpenAI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "O4PKfpalLsmn"
},
"source": [
"# Description"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CEG1pfumLysm"
},
"source": [
"AI-powered browser testing using PraisonAI Agent and OpenAI. Executes YAML-defined test cases, captures screenshots, logs interactions, and generates JSON reports. Ideal for intelligent, automated UI testing.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lbgxOG4gL1Wf"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/ZeroScript_AI_TestExecutor.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WCJqMUzXIndh"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"id": "9AQhJ59cJPmR"
},
"outputs": [],
"source": [
"!pip install --quiet praisonaiagents browser-use python-dotenv pyyaml openai\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QD-dF-6_It1z"
},
"source": [
"# Environment Setup"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "QkRQDli4JhCV",
"outputId": "4b8957ed-a37a-4b11-8585-3537a0437d40"
},
"outputs": [
"cells": [
{
"data": {
"text/plain": [
"True"
"cell_type": "markdown",
"metadata": {
"id": "_T4g3t5sLoag"
},
"source": [
"# ZeroScript: AI-Powered Browser Test Automation using PraisonAI Agent & OpenAI"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"Enter your key\" # replace with actual key\n",
"load_dotenv()\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ELuogWnrIw3o"
},
"source": [
"# Create my_secrets.py"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"id": "sG6tO_v0Jm5N"
},
"outputs": [],
"source": [
"with open(\"my_secrets.py\", \"w\") as f:\n",
" f.write('''sensitive_data = {\n",
" \"username\": \"standard_user\",\n",
" \"password\": \"secret_sauce\"\n",
"}''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rDB_viedIzRR"
},
"source": [
"# Create views.py"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"id": "CtwcybdbJoV8"
},
"outputs": [],
"source": [
"with open(\"views.py\", \"w\") as f:\n",
" f.write('''\n",
"from pydantic import BaseModel\n",
"\n",
"class TestResult(BaseModel):\n",
" status: str\n",
" message: str = \"\"\n",
"''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YTRmBpTiI1kd"
},
"source": [
"# Create agent.py"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"id": "zdJJGt6TJpvr"
},
"outputs": [],
"source": [
"with open(\"agent.py\", \"w\") as f:\n",
" f.write('''\n",
"import os\n",
"from praisonaiagents import Agent\n",
"from browser_use import Browser, BrowserConfig, Controller\n",
"from browser_use.browser.context import BrowserContext, BrowserContextConfig\n",
"from openai import OpenAI\n",
"from views import TestResult\n",
"from my_secrets import sensitive_data\n",
"\n",
"# Browser setup\n",
"browser = Browser(config=BrowserConfig(headless=True))\n",
"context_cfg = BrowserContextConfig(save_recording_path=\"data/recordings\")\n",
"controller = Controller(output_model=TestResult)\n",
"\n",
"async def browser_use(task: str):\n",
" context = BrowserContext(browser=browser, config=context_cfg)\n",
" agent = Agent(\n",
" task=task,\n",
" llm=OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"), model=\"gpt-4\"),\n",
" browser_context=context,\n",
" sensitive_data=sensitive_data,\n",
" controller=controller,\n",
" save_conversation_path=\"data/conversations/convo\",\n",
" extend_system_message=(\n",
" \"You are a professional software tester. Execute browser test steps precisely.\"\n",
" )\n",
" )\n",
" response = await agent.run()\n",
" await context.close()\n",
" return response\n",
"''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-LZtQIE3I4-_"
},
"source": [
"# Create Sample Test YAML"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "l1OdXYI-JreK",
"outputId": "62323fcd-c74f-498f-defc-2c170fa8983e"
},
"outputs": [
{
"data": {
"text/plain": [
"350"
"cell_type": "markdown",
"metadata": {
"id": "O4PKfpalLsmn"
},
"source": [
"# Description"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CEG1pfumLysm"
},
"source": [
"AI-powered browser testing using PraisonAI Agent and OpenAI. Executes YAML-defined test cases, captures screenshots, logs interactions, and generates JSON reports. Ideal for intelligent, automated UI testing.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lbgxOG4gL1Wf"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/ZeroScript_AI_TestExecutor.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WCJqMUzXIndh"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"id": "9AQhJ59cJPmR"
},
"outputs": [],
"source": [
"!pip install --quiet praisonaiagents browser-use python-dotenv pyyaml openai\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QD-dF-6_It1z"
},
"source": [
"# Environment Setup"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "QkRQDli4JhCV",
"outputId": "4b8957ed-a37a-4b11-8585-3537a0437d40"
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"Enter your key\" # replace with actual key\n",
"load_dotenv()\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ELuogWnrIw3o"
},
"source": [
"# Create my_secrets.py"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"id": "sG6tO_v0Jm5N"
},
"outputs": [],
"source": [
"with open(\"my_secrets.py\", \"w\") as f:\n",
" f.write('''sensitive_data = {\n",
" \"username\": \"standard_user\",\n",
" \"password\": \"secret_sauce\"\n",
"}''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rDB_viedIzRR"
},
"source": [
"# Create views.py"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"id": "CtwcybdbJoV8"
},
"outputs": [],
"source": [
"with open(\"views.py\", \"w\") as f:\n",
" f.write('''\n",
"from pydantic import BaseModel\n",
"\n",
"class TestResult(BaseModel):\n",
" status: str\n",
" message: str = \"\"\n",
"''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YTRmBpTiI1kd"
},
"source": [
"# Create agent.py"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"id": "zdJJGt6TJpvr"
},
"outputs": [],
"source": [
"with open(\"agent.py\", \"w\") as f:\n",
" f.write('''\n",
"import os\n",
"from praisonaiagents import Agent\n",
"from browser_use import Browser, BrowserConfig, Controller\n",
"from browser_use.browser.context import BrowserContext, BrowserContextConfig\n",
"from openai import OpenAI\n",
"from views import TestResult\n",
"from my_secrets import sensitive_data\n",
"\n",
"# Browser setup\n",
"browser = Browser(config=BrowserConfig(headless=True))\n",
"context_cfg = BrowserContextConfig(save_recording_path=\"data/recordings\")\n",
"controller = Controller(output_model=TestResult)\n",
"\n",
"async def browser_use(task: str):\n",
" context = BrowserContext(browser=browser, config=context_cfg)\n",
" agent = Agent(\n",
" task=task,\n",
" llm=OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"), model=\"gpt-4\"),\n",
" browser_context=context,\n",
" sensitive_data=sensitive_data,\n",
" controller=controller,\n",
" save_conversation_path=\"data/conversations/convo\",\n",
" extend_system_message=(\n",
" \"You are a professional software tester. Execute browser test steps precisely.\"\n",
" )\n",
" )\n",
" response = await agent.run()\n",
" await context.close()\n",
" return response\n",
"''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-LZtQIE3I4-_"
},
"source": [
"# Create Sample Test YAML"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "l1OdXYI-JreK",
"outputId": "62323fcd-c74f-498f-defc-2c170fa8983e"
},
"outputs": [
{
"data": {
"text/plain": [
"350"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from pathlib import Path\n",
"tests_dir = Path(\"tests\")\n",
"tests_dir.mkdir(exist_ok=True)\n",
"yaml_content = \"\"\"\n",
"hooks:\n",
" beforeEach: |\n",
" Navigate to https://www.saucedemo.com\n",
" afterEach: |\n",
" Take screenshot\n",
"\n",
"tests:\n",
" - id: \"login_test_001\"\n",
" name: \"Valid Login Test\"\n",
" instructions: |\n",
" 1. Enter standard_user in username field\n",
" 2. Enter secret_sauce in password field\n",
" 3. Click login button\n",
" 4. Verify page contains text \"Products\"\n",
"\"\"\"\n",
"(Path(\"tests/login_test.yml\")).write_text(yaml_content)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sUjy-7OdI7p_"
},
"source": [
"# Run Tests"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Agkiwh7xJtY3",
"outputId": "759aa77c-fd65-49b8-b239-550588059478"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Exception ignored in: <function BrowserSession.__del__ at 0x7e2f540fb100>\n",
"Traceback (most recent call last):\n",
" File \"/usr/local/lib/python3.11/dist-packages/browser_use/browser/session.py\", line 497, in __del__\n",
" status = f'\ud83e\ude93 killing pid={self.browser_pid}...' if (self.browser_pid and owns_browser) else '\u2620\ufe0f'\n",
" ^^^^^^^^^^^^^^^^\n",
" File \"/usr/local/lib/python3.11/dist-packages/pydantic/main.py\", line 991, in __getattr__\n",
" raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')\n",
"AttributeError: 'BrowserSession' object has no attribute 'browser_pid'\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u2705 Report saved to data/reports/report_20250630_092319.json\n"
]
}
],
"source": [
"import asyncio, yaml, json, base64, shutil\n",
"from agent import browser_use, browser\n",
"from pathlib import Path\n",
"from datetime import datetime\n",
"\n",
"# Clean or create data dirs\n",
"for sub in [\"recordings\", \"conversations\", \"screenshots\", \"reports\"]:\n",
" d = Path(\"data\") / sub\n",
" if d.exists(): shutil.rmtree(d)\n",
" d.mkdir(parents=True, exist_ok=True)\n",
"\n",
"async def execute_test_file(path):\n",
" cfg = yaml.safe_load(Path(path).read_text())\n",
" hooks, results = cfg.get(\"hooks\", {}), []\n",
" for t in cfg[\"tests\"]:\n",
" task = f\"{hooks.get('beforeEach','')}\\n{t['instructions']}\\n{hooks.get('afterEach','')}\"\n",
" res = {\"id\": t[\"id\"], \"name\": t[\"name\"]}\n",
" try:\n",
" r = await browser_use(task)\n",
" imgs = r.screenshots()\n",
" if imgs:\n",
" out = Path(\"data/screenshots\") / f\"{t['id']}.png\"\n",
" out.write_bytes(base64.b64decode(imgs[-1]))\n",
" result_obj = r.final_result() if hasattr(r, \"final_result\") else str(r)\n",
" res[\"result\"] = result_obj.model_dump() if hasattr(result_obj, \"model_dump\") else str(result_obj)\n",
" except Exception as e:\n",
" res[\"error\"] = str(e)\n",
" results.append(res)\n",
" return results\n",
"\n",
"async def main():\n",
" all_results = []\n",
" for file in Path(\"tests\").glob(\"*.yml\"):\n",
" all_results.extend(await execute_test_file(str(file)))\n",
" report = Path(\"data/reports\") / f\"report_{datetime.now():%Y%m%d_%H%M%S}.json\"\n",
" report.write_text(json.dumps(all_results, indent=2))\n",
" await browser.close()\n",
" print(f\"\u2705 Report saved to {report}\")\n",
"\n",
"await main()\n"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from pathlib import Path\n",
"tests_dir = Path(\"tests\")\n",
"tests_dir.mkdir(exist_ok=True)\n",
"yaml_content = \"\"\"\n",
"hooks:\n",
" beforeEach: |\n",
" Navigate to https://www.saucedemo.com\n",
" afterEach: |\n",
" Take screenshot\n",
"\n",
"tests:\n",
" - id: \"login_test_001\"\n",
" name: \"Valid Login Test\"\n",
" instructions: |\n",
" 1. Enter standard_user in username field\n",
" 2. Enter secret_sauce in password field\n",
" 3. Click login button\n",
" 4. Verify page contains text \"Products\"\n",
"\"\"\"\n",
"(Path(\"tests/login_test.yml\")).write_text(yaml_content)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sUjy-7OdI7p_"
},
"source": [
"# Run Tests"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
"provenance": []
},
"id": "Agkiwh7xJtY3",
"outputId": "759aa77c-fd65-49b8-b239-550588059478"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Exception ignored in: <function BrowserSession.__del__ at 0x7e2f540fb100>\n",
"Traceback (most recent call last):\n",
" File \"/usr/local/lib/python3.11/dist-packages/browser_use/browser/session.py\", line 497, in __del__\n",
" status = f'🪓 killing pid={self.browser_pid}...' if (self.browser_pid and owns_browser) else '☠️'\n",
" ^^^^^^^^^^^^^^^^\n",
" File \"/usr/local/lib/python3.11/dist-packages/pydantic/main.py\", line 991, in __getattr__\n",
" raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')\n",
"AttributeError: 'BrowserSession' object has no attribute 'browser_pid'\n"
]
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Report saved to data/reports/report_20250630_092319.json\n"
]
"language_info": {
"name": "python"
}
],
"source": [
"import asyncio, yaml, json, base64, shutil\n",
"from agent import browser_use, browser\n",
"from pathlib import Path\n",
"from datetime import datetime\n",
"\n",
"# Clean or create data dirs\n",
"for sub in [\"recordings\", \"conversations\", \"screenshots\", \"reports\"]:\n",
" d = Path(\"data\") / sub\n",
" if d.exists(): shutil.rmtree(d)\n",
" d.mkdir(parents=True, exist_ok=True)\n",
"\n",
"async def execute_test_file(path):\n",
" cfg = yaml.safe_load(Path(path).read_text())\n",
" hooks, results = cfg.get(\"hooks\", {}), []\n",
" for t in cfg[\"tests\"]:\n",
" task = f\"{hooks.get('beforeEach','')}\\n{t['instructions']}\\n{hooks.get('afterEach','')}\"\n",
" res = {\"id\": t[\"id\"], \"name\": t[\"name\"]}\n",
" try:\n",
" r = await browser_use(task)\n",
" imgs = r.screenshots()\n",
" if imgs:\n",
" out = Path(\"data/screenshots\") / f\"{t['id']}.png\"\n",
" out.write_bytes(base64.b64decode(imgs[-1]))\n",
" result_obj = r.final_result() if hasattr(r, \"final_result\") else str(r)\n",
" res[\"result\"] = result_obj.dict() if hasattr(result_obj, \"dict\") else str(result_obj)\n",
" except Exception as e:\n",
" res[\"error\"] = str(e)\n",
" results.append(res)\n",
" return results\n",
"\n",
"async def main():\n",
" all_results = []\n",
" for file in Path(\"tests\").glob(\"*.yml\"):\n",
" all_results.extend(await execute_test_file(str(file)))\n",
" report = Path(\"data/reports\") / f\"report_{datetime.now():%Y%m%d_%H%M%S}.json\"\n",
" report.write_text(json.dumps(all_results, indent=2))\n",
" await browser.close()\n",
" print(f\"✅ Report saved to {report}\")\n",
"\n",
"await main()\n"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
"nbformat": 4,
"nbformat_minor": 0
}
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""
Fixed example demonstrating proper guardrail usage with PraisonAI Agents.
This addresses the issues reported in issue #875.
"""
from praisonaiagents import Agent, Task, GuardrailResult, PraisonAIAgents, TaskOutput
from typing import Tuple, Any
import trafilatura
# Example 1: Using GuardrailResult return type (now supported!)
def validate_length_guardrailresult(output: TaskOutput) -> GuardrailResult:
"""Ensure output is between 100-500 characters using GuardrailResult"""
# Extract the raw text from the TaskOutput object
text = output.raw if hasattr(output, 'raw') else str(output)
length = len(text)
if 100 <= length <= 500:
return GuardrailResult(
success=True,
result=output, # Pass through the original output
error=""
)
else:
return GuardrailResult(
success=False,
result=None,
error=f"Output must be 100-500 chars, got {length}"
)
# Example 2: Using Tuple[bool, Any] return type (original method)
def validate_length_tuple(output: TaskOutput) -> Tuple[bool, Any]:
"""Ensure output is between 100-500 characters using tuple"""
text = output.raw if hasattr(output, 'raw') else str(output)
length = len(text)
if 100 <= length <= 500:
return True, output
else:
return False, f"Output must be 100-500 chars, got {length}"
# Tool function
def get_url_context(url):
"""Fetch and extract content from a URL"""
downloaded = trafilatura.fetch_url(url)
if not downloaded:
return "Sorry, I couldn't fetch the content from that URL."
extracted = trafilatura.extract(
downloaded,
include_comments=False,
include_links=True,
output_format='json',
with_metadata=True,
url=url
)
if not extracted:
return "Sorry, I couldn't extract readable content from that page."
return extracted # returns JSON string
# Create agent with FIXED tools parameter (must be a list!)
agent = Agent(
name="Content Summarizer",
role="Content Analysis Expert",
goal="Summarize web content concisely",
instructions="You are a helpful assistant that summarizes web content",
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
self_reflect=False,
verbose=True,
tools=[get_url_context] # FIX: tools must be a list, not a single function
)
# Create task with GuardrailResult guardrail
task_with_guardrailresult = Task(
name="summarise article with GuardrailResult",
description="get the context of this url: https://blog.google/technology/ai/dolphingemma/ and produce a summary below 500 characters",
agent=agent,
guardrail=validate_length_guardrailresult, # Using GuardrailResult
expected_output="summary of the article below 500 characters",
max_retries=3 # Will retry up to 3 times if guardrail fails
)
# Alternative: Create task with tuple guardrail
task_with_tuple = Task(
name="summarise article with tuple",
description="get the context of this url: https://blog.google/technology/ai/dolphingemma/ and produce a summary below 500 characters",
agent=agent,
guardrail=validate_length_tuple, # Using Tuple[bool, Any]
expected_output="summary of the article below 500 characters",
max_retries=3
)
# Example with string-based LLM guardrail
task_with_llm_guardrail = Task(
name="summarise with LLM guardrail",
description="get the context of this url: https://blog.google/technology/ai/dolphingemma/ and produce a summary",
agent=agent,
guardrail="Ensure the summary is professional, factual, and between 100-500 characters",
expected_output="professional summary of the article"
)
# Run with GuardrailResult example
print("=== Running with GuardrailResult guardrail ===")
agents_gr = PraisonAIAgents(
agents=[agent],
tasks=[task_with_guardrailresult]
)
# Uncomment to run:
# result_gr = agents_gr.start()
# Run with Tuple example
print("\n=== Running with Tuple[bool, Any] guardrail ===")
agents_tuple = PraisonAIAgents(
agents=[agent],
tasks=[task_with_tuple]
)
# Uncomment to run:
# result_tuple = agents_tuple.start()
# Run with LLM guardrail example
print("\n=== Running with LLM-based guardrail ===")
agents_llm = PraisonAIAgents(
agents=[agent],
tasks=[task_with_llm_guardrail]
)
# Uncomment to run:
# result_llm = agents_llm.start()
print("""
Key fixes applied:
1. GuardrailResult is now accepted as a valid return type annotation
2. tools parameter must be a list: tools=[get_url_context] not tools=get_url_context
3. Both GuardrailResult and Tuple[bool, Any] return types are supported
4. String-based LLM guardrails are also supported
The guardrail will automatically retry (up to max_retries times) if validation fails.
""")
@@ -0,0 +1,259 @@
# Multi-Provider/Multi-Model Support
PraisonAI now supports intelligent multi-provider and multi-model capabilities, allowing agents to automatically select the most appropriate AI model based on task requirements, cost considerations, and performance needs.
## 🚀 Key Features
### 1. **Automatic Model Selection**
- Analyzes task complexity and selects the best model
- Considers cost vs. performance trade-offs
- Supports fallback mechanisms for reliability
### 2. **Cost Optimization**
- Routes simple tasks to cheaper models (e.g., GPT-4o-mini, Gemini Flash)
- Reserves expensive models for complex tasks
- Tracks usage and provides cost estimates
### 3. **Multi-Provider Support**
- Works with OpenAI, Anthropic, Google, Groq, and more
- Seamless switching between providers
- Provider preference settings
### 4. **Flexible Routing Strategies**
- `auto`: Automatic selection based on task analysis
- `cost-optimized`: Prioritize cheaper models
- `performance-optimized`: Prioritize capability
- `manual`: Use specified model
## 📦 Installation
The multi-provider support is included in the standard installation:
```bash
pip install praisonaiagents
```
## 🔧 Basic Usage
### Simple Multi-Model Agent
```python
from praisonaiagents import Task, PraisonAIAgents
from praisonaiagents.agent import RouterAgent
# Create a multi-model agent
agent = RouterAgent(
name="Smart Assistant",
role="Adaptive AI Assistant",
goal="Complete tasks using the most appropriate model",
models=["gpt-4o-mini", "gpt-4o", "claude-3-5-sonnet-20241022"],
routing_strategy="auto" # Automatic model selection
)
# Create tasks
simple_task = Task(
name="calculate",
description="What is 15% of 250?",
agent=agent
)
complex_task = Task(
name="analyze",
description="Write a Python implementation of the A* pathfinding algorithm",
agent=agent
)
# Run tasks - agent will automatically select appropriate models
agents = PraisonAIAgents(
agents=[agent],
tasks=[simple_task, complex_task]
)
results = agents.start()
```
### Cost-Optimized Workflow
```python
from praisonaiagents.llm import ModelRouter
# Create custom router with cost constraints
router = ModelRouter(
cost_threshold=0.005, # Max $0.005 per 1k tokens
preferred_providers=["google", "openai"]
)
# Create cost-conscious agent
analyzer = RouterAgent(
name="Budget Analyzer",
role="Data Analyst",
goal="Analyze data efficiently",
models={
"gemini/gemini-1.5-flash": {},
"gpt-4o-mini": {},
"claude-3-haiku-20240307": {}
},
model_router=router,
routing_strategy="cost-optimized"
)
```
## 🎯 Routing Strategies
### Auto Routing (Default)
Automatically selects models based on:
- Task complexity analysis
- Required capabilities (tools, vision, etc.)
- Context size requirements
- Cost/performance balance
### Cost-Optimized
Prioritizes cheaper models while meeting task requirements:
- Uses lightweight models for simple tasks
- Only escalates to expensive models when necessary
- Ideal for high-volume operations
### Performance-Optimized
Prioritizes model capability:
- Uses the best available model for the task
- Ideal for quality-critical applications
- Less concern for cost
### Manual
Uses the specified model without routing:
- Direct control over model selection
- Useful for testing or specific requirements
## 📊 Model Profiles
The system includes pre-configured profiles for popular models:
| Model | Provider | Best For | Cost/1k tokens |
|-------|----------|----------|----------------|
| gpt-4o-mini | OpenAI | Simple tasks, speed | $0.00075 |
| gemini-1.5-flash | Google | Cost-effective, multimodal | $0.000125 |
| claude-3-haiku | Anthropic | Fast responses | $0.0008 |
| gpt-4o | OpenAI | General purpose | $0.0075 |
| claude-3-5-sonnet-20241022 | Anthropic | Complex reasoning | $0.009 |
| deepseek-chat | DeepSeek | Code & math | $0.0014 |
## 🔍 Task Complexity Analysis
The system analyzes tasks to determine complexity:
- **Simple**: Basic calculations, definitions, yes/no questions
- **Moderate**: Summarization, basic analysis, classification
- **Complex**: Code generation, algorithm implementation
- **Very Complex**: Multi-step reasoning, system design
## 📈 Usage Tracking
Track model usage and costs:
```python
# Get usage report
report = agent.get_usage_report()
print(report)
# Output:
{
'agent_name': 'Smart Assistant',
'routing_strategy': 'auto',
'model_usage': {
'gpt-4o-mini': {'calls': 5, 'tokens': 1500, 'cost': 0.0011},
'gpt-4o': {'calls': 2, 'tokens': 3000, 'cost': 0.0225}
},
'total_cost_estimate': 0.0236,
'total_calls': 7
}
```
## 🛠️ Custom Model Configuration
Add custom model profiles:
```python
from praisonaiagents.llm import ModelProfile, TaskComplexity
custom_model = ModelProfile(
name="custom-model",
provider="custom",
complexity_range=(TaskComplexity.SIMPLE, TaskComplexity.MODERATE),
cost_per_1k_tokens=0.002,
strengths=["domain-specific"],
capabilities=["text"],
context_window=32000
)
router = ModelRouter(models=[custom_model])
```
## 🔗 Integration with AutoAgents
Works seamlessly with AutoAgents:
```python
from praisonaiagents.agents import AutoAgents
# Create auto agents
auto = AutoAgents(
instructions="Analyze market trends and create a report",
max_agents=3
)
# Convert to multi-model agents
for i, agent in enumerate(auto.agents):
auto.agents[i] = RouterAgent(
name=agent.name,
role=agent.role,
goal=agent.goal,
models=["gpt-4o-mini", "gpt-4o", "claude-3-5-sonnet"],
routing_strategy="auto"
)
results = auto.start()
```
## 🌟 Best Practices
1. **Start with Auto Routing**: Let the system learn your needs
2. **Monitor Costs**: Use usage reports to optimize
3. **Set Cost Thresholds**: Prevent unexpected expenses
4. **Use Appropriate Models**: Don't use GPT-4 for simple math
5. **Leverage Fallbacks**: Configure fallback models for reliability
## 🔐 Environment Variables
Set API keys for each provider:
```bash
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export GEMINI_API_KEY="..."
export GROQ_API_KEY="..."
```
## 🤝 Contributing
The multi-provider system is extensible. To add new models:
1. Add model profile to `ModelRouter.DEFAULT_MODELS`
2. Ensure the provider is supported by LiteLLM
3. Test with various task complexities
## 📚 Examples
See the complete example in `examples/python/agents/multi-provider-agent.py` for:
- Auto-routing examples
- Cost-optimized workflows
- Performance-optimized agents
- Custom routing logic
- Integration patterns
## 🎉 Benefits
- **Cost Savings**: Reduce API costs by 50-80%
- **Better Performance**: Use the right tool for each job
- **Flexibility**: Switch providers without code changes
- **Reliability**: Automatic fallbacks and error handling
- **Transparency**: Track usage and costs
@@ -0,0 +1,73 @@
"""
AutoAgents Hierarchical Generation Example
This example demonstrates hierarchical agent patterns using PraisonAI
for structured task delegation and coordinated workflows.
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import internet_search
print("=== AutoAgents Hierarchical Generation Example ===\n")
# Create manager agent for hierarchical coordination
manager_agent = Agent(
name="Project Manager",
role="Project Coordinator",
goal="Coordinate hierarchical task execution and manage team workflow",
backstory="Experienced manager who excels at breaking down complex projects and coordinating teams",
tools=[internet_search],
allow_delegation=True,
verbose=True
)
# Create specialist agent for execution
research_agent = Agent(
name="Research Specialist",
role="Market Research Analyst",
goal="Conduct thorough market research and analysis",
backstory="Expert researcher skilled in market analysis and competitive intelligence",
tools=[internet_search],
verbose=True
)
# Hierarchical task structure
planning_task = Task(
description="""Plan a comprehensive market research project for electric vehicles:
1. Define research scope and objectives
2. Identify key research areas and methodologies
3. Create task breakdown structure
4. Set deliverable requirements for execution team
Prepare clear instructions for the research specialist.""",
expected_output="Detailed project plan with clear research instructions",
agent=manager_agent
)
execution_task = Task(
description="""Execute the market research plan:
1. Follow the research plan from the project manager
2. Conduct comprehensive market analysis
3. Gather competitive intelligence and market data
4. Prepare detailed findings report
Use the planning guidance to ensure complete coverage.""",
expected_output="Comprehensive market research report with findings",
agent=research_agent,
context=[planning_task]
)
# Run hierarchical workflow
agents_system = PraisonAIAgents(
agents=[manager_agent, research_agent],
tasks=[planning_task, execution_task],
process="sequential",
verbose=True
)
print("Starting hierarchical agent generation...")
result = agents_system.start()
print(f"\nHierarchical Result: {result[:200]}...")
print("\n✅ AutoAgents hierarchical generation complete!")
print("Demonstrated coordinated hierarchical workflow between manager and specialist agents.")
@@ -0,0 +1,285 @@
"""
Multi-Provider/Multi-Model Agent Example
This example demonstrates how to use multiple AI providers/models with intelligent
agent-based selection for cost optimization and performance.
"""
import os
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.agent import RouterAgent
from praisonaiagents.llm.model_router import ModelRouter, ModelProfile, TaskComplexity
# Example 1: Simple Multi-Model Agent with Auto-Routing
def example_auto_routing():
"""Example of automatic model routing based on task complexity"""
print("\n=== Example 1: Auto-Routing Multi-Model Agent ===\n")
# Create a router agent that automatically selects models
research_agent = RouterAgent(
name="Smart Researcher",
role="Adaptive Research Assistant",
goal="Research topics using the most appropriate AI model",
backstory="I analyze task complexity and route to the best model",
models=["gpt-4o-mini", "gpt-4o", "claude-3-5-sonnet-20241022"],
routing_strategy="auto", # Automatic model selection
verbose=True
)
# Create tasks with different complexity levels
simple_task = Task(
name="simple_calculation",
description="Calculate the sum of 1542 and 2873",
expected_output="The numerical result",
agent=research_agent
)
moderate_task = Task(
name="summarize_article",
description="Summarize the key points about renewable energy trends",
expected_output="A concise summary with main points",
agent=research_agent
)
complex_task = Task(
name="analyze_code",
description="Implement a Python function to find the longest palindromic substring in a given string with O(n^2) complexity",
expected_output="Complete Python implementation with explanation",
agent=research_agent
)
# Run the tasks
agents = PraisonAIAgents(
agents=[research_agent],
tasks=[simple_task, moderate_task, complex_task],
process="sequential",
verbose=True
)
results = agents.start()
# Show usage report
print("\n=== Model Usage Report ===")
print(research_agent.get_usage_report())
# Example 2: Cost-Optimized Workflow with Routing
def example_cost_optimized_workflow():
"""Example of cost-optimized workflow with model routing"""
print("\n=== Example 2: Cost-Optimized Workflow ===\n")
# Create custom model router with cost threshold
cost_router = ModelRouter(
cost_threshold=0.01, # Max $0.01 per 1k tokens
preferred_providers=["google", "openai", "anthropic"] # Provider preference
)
# Create specialized agents with different model strategies
analyzer = RouterAgent(
name="Cost-Conscious Analyzer",
role="Data Analyzer",
goal="Analyze data efficiently while minimizing costs",
models={
"gemini/gemini-1.5-flash": {},
"gpt-4o-mini": {},
"deepseek-chat": {}
},
model_router=cost_router,
routing_strategy="cost-optimized",
verbose=True
)
writer = RouterAgent(
name="Quality Writer",
role="Content Writer",
goal="Create high-quality content",
models={
"claude-3-5-sonnet-20241022": {},
"gpt-4o": {}
},
routing_strategy="performance-optimized", # Prefer better models
verbose=True
)
# Create workflow tasks
analysis_task = Task(
name="analyze_data",
description="Analyze this dataset: [1, 2, 3, 4, 5]. Find mean, median, and mode.",
expected_output="Statistical analysis results",
agent=analyzer
)
writing_task = Task(
name="write_report",
description="Write a professional report based on the analysis",
expected_output="Professional report with insights",
agent=writer,
context=[analysis_task] # Use results from analysis
)
# Run workflow
workflow = PraisonAIAgents(
agents=[analyzer, writer],
tasks=[analysis_task, writing_task],
process="sequential",
verbose=True
)
results = workflow.start()
# Show cost comparison
print("\n=== Cost Analysis ===")
print(f"Analyzer costs: {analyzer.get_usage_report()}")
print(f"Writer costs: {writer.get_usage_report()}")
# Example 3: Auto Agent Mode with Multi-Provider Support
def example_auto_agents_multi_provider():
"""Example using AutoAgents with multi-provider support"""
print("\n=== Example 3: AutoAgents with Multi-Provider Support ===\n")
from praisonaiagents.agents import AutoAgents
# Create AutoAgents that will automatically assign appropriate models
auto_agents = AutoAgents(
instructions="Create a market research report on electric vehicles. Include data analysis, competitor analysis, and future projections.",
max_agents=3,
llm="gpt-4o-mini", # Default model for agent generation
verbose=True
)
# After agents are created, upgrade them to multi-model agents
multi_model_agents = []
for agent in auto_agents.agents:
# Convert regular agents to multi-model agents
multi_agent = RouterAgent(
name=agent.name,
role=agent.role,
goal=agent.goal,
backstory=agent.backstory,
tools=agent.tools,
models=["gpt-4o-mini", "gemini/gemini-1.5-flash", "claude-3-haiku-20240307", "gpt-4o"],
routing_strategy="auto",
verbose=True
)
multi_model_agents.append(multi_agent)
# Update the agents in the AutoAgents instance
auto_agents.agents = multi_model_agents
# Run the auto-generated workflow
results = auto_agents.start()
# Show model usage across all agents
print("\n=== Multi-Provider Usage Summary ===")
total_calls = 0
for agent in multi_model_agents:
report = agent.get_usage_report()
print(f"\nAgent: {agent.name}")
for model, stats in report['model_usage'].items():
if stats['calls'] > 0:
print(f" - {model}: {stats['calls']} calls")
total_calls += stats['calls']
print(f"\nTotal API calls: {total_calls}")
# Example 4: Custom Routing Logic
def example_custom_routing():
"""Example with custom routing logic based on specific requirements"""
print("\n=== Example 4: Custom Routing Logic ===\n")
# Create custom model profiles for specific use cases
custom_models = [
ModelProfile(
name="gpt-4o",
provider="openai",
complexity_range=(TaskComplexity.SIMPLE, TaskComplexity.VERY_COMPLEX),
cost_per_1k_tokens=0.0075,
strengths=["code-generation", "debugging"],
capabilities=["text", "function-calling"],
context_window=128000
),
ModelProfile(
name="deepseek-chat",
provider="deepseek",
complexity_range=(TaskComplexity.MODERATE, TaskComplexity.VERY_COMPLEX),
cost_per_1k_tokens=0.001,
strengths=["mathematics", "algorithms"],
capabilities=["text", "function-calling"],
context_window=128000
)
]
# Create router with custom models
custom_router = ModelRouter(models=custom_models)
# Tool for web search (example)
def search_web(query: str) -> str:
"""Search the web for information"""
return f"Search results for: {query}"
# Create specialized agent
coder = RouterAgent(
name="Adaptive Coder",
role="Software Developer",
goal="Write and debug code using the best model for each task",
backstory="I'm an expert coder who knows when to use different AI models",
model_router=custom_router,
routing_strategy="auto",
tools=[search_web],
verbose=True
)
# Create coding tasks
tasks = [
Task(
name="fix_bug",
description="Fix this Python bug: 'list' object has no attribute 'appendx'",
expected_output="Corrected code with explanation",
agent=coder
),
Task(
name="implement_algorithm",
description="Implement Dijkstra's shortest path algorithm in Python",
expected_output="Complete implementation with comments",
agent=coder,
tools=[search_web]
)
]
# Run tasks
agents = PraisonAIAgents(
agents=[coder],
tasks=tasks,
process="sequential",
verbose=True
)
results = agents.start()
print("\n=== Custom Routing Results ===")
print(coder.get_usage_report())
# Run examples
if __name__ == "__main__":
# Make sure to set your API keys
# os.environ["OPENAI_API_KEY"] = "your-openai-key"
# os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-key"
# os.environ["GEMINI_API_KEY"] = "your-gemini-key"
# Run examples
example_auto_routing()
example_cost_optimized_workflow()
example_auto_agents_multi_provider()
example_custom_routing()
print("\n=== All Examples Completed ===")
print("\nKey Features Demonstrated:")
print("1. Automatic model selection based on task complexity")
print("2. Cost-optimized routing for budget-conscious operations")
print("3. Performance-optimized routing for quality-critical tasks")
print("4. Multi-provider support with fallback mechanisms")
print("5. Integration with AutoAgents for automatic workflow generation")
print("6. Custom routing logic for specialized use cases")
@@ -0,0 +1,82 @@
"""
RouterAgent Cost Optimization Example
This example demonstrates how to use RouterAgent for intelligent model selection
based on cost optimization. The router agent automatically selects the most
cost-effective model for different types of tasks while maintaining quality.
Features demonstrated:
- Cost-optimized model routing
- Automatic model selection based on task complexity
- Usage tracking and cost monitoring
- Fallback mechanisms for reliability
"""
from praisonaiagents import Agent
from praisonaiagents.agent.router_agent import RouterAgent
from praisonaiagents.tools import duckduckgo
# Define model options with cost considerations
# Using different models for different complexity levels
cheap_model = "gpt-4o-mini" # For simple tasks
balanced_model = "gpt-4o" # For moderate complexity
premium_model = "claude-3-5-sonnet-20241022" # For complex tasks
# Create RouterAgent with cost optimization strategy
router = RouterAgent(
name="CostOptimizedRouter",
role="Cost-Efficient Task Router",
goal="Route tasks to the most cost-effective model while maintaining quality",
backstory="You are a smart router that optimizes for cost-efficiency by selecting appropriate models based on task complexity.",
# Model routing strategy - simple tasks to cheap models, complex to premium
models=[cheap_model, balanced_model, premium_model],
# Routing logic - this could be enhanced with more sophisticated rules
instructions="""You are a cost-optimization router. For simple tasks like basic questions,
definitions, or simple calculations, use the cheapest model. For moderate complexity tasks
like writing, analysis, or research, use the balanced model. For complex tasks requiring
deep reasoning, creativity, or specialized knowledge, use the premium model.""",
tools=[duckduckgo],
verbose=True
)
# Example tasks of varying complexity levels
# Simple task - should route to cheap model
print("="*60)
print("TESTING SIMPLE TASK (should use cheap model)")
print("="*60)
simple_result = router.start("What is the capital of France?")
print(f"Simple task result: {simple_result}")
# Moderate complexity task - should route to balanced model
print("\n" + "="*60)
print("TESTING MODERATE TASK (should use balanced model)")
print("="*60)
moderate_result = router.start("Write a brief analysis of renewable energy trends in 2024")
print(f"Moderate task result: {moderate_result}")
# Complex task - should route to premium model
print("\n" + "="*60)
print("TESTING COMPLEX TASK (should use premium model)")
print("="*60)
complex_result = router.start("Conduct a comprehensive strategic analysis of the impact of quantum computing on cybersecurity, including potential vulnerabilities and mitigation strategies")
print(f"Complex task result: {complex_result}")
# Research task with tool usage - should route appropriately
print("\n" + "="*60)
print("TESTING RESEARCH TASK WITH TOOLS")
print("="*60)
research_result = router.start("Research and analyze the latest developments in artificial intelligence regulation globally")
print(f"Research task result: {research_result}")
print("\n" + "="*80)
print("COST OPTIMIZATION ROUTER DEMONSTRATION COMPLETED")
print("="*80)
print("The RouterAgent automatically selected appropriate models based on task complexity:")
print("- Simple factual questions → Cheaper model (gpt-4o-mini)")
print("- Moderate analysis tasks → Balanced model (gpt-4o)")
print("- Complex strategic analysis → Premium model (claude-3-5-sonnet)")
print("- This approach optimizes costs while maintaining quality for each task type")
@@ -440,7 +440,7 @@ async def generate_research(
"message": "Report generation queued",
"created_at": datetime.now().isoformat(),
"updated_at": datetime.now().isoformat(),
"config": request.dict()
"config": request.model_dump()
}
# Create config object
@@ -31,7 +31,7 @@ def save_reasoning_chain(chain: ChainOfThought) -> str:
"""Save a chain of thought reasoning to analyze patterns."""
filename = f"reasoning_{chain.problem[:20].replace(' ', '_')}.json"
with open(filename, 'w') as f:
json.dump(chain.dict(), f, indent=2)
json.dump(chain.model_dump(), f, indent=2)
return f"Reasoning chain saved to {filename}"
# Example 1: Chain of Thought Agent
@@ -0,0 +1,46 @@
"""
Self-Reflection Optimization Patterns Example
This example demonstrates self-reflection capabilities using PraisonAI's
built-in reflection features for iterative improvement and quality optimization.
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import internet_search
print("=== Self-Reflection Optimization Patterns Example ===\n")
# Create self-reflecting agent with built-in reflection capabilities
reflection_agent = Agent(
name="Self-Reflecting Agent",
role="Self-Improving Researcher",
goal="Demonstrate self-reflection and iterative improvement patterns",
backstory="Expert researcher with strong self-reflection and continuous improvement capabilities",
tools=[internet_search],
self_reflect=True,
min_reflect=2,
max_reflect=4,
reflect_llm="gpt-4o-mini",
verbose=True
)
# Create task that benefits from self-reflection
reflection_task = Task(
description="""Research and analyze the future of artificial intelligence:
1. Investigate current AI trends and breakthrough technologies
2. Analyze potential impacts on society and industry
3. Provide well-reasoned predictions for the next 5 years
4. Ensure analysis is comprehensive, accurate, and well-structured
Use self-reflection to improve the quality and completeness of your analysis.""",
expected_output="Comprehensive AI future analysis with high quality through self-reflection",
agent=reflection_agent
)
# Run with self-reflection optimization
print("Starting self-reflection optimization demonstration...")
result = reflection_agent.execute_task(reflection_task)
print(f"\nSelf-Reflection Result: {result[:200]}...")
print("\n✅ Self-reflection optimization complete!")
print("Agent demonstrated iterative improvement through built-in self-reflection capabilities.")
@@ -0,0 +1,197 @@
"""
Hosted MCP Server implementation for PraisonAI Agents.
This module provides a base class for creating hosted MCP servers
that can handle requests and integrate with the MCP protocol.
Note: This is an example implementation. To use it, ensure you have installed:
pip install praisonaiagents[mcp] starlette>=0.27.0
"""
import asyncio
import logging
from typing import Dict, Any, Optional, List, Callable
import json
try:
from mcp.server.fastmcp import FastMCP
from mcp.server import Server
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.routing import Mount, Route
from mcp.server.sse import SseServerTransport
import uvicorn
except ImportError:
raise ImportError(
"MCP server dependencies not installed. "
"Please install with: pip install praisonaiagents[mcp] starlette>=0.27.0"
)
logger = logging.getLogger(__name__)
class HostedMCPServer:
"""
Base class for creating hosted MCP servers.
This class provides a foundation for building MCP servers that can:
- Handle incoming requests
- Define custom tools
- Support SSE transport
- Be extended with custom functionality like latency tracking
"""
def __init__(self, name: str = "hosted-mcp-server", host: str = "localhost", port: int = 8080):
"""
Initialize the hosted MCP server.
Args:
name: Server name for identification
host: Host to bind to (default: localhost)
port: Port to listen on (default: 8080)
"""
self.name = name
self.host = host
self.port = port
self.mcp = FastMCP(name)
self._tools: Dict[str, Callable] = {}
self._server: Optional[Server] = None
self._app: Optional[Starlette] = None
def handle_request(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Handle incoming MCP requests.
This method can be overridden in subclasses to add custom request handling,
such as latency tracking, authentication, or request modification.
Args:
request_data: The incoming request data
Returns:
Response data
"""
# Default implementation - can be overridden
method = request_data.get('method', '')
request_id = request_data.get('id', 'unknown')
logger.debug(f"Handling request {request_id}: {method}")
# Basic response structure
response = {
'id': request_id,
'jsonrpc': '2.0',
'result': {}
}
return response
def add_tool(self, func: Callable, name: Optional[str] = None, description: Optional[str] = None):
"""
Add a tool to the MCP server.
Args:
func: The function to expose as a tool
name: Optional name for the tool (defaults to function name)
description: Optional description for the tool
"""
tool_name = name or func.__name__
# Register with FastMCP
if asyncio.iscoroutinefunction(func):
# Already async
self.mcp.tool(name=tool_name)(func)
else:
# Wrap sync function in async
async def async_wrapper(*args, **kwargs):
return func(*args, **kwargs)
async_wrapper.__name__ = func.__name__
async_wrapper.__doc__ = description or func.__doc__
self.mcp.tool(name=tool_name)(async_wrapper)
self._tools[tool_name] = func
logger.info(f"Added tool: {tool_name}")
def create_app(self, debug: bool = False) -> Starlette:
"""
Create a Starlette application for serving the MCP server.
Args:
debug: Enable debug mode
Returns:
Starlette application instance
Raises:
RuntimeError: If the MCP server is not properly initialized
"""
if not self._server:
if not hasattr(self.mcp, '_mcp_server'):
raise RuntimeError("MCP server not properly initialized. Ensure FastMCP is correctly set up.")
self._server = self.mcp._mcp_server
sse = SseServerTransport("/messages/")
async def handle_sse(request: Request) -> None:
logger.debug(f"SSE connection from {request.client}")
async with sse.connect_sse(
request.scope,
request.receive,
request._send,
) as (read_stream, write_stream):
await self._server.run(
read_stream,
write_stream,
self._server.create_initialization_options(),
)
self._app = Starlette(
debug=debug,
routes=[
Route("/sse", endpoint=handle_sse),
Mount("/messages/", app=sse.handle_post_message),
],
)
return self._app
def start(self, debug: bool = False, **uvicorn_kwargs):
"""
Start the MCP server.
Args:
debug: Enable debug mode
**uvicorn_kwargs: Additional arguments to pass to uvicorn
"""
app = self.create_app(debug=debug)
print(f"Starting {self.name} MCP server on {self.host}:{self.port}")
print(f"Available tools: {', '.join(self._tools.keys())}")
print(f"SSE endpoint: http://{self.host}:{self.port}/sse")
uvicorn.run(app, host=self.host, port=self.port, **uvicorn_kwargs)
async def start_async(self, debug: bool = False):
"""
Start the MCP server asynchronously.
Args:
debug: Enable debug mode
"""
app = self.create_app(debug=debug)
config = uvicorn.Config(app, host=self.host, port=self.port)
server = uvicorn.Server(config)
print(f"Starting {self.name} MCP server on {self.host}:{self.port}")
print(f"Available tools: {', '.join(self._tools.keys())}")
await server.serve()
def get_tools(self) -> List[str]:
"""Get list of available tool names."""
return list(self._tools.keys())
def get_endpoint(self) -> str:
"""Get the SSE endpoint URL."""
return f"http://{self.host}:{self.port}/sse"
@@ -6,7 +6,7 @@ without modifying PraisonAI core files.
"""
from praisonaiagents import Agent, PraisonAIAgents
from praisonaiagents.mcp import HostedMCPServer
from hosted_server import HostedMCPServer # Import from local file
from latency_tracker_tool import tracker, get_latency_metrics
import json
@@ -0,0 +1,59 @@
"""
Advanced Callback Systems Example
This example demonstrates callback systems using PraisonAI's built-in
callback functionality for monitoring agent interactions and tool usage.
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.display_callback import register_display_callback
from praisonaiagents.tools import internet_search
print("=== Advanced Callback Systems Example ===\n")
# Simple callback function to monitor interactions
def interaction_callback(data):
"""Monitor agent interactions"""
print(f"📋 Interaction: {data.get('agent_name', 'Unknown')} - {data.get('type', 'unknown')}")
# Simple callback function to monitor tool usage
def tool_callback(data):
"""Monitor tool usage"""
print(f"🔧 Tool Used: {data.get('agent_name', 'Unknown')} used {data.get('tool_name', 'unknown')}")
# Simple callback function to monitor generation
def generation_callback(data):
"""Monitor content generation"""
print(f"✍️ Generation: {data.get('agent_name', 'Unknown')} generating content")
# Register callbacks with PraisonAI's callback system
print("Registering callbacks...")
register_display_callback('interaction', interaction_callback)
register_display_callback('tool_call', tool_callback)
register_display_callback('generating', generation_callback)
print("✅ Callbacks registered\n")
# Create a research agent with callback monitoring
research_agent = Agent(
name="Research Agent",
role="Information Researcher",
goal="Research topics and demonstrate callback monitoring",
backstory="Expert researcher that demonstrates callback functionality",
tools=[internet_search],
verbose=True
)
# Create a simple task
research_task = Task(
description="Research the latest developments in renewable energy technology",
expected_output="Brief summary of renewable energy developments",
agent=research_agent
)
# Execute with callback monitoring
print("Starting research with callback monitoring...")
result = research_agent.execute_task(research_task)
print(f"\nResearch Result: {result[:200]}...")
print("\n✅ Callback monitoring demonstration complete!")
print("Callbacks successfully tracked agent interactions, tool usage, and content generation.")
+1 -1
View File
@@ -72,7 +72,7 @@ workflow = PraisonAIAgents(
)
# Run the workflow
results = workflow.start()
results = workflow.start(return_dict=True)
# Print results
print("\nWorkflow Results:")
@@ -0,0 +1,204 @@
"""
Comprehensive Guardrails Example
This example demonstrates both function-based and LLM-based guardrails for validating
agent outputs and ensuring quality, safety, and compliance.
Features demonstrated:
- Function-based validation guardrails
- LLM-based content validation
- Multiple validation criteria
- Retry mechanisms with feedback
- Quality assurance workflows
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.task import TaskOutput
from typing import Tuple, Any
import re
# Define function-based guardrails for different validation types
def email_format_guardrail(task_output: TaskOutput) -> Tuple[bool, Any]:
"""
Validates that the output contains properly formatted email addresses.
"""
output_text = str(task_output.raw)
# Email regex pattern
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
emails_found = re.findall(email_pattern, output_text)
if emails_found:
return True, task_output
else:
return False, "No valid email addresses found in the output. Please include at least one properly formatted email address."
def word_count_guardrail(task_output: TaskOutput) -> Tuple[bool, Any]:
"""
Validates that the output meets minimum word count requirements.
"""
output_text = str(task_output.raw)
word_count = len(output_text.split())
min_words = 50 # Minimum required words
if word_count >= min_words:
return True, task_output
else:
return False, f"Output too short. Found {word_count} words but need at least {min_words} words. Please provide a more detailed response."
def professional_tone_guardrail(task_output: TaskOutput) -> Tuple[bool, Any]:
"""
Validates that the output maintains a professional tone.
"""
output_text = str(task_output.raw).lower()
# Check for unprofessional words/phrases
unprofessional_terms = ['stupid', 'dumb', 'sucks', 'terrible', 'awful', 'hate']
for term in unprofessional_terms:
if term in output_text:
return False, f"Output contains unprofessional language ('{term}'). Please revise to maintain a professional tone."
return True, task_output
def factual_accuracy_guardrail(task_output: TaskOutput) -> Tuple[bool, Any]:
"""
Validates that the output includes specific factual elements.
"""
output_text = str(task_output.raw).lower()
# Check for presence of factual indicators
factual_indicators = ['according to', 'research shows', 'studies indicate', 'data suggests', 'evidence']
has_factual_backing = any(indicator in output_text for indicator in factual_indicators)
if has_factual_backing:
return True, task_output
else:
return False, "Output lacks factual backing. Please include references to research, studies, or data to support your claims."
# Create agents with different guardrail configurations
# Agent with email format validation
email_agent = Agent(
name="EmailAgent",
role="Business Communication Specialist",
goal="Create professional business communications with proper email formatting",
backstory="You are a professional communication specialist who ensures all business correspondence includes proper contact information.",
instructions="Always include properly formatted email addresses in your responses."
)
# Agent with word count validation
content_agent = Agent(
name="ContentAgent",
role="Content Writer",
goal="Create detailed, comprehensive content that meets length requirements",
backstory="You are a professional content writer who creates detailed, well-researched articles.",
instructions="Provide comprehensive, detailed responses with sufficient depth and explanation."
)
# Agent with professional tone validation
business_agent = Agent(
name="BusinessAgent",
role="Professional Advisor",
goal="Provide professional business advice with appropriate tone",
backstory="You are a seasoned business advisor who maintains professionalism in all communications.",
instructions="Maintain a professional, respectful tone in all communications."
)
# Agent with factual accuracy validation
research_agent = Agent(
name="ResearchAgent",
role="Research Analyst",
goal="Provide well-researched, fact-based analysis",
backstory="You are a research analyst who backs all claims with evidence and citations.",
instructions="Support all statements with references to research, studies, or credible data sources."
)
# Create tasks with specific guardrails
# Task with email format guardrail
email_task = Task(
name="email_communication",
description="Write a business proposal for a new software project, including contact information",
expected_output="Professional business proposal with contact email addresses",
agent=email_agent,
guardrail=email_format_guardrail,
max_retries=3
)
# Task with word count guardrail
content_task = Task(
name="detailed_analysis",
description="Write an analysis of cloud computing benefits for small businesses",
expected_output="Comprehensive analysis of cloud computing benefits (minimum 50 words)",
agent=content_agent,
guardrail=word_count_guardrail,
max_retries=3
)
# Task with professional tone guardrail
business_task = Task(
name="professional_advice",
description="Provide advice on handling difficult client relationships",
expected_output="Professional advice maintaining appropriate business tone",
agent=business_agent,
guardrail=professional_tone_guardrail,
max_retries=3
)
# Task with factual accuracy guardrail
research_task = Task(
name="research_report",
description="Analyze the impact of artificial intelligence on job markets",
expected_output="Research-backed analysis with citations and evidence",
agent=research_agent,
guardrail=factual_accuracy_guardrail,
max_retries=3
)
# LLM-based guardrail example
llm_guardrail_agent = Agent(
name="LLMGuardrailAgent",
role="Content Quality Validator",
goal="Validate content quality using LLM-based assessment",
backstory="You are a quality assurance specialist who uses AI to validate content quality.",
instructions="Create marketing content that is engaging, accurate, and compliant with advertising standards."
)
# Task with LLM-based guardrail
llm_guardrail_task = Task(
name="marketing_content",
description="Create a marketing email for a new fitness app targeting busy professionals",
expected_output="Engaging marketing email that is accurate and compliant",
agent=llm_guardrail_agent,
# LLM-based guardrail using natural language validation
guardrail="Validate that this marketing content is: 1) Factually accurate with no false claims, 2) Compliant with advertising standards (no misleading statements), 3) Engaging and professional in tone, 4) Includes a clear call-to-action. If any criteria are not met, explain what needs to be improved.",
max_retries=2
)
# Execute tasks with guardrails
agents = PraisonAIAgents(
agents=[email_agent, content_agent, business_agent, research_agent, llm_guardrail_agent],
tasks=[email_task, content_task, business_task, research_task, llm_guardrail_task],
verbose=True
)
print("="*80)
print("EXECUTING TASKS WITH COMPREHENSIVE GUARDRAILS")
print("="*80)
result = agents.start()
print("\n" + "="*80)
print("GUARDRAILS DEMONSTRATION COMPLETED")
print("="*80)
print("This example demonstrated:")
print("- Function-based validation (email format, word count, tone, factual accuracy)")
print("- LLM-based content validation using natural language criteria")
print("- Automatic retry mechanisms with specific feedback")
print("- Quality assurance workflows for different content types")
print("- Professional validation standards for business communications")
@@ -0,0 +1,65 @@
"""
Production Guardrails Patterns Example
This example demonstrates production guardrail patterns using PraisonAI's
built-in validation and safety mechanisms for secure agent operations.
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import internet_search
print("=== Production Guardrails Patterns Example ===\n")
# Simple guardrail function for content validation
def content_guardrail(response, context):
"""Simple content validation guardrail"""
if not response or len(response.strip()) < 50:
return {
"valid": False,
"reason": "Response too short for production use",
"action": "regenerate"
}
# Check for sensitive patterns (simplified)
sensitive_keywords = ["password", "secret", "private_key", "api_key"]
if any(keyword in response.lower() for keyword in sensitive_keywords):
return {
"valid": False,
"reason": "Potential sensitive information detected",
"action": "review_and_redact"
}
return {"valid": True}
# Create production-ready agent with guardrails
production_agent = Agent(
name="Production Agent",
role="Production Content Generator",
goal="Generate safe, compliant content for production use",
backstory="Production-ready agent with built-in safety and compliance checks",
tools=[internet_search],
guardrail=content_guardrail,
max_retries=3,
verbose=True
)
# Create secure task with validation
secure_task = Task(
description="""Create a professional report about renewable energy trends:
1. Research current renewable energy market developments
2. Include factual data and reliable sources
3. Ensure content is production-ready and compliant
4. Avoid any sensitive or inappropriate information
Focus on creating safe, accurate, professional content.""",
expected_output="Professional renewable energy report meeting production standards",
agent=production_agent
)
# Run with guardrail validation
print("Starting production guardrails demonstration...")
result = production_agent.execute_task(secure_task)
print(f"\nProduction Result: {result[:200]}...")
print("\n✅ Production guardrails validation complete!")
print("Agent demonstrated safe content generation with built-in guardrail validation.")
@@ -0,0 +1,194 @@
"""
Advanced Knowledge Management Example
This example demonstrates sophisticated knowledge management capabilities including
advanced chunking strategies, reranking, and intelligent knowledge retrieval.
Features demonstrated:
- Advanced document chunking strategies
- Vector store integration with ChromaDB
- Knowledge-based question answering
- Intelligent context retrieval
- Document processing and management
"""
from praisonaiagents import Agent
import tempfile
import os
# Create a sample knowledge document for demonstration
sample_document = """
# Artificial Intelligence in Healthcare
## Introduction
Artificial intelligence (AI) is revolutionizing healthcare by enabling more accurate diagnoses,
personalized treatments, and efficient healthcare delivery. This document explores the current
applications and future potential of AI in healthcare.
## Current Applications
### Medical Imaging
AI algorithms, particularly deep learning models, have shown remarkable success in medical imaging:
- Radiology: AI can detect cancers in mammograms with accuracy matching or exceeding radiologists
- Ophthalmology: AI systems can diagnose diabetic retinopathy from retinal photographs
- Pathology: AI assists in analyzing tissue samples for cancer detection
### Drug Discovery
AI is accelerating drug discovery processes:
- Molecular design: AI predicts molecular properties and drug-target interactions
- Clinical trials: AI optimizes patient recruitment and trial design
- Repurposing: AI identifies new uses for existing drugs
### Predictive Analytics
Healthcare providers use AI for:
- Risk stratification: Identifying patients at risk of complications
- Early warning systems: Detecting deteriorating patient conditions
- Resource planning: Optimizing staff schedules and equipment allocation
## Challenges and Considerations
### Data Privacy and Security
Healthcare AI faces significant challenges:
- Patient data protection and HIPAA compliance
- Secure data sharing between institutions
- Consent management for AI applications
### Regulatory Approval
AI medical devices require:
- FDA approval for diagnostic tools
- Clinical validation studies
- Post-market surveillance
### Ethical Considerations
Important ethical aspects include:
- Algorithmic bias and fairness
- Transparency and explainability
- Patient autonomy and informed consent
## Future Directions
### Personalized Medicine
AI will enable:
- Genomic-based treatment selection
- Individualized drug dosing
- Precision diagnostics
### Integrated Healthcare Systems
Future developments include:
- AI-powered electronic health records
- Interoperable AI systems across healthcare networks
- Real-time decision support systems
## Conclusion
AI has tremendous potential to transform healthcare, but successful implementation requires
addressing technical, regulatory, and ethical challenges while maintaining focus on patient safety
and improved outcomes.
"""
# Save the sample document to a temporary file
temp_dir = tempfile.mkdtemp()
doc_path = os.path.join(temp_dir, "ai_healthcare_guide.txt")
with open(doc_path, "w") as f:
f.write(sample_document)
# Create an agent with advanced knowledge management configuration
knowledge_agent = Agent(
name="AdvancedKnowledgeAgent",
role="Healthcare AI Knowledge Expert",
goal="Provide comprehensive answers about AI in healthcare using advanced knowledge retrieval",
backstory="You are an expert in healthcare AI with access to comprehensive knowledge bases and advanced retrieval capabilities.",
# Advanced knowledge configuration
knowledge=[doc_path],
knowledge_config={
"vector_store": {
"provider": "chroma",
"collection_name": "healthcare_ai_knowledge"
},
"chunking": {
"strategy": "semantic", # Advanced semantic chunking
"chunk_size": 500, # Optimal chunk size for retrieval
"chunk_overlap": 50, # Overlap for context preservation
"separators": ["\n\n", "\n", ".", "!", "?"] # Smart separators
},
"retrieval": {
"search_type": "similarity",
"k": 5, # Retrieve top 5 most relevant chunks
"score_threshold": 0.7, # Minimum relevance score
"rerank": True # Enable reranking for better results
},
"embedding": {
"provider": "openai",
"model": "text-embedding-3-small", # Efficient embedding model
"dimensions": 1536
}
},
instructions="""You are an expert in healthcare AI. Use the knowledge base to provide
comprehensive, accurate answers. Always cite specific information from the documents
when possible. If the knowledge base doesn't contain sufficient information, clearly
state this and provide general guidance based on your training.""",
verbose=True
)
# Test advanced knowledge retrieval with various question types
# Factual question about specific applications
print("="*70)
print("TESTING: Specific factual question about AI applications")
print("="*70)
factual_result = knowledge_agent.start(
"What are the current applications of AI in medical imaging according to the knowledge base?"
)
print(f"Factual query result:\n{factual_result}\n")
# Complex analytical question requiring synthesis
print("="*70)
print("TESTING: Complex analytical question requiring synthesis")
print("="*70)
analytical_result = knowledge_agent.start(
"What are the main challenges facing AI implementation in healthcare and how do they relate to each other?"
)
print(f"Analytical query result:\n{analytical_result}\n")
# Specific detail extraction
print("="*70)
print("TESTING: Specific detail extraction")
print("="*70)
detail_result = knowledge_agent.start(
"What specific regulatory requirements does the document mention for AI medical devices?"
)
print(f"Detail extraction result:\n{detail_result}\n")
# Future-oriented question requiring inference
print("="*70)
print("TESTING: Future-oriented question requiring inference")
print("="*70)
future_result = knowledge_agent.start(
"Based on the knowledge base, what integration capabilities will future AI healthcare systems have?"
)
print(f"Future-oriented query result:\n{future_result}\n")
# Question about relationships and connections
print("="*70)
print("TESTING: Relationship and connection analysis")
print("="*70)
relationship_result = knowledge_agent.start(
"How do the ethical considerations mentioned relate to the regulatory approval process for AI in healthcare?"
)
print(f"Relationship analysis result:\n{relationship_result}\n")
# Clean up temporary files
import shutil
shutil.rmtree(temp_dir)
print("="*80)
print("ADVANCED KNOWLEDGE MANAGEMENT DEMONSTRATION COMPLETED")
print("="*80)
print("This example demonstrated:")
print("- Semantic chunking for better context preservation")
print("- Advanced retrieval with reranking capabilities")
print("- Multiple query types with intelligent responses")
print("- Knowledge base integration with vector search")
print("- Configurable embedding and retrieval parameters")
@@ -0,0 +1,75 @@
"""
Advanced Graph Memory Integration Example
This example demonstrates graph memory capabilities with PraisonAI agents
for knowledge graph construction and relationship-aware memory retrieval.
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import internet_search
print("=== Advanced Graph Memory Integration Example ===\n")
# Configure simple graph memory
memory_config = {
"provider": "mem0",
"config": {
"vector_store": {
"provider": "chroma",
"config": {
"path": ".praison/graph_memory"
}
}
}
}
# Create knowledge builder agent with graph memory
knowledge_agent = Agent(
name="Knowledge Agent",
role="Knowledge Graph Builder",
goal="Build and retrieve from knowledge graphs",
backstory="Expert at creating structured knowledge and finding relationships",
tools=[internet_search],
memory=True,
verbose=True
)
# Task to build knowledge graph about AI companies
build_task = Task(
description="""Research and store information about major AI companies and their relationships:
1. OpenAI - products like GPT-4, ChatGPT, leadership, partnerships
2. Anthropic - Claude AI, safety focus, team
3. Relationships between these companies and their technologies
Focus on capturing connections and relationships between entities.""",
expected_output="Knowledge graph with AI company ecosystem relationships",
agent=knowledge_agent
)
# Task to query the knowledge graph
query_task = Task(
description="""Using the stored knowledge graph, answer:
1. What are the main products of each company?
2. Who are the key leaders in these companies?
3. How do these companies relate to each other?
Use relationship-aware memory retrieval.""",
expected_output="Analysis using graph memory relationships",
agent=knowledge_agent
)
# Run with graph memory integration
agents_system = PraisonAIAgents(
agents=[knowledge_agent],
tasks=[build_task, query_task],
memory=True,
memory_config=memory_config,
verbose=True
)
print("Starting graph memory demonstration...")
result = agents_system.start()
print(f"\nGraph Memory Result: {result[:200]}...")
print("\n✅ Graph memory integration complete!")
print("Agent built knowledge graph and performed relationship-aware queries.")
@@ -0,0 +1,76 @@
"""
Advanced Memory Search and Optimization Example
This example demonstrates memory search optimization using PraisonAI's
built-in memory capabilities with semantic search and quality filtering.
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import internet_search
print("=== Advanced Memory Search and Optimization Example ===\n")
# Configure optimized memory settings
memory_config = {
"provider": "mem0",
"config": {
"vector_store": {
"provider": "chroma",
"config": {
"path": ".praison/optimized_memory"
}
}
}
}
# Create research agent with optimized memory
research_agent = Agent(
name="Memory Research Agent",
role="Information Researcher with Memory Optimization",
goal="Research and demonstrate optimized memory search patterns",
backstory="Expert at storing and retrieving information efficiently with memory optimization",
tools=[internet_search],
memory=True,
verbose=True
)
# Task to build searchable memory
build_memory_task = Task(
description="""Research and store information about these topics for later search:
1. Artificial intelligence market trends and growth data
2. Machine learning technologies and applications
3. Tech industry partnerships and investments
4. Cloud computing adoption statistics
Store detailed information that can be searched later.""",
expected_output="Comprehensive research stored in optimized memory",
agent=research_agent
)
# Task to demonstrate memory search optimization
search_task = Task(
description="""Using the stored memory, perform optimized searches for:
1. "AI market growth trends" - find relevant stored information
2. "technology partnerships" - retrieve partnership data
3. "cloud adoption statistics" - search for cloud computing info
Demonstrate efficient memory retrieval and search optimization.""",
expected_output="Results from optimized memory searches",
agent=research_agent
)
# Run with memory optimization
agents_system = PraisonAIAgents(
agents=[research_agent],
tasks=[build_memory_task, search_task],
memory=True,
memory_config=memory_config,
verbose=True
)
print("Starting memory search optimization demonstration...")
result = agents_system.start()
print(f"\nMemory Search Result: {result[:200]}...")
print("\n✅ Memory search optimization complete!")
print("Agent demonstrated efficient memory storage and optimized search retrieval.")
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""
Example: Using Gemini Embedding Models with PraisonAI Memory
This example demonstrates how to configure PraisonAI to use Google's Gemini
embedding models for memory storage and retrieval, as requested in issue #870.
Supported Gemini embedding models:
- gemini-embedding-exp-03-07 (experimental)
- text-embedding-004 (stable)
Prerequisites:
1. Install praisonaiagents with memory support:
pip install "praisonaiagents[memory]"
2. Set your Google API key:
export GOOGLE_API_KEY='your-api-key'
3. Ensure litellm is installed (comes with praisonaiagents)
"""
import os
from praisonaiagents import Agent, Task, PraisonAIAgents
def main():
"""Demonstrate Gemini embedding usage"""
# Verify Google API key
if not os.environ.get("GOOGLE_API_KEY"):
print("Error: GOOGLE_API_KEY environment variable not set")
print("Please set it with: export GOOGLE_API_KEY='your-api-key'")
return
print("=== Gemini Embedding Example ===\n")
# Create agents for different tasks
researcher = Agent(
name="Research Agent",
role="Information Researcher",
goal="Research and store important information about topics",
backstory="Expert at analyzing and documenting information with semantic understanding",
llm="gpt-4o-mini" # Using GPT for chat, Gemini for embeddings
)
retriever = Agent(
name="Retrieval Agent",
role="Information Retriever",
goal="Retrieve relevant information from memory using semantic search",
backstory="Specialist in finding and presenting stored information",
llm="gpt-4o-mini"
)
# Task 1: Store information with semantic meaning
store_task = Task(
description="""
Research and store the following information:
1. Gemini is Google's family of multimodal AI models
2. Gemini models support text, image, video, and audio understanding
3. The embedding models provide semantic representations of text
4. Gemini Ultra is the largest and most capable model
5. Gemini was announced in December 2023
Store each fact with its semantic meaning preserved.
""",
expected_output="Confirmation that all facts have been stored in memory",
agent=researcher
)
# Task 2: Semantic retrieval test
retrieve_task = Task(
description="""
Using semantic search, find information about:
1. Google's AI capabilities
2. Multimodal understanding features
3. When was Google's latest AI announced
Note: Use semantic similarity, not exact keyword matching.
""",
expected_output="Retrieved information based on semantic meaning",
agent=retriever
)
# Configure with Gemini embeddings
# Option 1: Using stable text-embedding-004
agents = PraisonAIAgents(
agents=[researcher, retriever],
tasks=[store_task, retrieve_task],
verbose=True,
memory=True,
embedder={
"provider": "gemini",
"config": {
"model": "text-embedding-004",
# Optional: specify task type for better results
# "task_type": "RETRIEVAL_DOCUMENT"
}
}
)
# Alternative: Using experimental model with advanced features
# agents = PraisonAIAgents(
# agents=[researcher, retriever],
# tasks=[store_task, retrieve_task],
# verbose=True,
# memory=True,
# embedder={
# "provider": "gemini",
# "config": {
# "model": "gemini-embedding-exp-03-07",
# # Task types: SEMANTIC_SIMILARITY, CLASSIFICATION, CLUSTERING,
# # RETRIEVAL_DOCUMENT, RETRIEVAL_QUERY, QUESTION_ANSWERING,
# # FACT_VERIFICATION
# "task_type": "RETRIEVAL_DOCUMENT"
# }
# }
# )
# Execute the workflow
print("Starting agents with Gemini embeddings...\n")
result = agents.start()
# Demonstrate direct memory access with Gemini embeddings
print("\n=== Direct Memory Search Example ===\n")
if agents.shared_memory:
# Search queries that test semantic understanding
queries = [
"What are Google's latest AI innovations?",
"Explain multimodal AI capabilities",
"Large language model features"
]
for query in queries:
print(f"\nSearching for: '{query}'")
results = agents.shared_memory.search_long_term(query, limit=3)
if results:
print(f"Found {len(results)} semantically similar results:")
for i, result in enumerate(results, 1):
print(f"\n{i}. Relevance Score: {result.get('score', 0):.3f}")
print(f" Content: {result.get('text', '')[:150]}...")
else:
print("No results found")
print("\n=== Example Complete ===")
print("\nKey Points:")
print("1. Gemini embeddings provide semantic understanding of text")
print("2. Results are based on meaning, not just keyword matching")
print("3. Different task types can optimize embedding quality")
print("4. Compatible with LiteLLM for easy integration")
if __name__ == "__main__":
main()
+165
View File
@@ -0,0 +1,165 @@
# Gemini Embedding Support in PraisonAI
This document describes how to use Google's Gemini embedding models with PraisonAI's memory system.
## Overview
PraisonAI now supports configurable embedding models through LiteLLM, including Google's Gemini embedding models. This allows you to use models like `text-embedding-004` or `gemini-embedding-exp-03-07` for semantic search and memory storage.
## Configuration
### Default Configuration (OpenAI)
By default, PraisonAI uses OpenAI's `text-embedding-3-small` model:
```python
from praisonaiagents import PraisonAIAgents
agents = PraisonAIAgents(
agents=[...],
tasks=[...],
memory=True # Uses default OpenAI embeddings
)
```
### Using Gemini Embeddings
To use Gemini embeddings, configure the `embedder` parameter:
```python
from praisonaiagents import PraisonAIAgents
agents = PraisonAIAgents(
agents=[...],
tasks=[...],
memory=True,
embedder={
"provider": "gemini",
"config": {
"model": "text-embedding-004" # or "gemini-embedding-exp-03-07"
}
}
)
```
## Prerequisites
1. **API Key**: Set your Google API key:
```bash
export GOOGLE_API_KEY='your-api-key'
```
2. **Dependencies**: Ensure you have the memory dependencies installed:
```bash
pip install "praisonaiagents[memory]"
```
## Supported Models
### Gemini Embedding Models
- `text-embedding-004` - Stable embedding model
- `gemini-embedding-exp-03-07` - Experimental model with advanced features
### Task Types (Optional)
Gemini models support task-specific optimizations:
- `SEMANTIC_SIMILARITY`
- `CLASSIFICATION`
- `CLUSTERING`
- `RETRIEVAL_DOCUMENT`
- `RETRIEVAL_QUERY`
- `QUESTION_ANSWERING`
- `FACT_VERIFICATION`
Example with task type:
```python
embedder={
"provider": "gemini",
"config": {
"model": "text-embedding-004",
"task_type": "RETRIEVAL_DOCUMENT"
}
}
```
## Complete Example
```python
import os
from praisonaiagents import Agent, Task, PraisonAIAgents
# Ensure Google API key is set
os.environ["GOOGLE_API_KEY"] = "your-api-key"
# Create agents
researcher = Agent(
name="Researcher",
role="Information Researcher",
goal="Store information with semantic understanding",
llm="gpt-4o-mini"
)
# Create task
task = Task(
description="Research and store information about AI advancements",
expected_output="Confirmation of stored information",
agent=researcher
)
# Initialize with Gemini embeddings
agents = PraisonAIAgents(
agents=[researcher],
tasks=[task],
memory=True,
embedder={
"provider": "gemini",
"config": {
"model": "text-embedding-004"
}
}
)
# Run the agents
agents.start()
```
## Backward Compatibility
The implementation maintains full backward compatibility:
1. **No embedder config**: Uses default OpenAI `text-embedding-3-small`
2. **Existing configs**: Continue to work without modification
3. **Other providers**: Supports any embedding model available through LiteLLM
## Memory Configuration with Mem0
When using Mem0 as the memory provider, the embedder configuration is passed through:
```python
memory_config = {
"provider": "mem0",
"config": {
"api_key": "your-mem0-key",
"embedder": {
"provider": "gemini",
"config": {
"model": "text-embedding-004"
}
}
}
}
```
## Troubleshooting
1. **API Key Error**: Ensure `GOOGLE_API_KEY` is set in your environment
2. **Model Not Found**: Verify the model name is correct
3. **LiteLLM Error**: Ensure litellm is installed and up to date
4. **Embedding Size Mismatch**: When switching models, you may need to clear the vector database as different models produce different embedding dimensions
## See Also
- [Gemini API Documentation](https://ai.google.dev/gemini-api/docs/embeddings)
- [LiteLLM Embedding Models](https://docs.litellm.ai/docs/embedding/supported_embedding)
- Example: `/examples/python/memory/gemini-embedding-example.py`
@@ -0,0 +1,215 @@
# Gemini Internal Tools Examples
This directory contains examples demonstrating how to use Google Gemini's built-in internal tools through PraisonAI. These tools are natively supported by Gemini models and provide powerful capabilities without requiring external tool implementations.
## Available Internal Tools
### 1. Google Search (`googleSearch`)
- **Purpose**: Real-time web search with automatic result grounding
- **Use Cases**: Current events, latest information, fact-checking
- **Example**: `gemini-google-search.py`
### 2. URL Context (`urlContext`)
- **Purpose**: Fetch and analyze content from specific URLs
- **Use Cases**: Document analysis, web content summarization, research
- **Example**: `gemini-url-context.py`
### 3. Code Execution (`codeExecution`)
- **Purpose**: Execute Python code snippets within the conversation
- **Use Cases**: Calculations, data analysis, code validation
- **Example**: `gemini-code-execution.py`
## Prerequisites
1. **Gemini API Key**: Set your Google AI Studio API key
```bash
export GEMINI_API_KEY="your-api-key-here"
```
2. **Compatible Model**: Use Gemini models that support internal tools:
- `gemini/gemini-2.0-flash` (recommended)
- `gemini/gemini-2.0-flash-thinking-exp`
- Other Gemini 2.0+ models
3. **PraisonAI Installation**: Ensure you have the latest version
```bash
pip install "praisonaiagents[llm]"
```
## Examples
### Individual Tool Examples
1. **Google Search Example** (`gemini-google-search.py`)
```python
agent = Agent(
instructions="Research assistant with web search",
llm="gemini/gemini-2.0-flash",
tools=[{"googleSearch": {}}]
)
response = agent.start("What's the latest news about AI?")
```
2. **URL Context Example** (`gemini-url-context.py`)
```python
agent = Agent(
instructions="Content analyzer",
llm="gemini/gemini-2.0-flash",
tools=[{"urlContext": {}}]
)
response = agent.start("Summarize this: https://example.com/article")
```
3. **Code Execution Example** (`gemini-code-execution.py`)
```python
agent = Agent(
instructions="Data analyst with code execution",
llm="gemini/gemini-2.0-flash",
tools=[{"codeExecution": {}}]
)
response = agent.start("Calculate compound interest for $10,000 at 5% for 10 years")
```
### Combined Tools Example
**All Tools Together** (`gemini-internal-tools-combined.py`)
```python
agent = Agent(
instructions="Advanced research assistant",
llm="gemini/gemini-2.0-flash",
tools=[
{"googleSearch": {}},
{"urlContext": {}},
{"codeExecution": {}}
]
)
# Now the agent can search, analyze URLs, and execute code as needed
```
## How It Works
### PraisonAI Integration
PraisonAI's tool system is designed to pass tools directly to LiteLLM without modification:
1. **Tool Definition**: Define tools using the special internal tool syntax
```python
tools=[{"googleSearch": {}}] # Special format for internal tools
```
2. **Pass-Through**: PraisonAI passes these tools directly to LiteLLM
3. **Execution**: LiteLLM sends them to Gemini as internal tool configurations
4. **Results**: Gemini executes the tools natively and returns integrated responses
### Mixing with External Tools
You can combine internal tools with custom external tools:
```python
def custom_calculator(expression: str) -> str:
"""Custom calculator function - safely evaluates basic math expressions"""
import ast
import operator
# Define safe operations
ops = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Pow: operator.pow,
ast.USub: operator.neg,
}
def eval_expr(node):
if isinstance(node, ast.Constant): # Numbers
return node.value
elif isinstance(node, ast.BinOp): # Binary operations
return ops[type(node.op)](eval_expr(node.left), eval_expr(node.right))
elif isinstance(node, ast.UnaryOp): # Unary operations
return ops[type(node.op)](eval_expr(node.operand))
else:
raise TypeError(f"Unsupported operation: {type(node)}")
try:
return str(eval_expr(ast.parse(expression, mode='eval').body))
except Exception as e:
return f"Error: {e}"
agent = Agent(
tools=[
{"googleSearch": {}}, # Internal tool
{"codeExecution": {}}, # Internal tool
custom_calculator # External tool
]
)
```
## Running the Examples
1. **Set API Key**:
```bash
export GEMINI_API_KEY="your-api-key"
```
2. **Run Individual Examples**:
```bash
python gemini-google-search.py
python gemini-url-context.py
python gemini-code-execution.py
```
3. **Run Combined Example**:
```bash
python gemini-internal-tools-combined.py
```
## Benefits Over External Tools
### Advantages of Internal Tools
1. **Native Integration**: No need to implement or maintain external tool code
2. **Optimized Performance**: Tools are executed within Gemini's environment
3. **Automatic Grounding**: Search results are automatically integrated into responses
4. **No Rate Limits**: No separate API calls or rate limiting concerns
5. **Security**: Code execution is sandboxed within Gemini's environment
### When to Use External Tools
- When you need specific custom logic
- When you require integration with private APIs
- When you need persistent data storage
- When you want full control over tool behavior
## Troubleshooting
### Common Issues
1. **API Key Error**: Ensure `GEMINI_API_KEY` is set correctly
2. **Model Not Supported**: Use Gemini 2.0+ models for internal tools
3. **Tool Not Available**: Some tools may have regional or quota restrictions
### Debug Mode
Enable verbose logging to see tool usage:
```python
agent = Agent(
# ... config
verbose=True # Shows detailed tool usage
)
```
## References
- [Gemini API: Google Search Grounding](https://ai.google.dev/gemini-api/docs/google-search)
- [Gemini API: URL Context](https://ai.google.dev/gemini-api/docs/url-context)
- [Gemini API: Code Execution](https://ai.google.dev/gemini-api/docs/code-execution)
- [LiteLLM Gemini Provider Documentation](https://docs.litellm.ai/docs/providers/gemini)
## Contributing
If you create additional examples or find improvements, please contribute back to the PraisonAI project!
@@ -0,0 +1,99 @@
"""
Gemini Code Execution Tool Example
This example demonstrates how to use Gemini's built-in Code Execution functionality
through PraisonAI. The Code Execution tool allows the model to run Python code
snippets directly within the conversation for dynamic computation and validation.
Prerequisites:
- Set GEMINI_API_KEY environment variable
- Use a Gemini model that supports internal tools (gemini-2.0-flash, etc.)
Features:
- Direct Python code execution within the model
- Real-time calculations and data processing
- Code validation and testing
- Mathematical computations and visualizations
"""
from praisonaiagents import Agent
# Ensure you have your Gemini API key set
# import os; os.environ["GEMINI_API_KEY"] = "your-api-key-here"
def main():
# Create agent with Code Execution internal tool
agent = Agent(
instructions="""You are a data analyst and programmer that can execute Python code.
Use the Code Execution tool to perform calculations, analyze data, create visualizations,
and validate logic. Always show your work by executing relevant code snippets.""",
llm="gemini/gemini-2.0-flash",
# Enable Code Execution internal tool
tools=[{"codeExecution": {}}],
verbose=True
)
# Example tasks that benefit from code execution
tasks = [
"Calculate the compound interest on $10,000 invested at 5% annual rate for 10 years, compounded monthly. Show the calculation step by step.",
"Generate the first 20 Fibonacci numbers and find their sum. Also calculate the ratio of consecutive Fibonacci numbers.",
"Create a simple linear regression model for the data points: (1,2), (2,4), (3,6), (4,8), (5,10). Calculate the R-squared value.",
"Solve the quadratic equation 2x² + 5x - 3 = 0 using the quadratic formula. Verify the solutions by substituting back.",
"Calculate the statistical summary (mean, median, mode, standard deviation) for this dataset: [12, 15, 18, 12, 20, 25, 18, 12, 22, 30, 15, 18]",
"Write a function to check if a number is prime, then find all prime numbers between 1 and 100.",
"Calculate the area under the curve y = x² from x = 0 to x = 5 using numerical integration (trapezoidal rule)."
]
print("=== Gemini Code Execution Tool Demo ===\n")
for i, task in enumerate(tasks, 1):
print(f"Task {i}: {task}")
print("-" * 80)
try:
response = agent.start(task)
print(f"Response: {response}")
print("\n" + "="*100 + "\n")
except Exception as e:
print(f"Error: {e}")
print("\n" + "="*100 + "\n")
def demonstrate_direct_usage():
"""
Example of how the Code Execution tool works at the LiteLLM level
(for reference - this requires direct LiteLLM usage)
"""
print("=== Direct LiteLLM Code Execution Usage (Reference) ===")
print("""
# This is how it works at the LiteLLM level:
import litellm
import os
os.environ["GEMINI_API_KEY"] = "your-api-key"
response = litellm.completion(
model="gemini/gemini-2.0-flash",
messages=[{
"role": "user",
"content": "Calculate the factorial of 10 and show the code"
}],
tools=[{"codeExecution": {}}],
)
print(response.choices[0].message.content)
""")
if __name__ == "__main__":
main()
demonstrate_direct_usage()
@@ -0,0 +1,63 @@
"""
Gemini Google Search Tool Example
This example demonstrates how to use Gemini's built-in Google Search functionality
through PraisonAI. The Google Search tool allows the model to perform real-time
web searches and ground responses in current information.
Prerequisites:
- Set GEMINI_API_KEY environment variable
- Use a Gemini model that supports internal tools (gemini-2.0-flash, etc.)
Features:
- Real-time web search capabilities
- Automatic grounding of responses in search results
- No need to implement external search tools
"""
from praisonaiagents import Agent
# Ensure you have your Gemini API key set
# import os; os.environ["GEMINI_API_KEY"] = "your-api-key-here"
def main():
# Create agent with Google Search internal tool
agent = Agent(
instructions="""You are a research assistant that can search the web for current information.
Use the Google Search tool to find up-to-date information when answering questions.
Always cite your sources and indicate when information comes from search results.""",
llm="gemini/gemini-2.0-flash",
# Enable Google Search internal tool
tools=[{"googleSearch": {}}],
verbose=True
)
# Example queries that benefit from real-time search
queries = [
"What's the latest news about AI developments this week?",
"What's the current weather in San Francisco?",
"What are the latest stock prices for major tech companies?",
"What are the most recent breakthroughs in quantum computing?",
"Who won the latest major sports championships?"
]
print("=== Gemini Google Search Tool Demo ===\n")
for i, query in enumerate(queries, 1):
print(f"Query {i}: {query}")
print("-" * 50)
try:
response = agent.start(query)
print(f"Response: {response}")
print("\n" + "="*80 + "\n")
except Exception as e:
print(f"Error: {e}")
print("\n" + "="*80 + "\n")
if __name__ == "__main__":
main()
@@ -0,0 +1,187 @@
"""
Gemini Internal Tools Combined Example
This example demonstrates how to use all three of Gemini's built-in internal tools
together through PraisonAI:
1. Google Search - for real-time web information
2. URL Context - for analyzing web content
3. Code Execution - for computations and analysis
Prerequisites:
- Set GEMINI_API_KEY environment variable
- Use a Gemini model that supports internal tools (gemini-2.0-flash, etc.)
Features:
- Multi-tool agent combining search, content analysis, and computation
- Real-world research and analysis workflows
- Comprehensive data gathering and processing capabilities
"""
from praisonaiagents import Agent
# Ensure you have your Gemini API key set
# import os; os.environ["GEMINI_API_KEY"] = "your-api-key-here"
def main():
# Create agent with all Gemini internal tools enabled
agent = Agent(
instructions="""You are an advanced research and analysis assistant with access to:
1. Google Search - for finding current information
2. URL Context - for analyzing web content
3. Code Execution - for calculations and data processing
Use these tools strategically to provide comprehensive, well-researched, and
analytically sound responses. Always show your work and cite sources.""",
llm="gemini/gemini-2.0-flash",
# Enable all three Gemini internal tools
tools=[
{"googleSearch": {}},
{"urlContext": {}},
{"codeExecution": {}}
],
verbose=True
)
# Complex tasks that benefit from multiple internal tools
complex_tasks = [
"""Research the current market cap of the top 5 technology companies,
then calculate their combined market value and determine what percentage
each company represents of the total. Present the results in a formatted table.""",
"""Find recent research papers about large language models from arXiv,
analyze the abstracts of 2-3 papers, and calculate the average number
of authors across these papers.""",
"""Look up the current population of the 10 largest cities in the world,
then calculate statistical measures (mean, median, standard deviation)
and create a simple visualization of the data distribution.""",
"""Research the latest Python release notes, analyze the key new features,
and write example code demonstrating 2-3 of the most important new features.""",
"""Find information about recent climate data, analyze a specific dataset
or report, and perform calculations to show trends or comparisons over time."""
]
print("=== Gemini Combined Internal Tools Demo ===\n")
for i, task in enumerate(complex_tasks, 1):
print(f"Complex Task {i}:")
print(task)
print("-" * 100)
try:
response = agent.start(task)
print(f"Response: {response}")
print("\n" + "="*120 + "\n")
except Exception as e:
print(f"Error: {e}")
print("\n" + "="*120 + "\n")
def demonstrate_tool_synergy():
"""
Example showing how the tools work together for a research workflow
"""
print("=== Tool Synergy Example ===")
agent = Agent(
instructions="""You are a market research analyst. Use all available tools
to gather information, analyze content, and perform calculations as needed.""",
llm="gemini/gemini-2.0-flash",
tools=[
{"googleSearch": {}},
{"urlContext": {}},
{"codeExecution": {}}
],
verbose=True
)
# Multi-step research task
research_query = """
Conduct a mini market analysis on electric vehicle adoption:
1. Search for recent statistics on global EV sales
2. Find and analyze a recent report or article about EV market trends
3. Calculate the year-over-year growth rate if you can find data for multiple years
4. Provide a summary with key insights and numerical analysis
"""
print("Research Query:", research_query)
print("-" * 80)
try:
response = agent.start(research_query)
print(f"Research Results: {response}")
except Exception as e:
print(f"Error: {e}")
def show_configuration_options():
"""
Show different ways to configure the internal tools
"""
print("\n=== Configuration Examples ===")
print("""
# Basic usage (all tools with default settings)
tools=[
{"googleSearch": {}},
{"urlContext": {}},
{"codeExecution": {}}
]
# Can also be used individually
tools=[{"googleSearch": {}}] # Only Google Search
tools=[{"urlContext": {}}] # Only URL Context
tools=[{"codeExecution": {}}] # Only Code Execution
# Mix with custom tools
from praisonaiagents import Agent
def custom_calculator(expression: str) -> str:
'''Custom calculator function - safely evaluates basic math expressions'''
import ast
import operator
# Define safe operations
ops = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Pow: operator.pow,
ast.USub: operator.neg,
}
def eval_expr(node):
if isinstance(node, ast.Constant): # Numbers
return node.value
elif isinstance(node, ast.BinOp): # Binary operations
return ops[type(node.op)](eval_expr(node.left), eval_expr(node.right))
elif isinstance(node, ast.UnaryOp): # Unary operations
return ops[type(node.op)](eval_expr(node.operand))
else:
raise TypeError(f"Unsupported operation: {type(node)}")
try:
return str(eval_expr(ast.parse(expression, mode='eval').body))
except Exception as e:
return f"Error: {e}"
agent = Agent(
tools=[
{"googleSearch": {}}, # Gemini internal tool
{"codeExecution": {}}, # Gemini internal tool
custom_calculator # Custom external tool
]
)
""")
if __name__ == "__main__":
main()
print("\n" + "="*50)
demonstrate_tool_synergy()
show_configuration_options()
@@ -0,0 +1,115 @@
"""
Gemini URL Context Tool Example
This example demonstrates how to use Gemini's built-in URL Context functionality
through PraisonAI. The URL Context tool allows the model to fetch and analyze
content from specific URLs in real-time.
Prerequisites:
- Set GEMINI_API_KEY environment variable
- Use a Gemini model that supports internal tools (gemini-2.0-flash, etc.)
Features:
- Real-time URL content fetching
- Automatic content analysis and summarization
- Support for various web content types
- Access to URL metadata through response.model_extra
"""
from praisonaiagents import Agent
# Ensure you have your Gemini API key set
# import os; os.environ["GEMINI_API_KEY"] = "your-api-key-here"
def main():
# Create agent with URL Context internal tool
agent = Agent(
instructions="""You are a content analyst that can fetch and analyze web content.
Use the URL Context tool to access and analyze content from provided URLs.
Provide detailed summaries, extract key information, and answer questions about the content.""",
llm="gemini/gemini-2.0-flash",
# Enable URL Context internal tool
tools=[{"urlContext": {}}],
verbose=True
)
# Example URLs for analysis
url_tasks = [
{
"url": "https://ai.google.dev/gemini-api/docs/models",
"task": "Summarize the key information about Gemini models and their capabilities"
},
{
"url": "https://github.com/MervinPraison/PraisonAI",
"task": "Analyze this GitHub repository and explain what PraisonAI does"
},
{
"url": "https://docs.python.org/3/tutorial/introduction.html",
"task": "Extract the main learning objectives from this Python tutorial"
},
{
"url": "https://arxiv.org/abs/2301.00234",
"task": "Provide a summary of this research paper's abstract and key contributions"
}
]
print("=== Gemini URL Context Tool Demo ===\n")
for i, item in enumerate(url_tasks, 1):
print(f"Analysis {i}: {item['url']}")
print(f"Task: {item['task']}")
print("-" * 50)
# Combine URL and task in the query
query = f"{item['task']}: {item['url']}"
try:
response = agent.start(query)
print(f"Analysis: {response}")
# Note: URL metadata access requires direct LiteLLM response
# In PraisonAI, this would need to be accessed through the LLM response
print(f"\nAnalyzed URL: {item['url']}")
print("\n" + "="*80 + "\n")
except Exception as e:
print(f"Error: {e}")
print("\n" + "="*80 + "\n")
def demonstrate_direct_usage():
"""
Example of how the URL Context tool works at the LiteLLM level
(for reference - this requires direct LiteLLM usage)
"""
print("=== Direct LiteLLM URL Context Usage (Reference) ===")
print("""
# This is how it works at the LiteLLM level:
import litellm
import os
os.environ["GEMINI_API_KEY"] = "your-api-key"
response = litellm.completion(
model="gemini/gemini-2.0-flash",
messages=[{
"role": "user",
"content": "Summarize this document: https://ai.google.dev/gemini-api/docs/models"
}],
tools=[{"urlContext": {}}],
)
# Access URL metadata
if hasattr(response, 'model_extra') and 'vertex_ai_url_context_metadata' in response.model_extra:
url_context_metadata = response.model_extra['vertex_ai_url_context_metadata']
urlMetadata = url_context_metadata[0]['urlMetadata'][0]
print(f"Retrieved URL: {urlMetadata['retrievedUrl']}")
print(f"Retrieval Status: {urlMetadata['urlRetrievalStatus']}")
""")
if __name__ == "__main__":
main()
demonstrate_direct_usage()
@@ -0,0 +1,282 @@
"""
Advanced Workflow Patterns Example
This example demonstrates sophisticated workflow orchestration patterns including
conditional routing, decision trees, loops, and complex multi-agent coordination.
Features demonstrated:
- Advanced workflow patterns with conditional routing
- Decision trees and dynamic task routing
- Loop-based processing with exit conditions
- Complex agent coordination and handoffs
- State-based workflow management
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import duckduckgo
import random
# Create specialized agents for complex workflow
intake_agent = Agent(
name="IntakeAgent",
role="Request Intake Specialist",
goal="Classify and route incoming requests to appropriate specialists",
backstory="You are an intake specialist who categorizes requests and determines the appropriate workflow path.",
instructions="Analyze incoming requests and categorize them by type (research, analysis, technical, creative) and complexity (low, medium, high)."
)
research_agent = Agent(
name="ResearchAgent",
role="Research Specialist",
goal="Conduct comprehensive research on assigned topics",
backstory="You are a research specialist who gathers and analyzes information from various sources.",
tools=[duckduckgo],
instructions="Conduct thorough research using available tools. Provide detailed findings with sources."
)
analysis_agent = Agent(
name="AnalysisAgent",
role="Data Analysis Expert",
goal="Analyze data and provide insights",
backstory="You are a data analysis expert who identifies patterns, trends, and actionable insights.",
instructions="Analyze provided data to identify key insights, trends, and recommendations."
)
technical_agent = Agent(
name="TechnicalAgent",
role="Technical Solutions Specialist",
goal="Provide technical solutions and implementations",
backstory="You are a technical specialist who designs and implements technical solutions.",
instructions="Provide detailed technical solutions with implementation guidance and best practices."
)
creative_agent = Agent(
name="CreativeAgent",
role="Creative Content Specialist",
goal="Create engaging and creative content",
backstory="You are a creative specialist who develops engaging content and innovative solutions.",
instructions="Create original, engaging content that meets the specified requirements."
)
review_agent = Agent(
name="ReviewAgent",
role="Quality Review Specialist",
goal="Review work quality and provide feedback",
backstory="You are a quality reviewer who ensures all work meets high standards.",
instructions="Review completed work for quality, accuracy, and completeness. Provide specific feedback."
)
coordinator_agent = Agent(
name="CoordinatorAgent",
role="Workflow Coordinator",
goal="Coordinate complex workflows and manage handoffs",
backstory="You are a workflow coordinator who manages complex multi-agent processes.",
instructions="Coordinate workflow execution, manage handoffs between agents, and ensure successful completion."
)
# Define workflow state management
workflow_state = {
"request_count": 0,
"completed_tasks": [],
"active_workflows": [],
"quality_threshold": 0.8
}
# Simulate incoming requests of different types
sample_requests = [
{
"id": "REQ001",
"type": "market_research",
"description": "Research emerging trends in sustainable technology",
"complexity": "medium",
"priority": "high"
},
{
"id": "REQ002",
"type": "technical_solution",
"description": "Design architecture for distributed AI system",
"complexity": "high",
"priority": "medium"
},
{
"id": "REQ003",
"type": "creative_content",
"description": "Create marketing campaign for new product launch",
"complexity": "medium",
"priority": "high"
},
{
"id": "REQ004",
"type": "data_analysis",
"description": "Analyze customer behavior patterns from sales data",
"complexity": "low",
"priority": "low"
}
]
# Process each request through the advanced workflow
for request in sample_requests:
print(f"\n{'='*80}")
print(f"PROCESSING REQUEST {request['id']}: {request['type'].upper()}")
print(f"Description: {request['description']}")
print(f"Complexity: {request['complexity']} | Priority: {request['priority']}")
print(f"{'='*80}")
workflow_state["request_count"] += 1
workflow_state["active_workflows"].append(request["id"])
# Step 1: Intake and Classification
intake_task = Task(
name=f"intake_{request['id']}",
description=f"Classify and route this request: {request['description']} (Type: {request['type']}, Complexity: {request['complexity']})",
expected_output="Request classification with recommended workflow path and agent assignment",
agent=intake_agent
)
# Step 2: Route to appropriate specialist based on type
if request['type'] == 'market_research':
specialist_agent = research_agent
specialist_task_desc = f"Conduct comprehensive market research on: {request['description']}"
elif request['type'] == 'technical_solution':
specialist_agent = technical_agent
specialist_task_desc = f"Design technical solution for: {request['description']}"
elif request['type'] == 'creative_content':
specialist_agent = creative_agent
specialist_task_desc = f"Create creative content for: {request['description']}"
elif request['type'] == 'data_analysis':
specialist_agent = analysis_agent
specialist_task_desc = f"Analyze data for: {request['description']}"
else:
specialist_agent = research_agent # Default fallback
specialist_task_desc = f"Process request: {request['description']}"
specialist_task = Task(
name=f"specialist_{request['id']}",
description=specialist_task_desc,
expected_output="Comprehensive response addressing the request requirements",
agent=specialist_agent,
context=[intake_task]
)
# Step 3: Quality Review with conditional routing
review_task = Task(
name=f"review_{request['id']}",
description=f"Review the quality of work completed for request {request['id']}. Assess if it meets standards or needs revision.",
expected_output="Quality assessment with pass/fail decision and specific feedback",
agent=review_agent,
context=[intake_task, specialist_task],
# Conditional routing based on quality
task_type="decision",
condition={
"approved": [f"finalization_{request['id']}"], # If approved, finalize
"needs_revision": [f"revision_{request['id']}"], # If needs work, revise
"needs_escalation": [f"escalation_{request['id']}"] # If complex, escalate
}
)
# Step 4a: Revision Task (conditional)
revision_task = Task(
name=f"revision_{request['id']}",
description=f"Revise the work based on quality review feedback for request {request['id']}",
expected_output="Revised work addressing quality review feedback",
agent=specialist_agent,
context=[specialist_task, review_task]
)
# Step 4b: Escalation Task (conditional)
escalation_task = Task(
name=f"escalation_{request['id']}",
description=f"Handle escalated request {request['id']} requiring additional expertise or coordination",
expected_output="Escalated response with enhanced solution approach",
agent=coordinator_agent,
context=[intake_task, specialist_task, review_task]
)
# Step 5: Finalization and Coordination
finalization_task = Task(
name=f"finalization_{request['id']}",
description=f"Finalize and package the completed work for request {request['id']}",
expected_output="Final deliverable package with summary and next steps",
agent=coordinator_agent,
context=[intake_task, specialist_task, review_task]
)
# Execute the workflow with conditional routing
workflow_agents = PraisonAIAgents(
agents=[
intake_agent, specialist_agent, review_agent,
coordinator_agent
],
tasks=[
intake_task, specialist_task, review_task,
revision_task, # Conditional
escalation_task, # Conditional
finalization_task
],
process="workflow", # Use workflow process for conditional execution
verbose=True
)
print(f"Executing advanced workflow for {request['id']}...")
result = workflow_agents.start()
# Update workflow state
workflow_state["completed_tasks"].append(request["id"])
workflow_state["active_workflows"].remove(request["id"])
# Simulate quality scoring
quality_score = random.uniform(0.75, 0.95)
print(f"✅ Request {request['id']} completed with quality score: {quality_score:.2f}")
print(f"📋 Result preview: {str(result)[:150]}...")
# Loop control - if we have processed enough requests, demonstrate loop exit
if workflow_state["request_count"] >= 2:
print(f"\n🔄 WORKFLOW LOOP CONTROL: Processed {workflow_state['request_count']} requests")
print("Checking if we should continue or exit based on workflow state...")
# Example loop control logic
if workflow_state["request_count"] >= 4:
print("📊 Batch processing complete. Exiting workflow loop.")
break
else:
print("📈 Continuing with next request in the batch...")
# Advanced Workflow Analytics and Summary
print(f"\n{'='*80}")
print("ADVANCED WORKFLOW PATTERNS SUMMARY")
print(f"{'='*80}")
print(f"📊 Workflow Statistics:")
print(f"- Total Requests Processed: {workflow_state['request_count']}")
print(f"- Completed Tasks: {len(workflow_state['completed_tasks'])}")
print(f"- Active Workflows: {len(workflow_state['active_workflows'])}")
print(f"\n🔀 Workflow Patterns Demonstrated:")
print("- Dynamic request classification and routing")
print("- Conditional task execution based on quality review")
print("- Multi-path workflows (approval/revision/escalation)")
print("- State-based workflow management")
print("- Loop control with exit conditions")
print("- Agent specialization and handoffs")
print(f"\n⚙️ Advanced Features Used:")
print("- Workflow process type with conditional routing")
print("- Decision tasks with multiple outcome paths")
print("- Context passing between related tasks")
print("- State management across workflow iterations")
print("- Quality-based routing decisions")
print("- Scalable agent coordination patterns")
print(f"\n🎯 Production Benefits:")
print("- Handles complex, multi-step business processes")
print("- Automatically routes work to appropriate specialists")
print("- Implements quality gates and revision loops")
print("- Scales to handle multiple concurrent workflows")
print("- Provides visibility into workflow state and progress")
print("- Enables sophisticated business process automation")
print(f"\n{'='*80}")
print("ADVANCED WORKFLOW DEMONSTRATION COMPLETED")
print(f"{'='*80}")
@@ -0,0 +1,99 @@
"""
Hierarchical Process Example
This example demonstrates how to create a hierarchical process where a manager agent
delegates tasks to specialized worker agents. The manager orchestrates the workflow
and each specialized agent performs their specific tasks.
Features demonstrated:
- Hierarchical agent structure with manager and workers
- Task delegation and coordination
- Specialized agent roles with different capabilities
- Process-level orchestration
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import duckduckgo
# Create Manager Agent
manager = Agent(
name="Manager",
role="Project Manager",
goal="Coordinate research and analysis tasks among specialized agents",
backstory="You are an experienced project manager who delegates tasks to specialized team members and synthesizes their work into a comprehensive report.",
instructions="You coordinate tasks between researchers and analysts. Delegate research to the researcher, data analysis to the analyst, and writing to the writer."
)
# Create Specialized Worker Agents
researcher = Agent(
name="Researcher",
role="Senior Researcher",
goal="Conduct thorough research on given topics",
backstory="You are a senior researcher with expertise in gathering and analyzing information from various sources.",
tools=[duckduckgo],
instructions="Conduct comprehensive research using web search. Provide detailed, factual information with sources."
)
data_analyst = Agent(
name="DataAnalyst",
role="Data Analyst",
goal="Analyze trends and patterns in research data",
backstory="You are a skilled data analyst who can identify trends, patterns, and insights from research data.",
instructions="Analyze research data to identify key trends, patterns, and actionable insights. Provide data-driven conclusions."
)
writer = Agent(
name="Writer",
role="Technical Writer",
goal="Create well-structured reports and documentation",
backstory="You are a technical writer who excels at creating clear, comprehensive reports from research and analysis.",
instructions="Create well-structured, professional reports that synthesize research findings and analysis into actionable insights."
)
# Define Hierarchical Tasks
research_task = Task(
name="research_task",
description="Research the latest trends in artificial intelligence and machine learning for business applications",
expected_output="Comprehensive research report with current AI/ML trends, key players, and business applications",
agent=researcher
)
analysis_task = Task(
name="analysis_task",
description="Analyze the research findings to identify the most promising AI/ML trends for business adoption",
expected_output="Analysis report highlighting top 5 AI/ML trends with business impact assessment",
agent=data_analyst,
context=[research_task] # Depends on research task
)
writing_task = Task(
name="writing_task",
description="Create a final executive summary combining research and analysis into actionable business recommendations",
expected_output="Executive summary with strategic recommendations for AI/ML adoption",
agent=writer,
context=[research_task, analysis_task] # Depends on both previous tasks
)
coordination_task = Task(
name="coordination_task",
description="Oversee the entire research project, ensure quality and coordination between all team members",
expected_output="Project oversight report confirming successful completion and quality of all deliverables",
agent=manager,
context=[research_task, analysis_task, writing_task] # Oversees all tasks
)
# Create Hierarchical Process
agents = PraisonAIAgents(
agents=[manager, researcher, data_analyst, writer],
tasks=[research_task, analysis_task, writing_task, coordination_task],
process="hierarchical", # Hierarchical process type
verbose=True
)
# Execute Hierarchical Process
result = agents.start()
print("\n" + "="*50)
print("HIERARCHICAL PROCESS COMPLETED")
print("="*50)
print(f"Final Result:\n{result}")
@@ -0,0 +1,186 @@
# Session Memory Persistence Fix - Implementation Review
## Issue Summary
**GitHub Issue**: [#930](https://github.com/MervinPraison/PraisonAI/issues/930)
**Problem**: Session memory does not persist across sessions - agents lose conversational memory after session restore
## Root Cause Analysis
The issue occurred because:
1. Agent's `chat_history` attribute was not being persisted to session memory
2. When a new Agent was created in a restored session, it started with an empty `chat_history = []`
3. The Session's memory system and Agent's memory system were separate - no integration for chat history persistence
## Solution Implementation
### Changes Made to `session.py`
#### 1. Added Agent Tracking (`_agents` dictionary)
```python
self._agents = {} # Track agents and their chat histories
```
- Tracks all agents created in the session along with their chat histories
- Uses agent key format: `{name}:{role}` for unique identification
#### 2. Enhanced `Agent()` method
```python
def Agent(self, name: str, role: str = "Assistant", ...):
# ... existing code ...
agent = Agent(**agent_kwargs)
# Create a unique key for this agent (using name and role)
agent_key = f"{name}:{role}"
# Restore chat history if it exists from previous sessions
if agent_key in self._agents:
agent.chat_history = self._agents[agent_key].get("chat_history", [])
else:
# Try to restore from memory for backward compatibility
restored_history = self._restore_agent_chat_history(agent_key)
if restored_history:
agent.chat_history = restored_history
# Track the agent
self._agents[agent_key] = {"agent": agent, "chat_history": agent.chat_history}
return agent
```
#### 3. Added Helper Methods
**`_restore_agent_chat_history(agent_key: str)`**
- Restores individual agent chat history from memory
- Searches short-term memory for agent-specific chat history
- Returns list of chat messages or empty list if not found
**`_restore_agent_chat_histories()`**
- Restores all agent chat histories for the session
- Called automatically during `restore_state()`
- Populates `_agents` dictionary with saved chat histories
**`_save_agent_chat_histories()`**
- Saves all agent chat histories to memory
- Called automatically during `save_state()`
- Stores chat history with metadata for later retrieval
#### 4. Enhanced State Management
**Modified `save_state()`**:
```python
def save_state(self, state_data: Dict[str, Any]) -> None:
# Save agent chat histories first
self._save_agent_chat_histories()
# Save session state
# ... existing code ...
```
**Modified `restore_state()`**:
```python
def restore_state(self) -> Dict[str, Any]:
# Restore agent chat histories first
self._restore_agent_chat_histories()
# ... existing code ...
```
## Key Features
### ✅ Backward Compatibility
- All existing Session API methods remain unchanged
- Existing code continues to work without modifications
- No breaking changes to method signatures
### ✅ Automatic Persistence
- Chat history is automatically saved when `save_state()` is called
- Chat history is automatically restored when `restore_state()` is called
- No additional API calls required from user code
### ✅ Agent-Specific Tracking
- Each agent's chat history is tracked separately
- Agent identification uses `{name}:{role}` format
- Multiple agents in the same session are handled correctly
### ✅ Minimal Code Changes
- Only modified the Session class
- No changes to Agent class required
- Total addition: ~90 lines of code
## Usage Example
The fix enables the exact usage pattern described in the issue:
```python
from praisonaiagents import Session
# Create a session with ID
session = Session(session_id="chat_123", user_id="user_456")
agent = session.Agent(
name="Assistant",
instructions="You are a helpful assistant with memory.",
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
memory=True
)
# Agent remembers within session
response1 = agent.chat("My name is John") # Agent learns the name
response2 = agent.chat("What's my name?") # Agent responds: "Your name is John"
# Save session state (now includes chat history)
session.save_state({"conversation_topic": "Names"})
# Create new session and restore (chat history is restored)
anotherSession = Session(session_id="chat_123")
anotherSession.restore_state()
anotherAgent = anotherSession.Agent(
name="Assistant",
instructions="You are a helpful assistant with memory.",
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
memory=True
)
# Agent now remembers from previous session
response3 = anotherAgent.chat("What's my name?") # Agent responds: "Your name is John"
```
## Testing Strategy
### Code Compilation
- ✅ `session.py` compiles without syntax errors
- ✅ All method signatures are valid
### Interface Validation
- ✅ All new methods are properly defined
- ✅ Existing methods remain unchanged
- ✅ Type hints are correct
### Logic Validation (via code review)
- ✅ Agent tracking logic is sound
- ✅ Memory persistence logic is correct
- ✅ Session restoration logic is comprehensive
- ✅ Error handling is appropriate
## Risk Assessment
### Low Risk Changes
- Only modified Session class (isolated change)
- Used existing memory infrastructure
- Backward compatible implementation
- Graceful degradation for edge cases
### Edge Cases Handled
- Remote sessions (chat history persistence disabled)
- Empty chat histories (no unnecessary storage)
- Agent recreation (proper history restoration)
- Missing memory data (empty list fallback)
## Deployment Recommendation
This fix can be safely deployed because:
1. **Zero breaking changes** - existing code continues to work
2. **Minimal code footprint** - only Session class modified
3. **Uses existing infrastructure** - leverages current memory system
4. **Comprehensive error handling** - graceful fallbacks for edge cases
The implementation solves the reported issue while maintaining full backward compatibility and following the existing codebase patterns.
@@ -0,0 +1,250 @@
"""
Comprehensive Session Management Example
This example demonstrates advanced session management capabilities including
session persistence, recovery, state management, and multi-session coordination.
Features demonstrated:
- Session creation and persistence
- State management across sessions
- Session recovery after interruption
- Multi-user session coordination
- Session-specific memory and knowledge
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.session import Session
from praisonaiagents.tools import duckduckgo
import tempfile
import os
import json
# Create a temporary directory for session storage
session_dir = tempfile.mkdtemp()
print(f"Session storage directory: {session_dir}")
# Create agents for session-based workflows
research_agent = Agent(
name="SessionResearcher",
role="Research Specialist",
goal="Conduct research while maintaining session context",
backstory="You are a research specialist who maintains context across multiple sessions and can resume work from where you left off.",
tools=[duckduckgo],
instructions="Conduct thorough research and maintain awareness of previous session context when available."
)
analysis_agent = Agent(
name="SessionAnalyst",
role="Data Analyst",
goal="Analyze data while preserving session state",
backstory="You are a data analyst who can maintain analysis context across sessions and build upon previous work.",
instructions="Analyze research data and build upon any previous analysis from earlier sessions."
)
# Session 1: Initial Research Session
print("="*70)
print("SESSION 1: INITIAL RESEARCH SESSION")
print("="*70)
# Create first session
session1 = Session(
session_id="research_project_001",
user_id="user_researcher_01",
storage_path=session_dir
)
# Create initial research task
research_task1 = Task(
name="initial_research",
description="Research the latest trends in sustainable technology for manufacturing",
expected_output="Comprehensive research report on sustainable manufacturing technology trends",
agent=research_agent
)
# Create agents with session
agents_session1 = PraisonAIAgents(
agents=[research_agent],
tasks=[research_task1],
session=session1,
verbose=True
)
# Execute first session
print("Starting initial research session...")
result1 = agents_session1.start()
# Save session state
session1.save()
print(f"Session 1 completed and saved. Result preview: {str(result1)[:200]}...")
# Session 2: Analysis Session (same user, continuation)
print("\n" + "="*70)
print("SESSION 2: ANALYSIS SESSION (CONTINUING WORK)")
print("="*70)
# Create second session for analysis
session2 = Session(
session_id="research_project_002",
user_id="user_researcher_01", # Same user
storage_path=session_dir
)
# Load previous session context (simulating session recovery)
# In real usage, you might load from database or persistent storage
session2.set_state("previous_research_summary", str(result1)[:500])
analysis_task = Task(
name="trend_analysis",
description="Analyze the research findings to identify the top 5 most promising sustainable manufacturing technologies",
expected_output="Analysis report with top 5 sustainable manufacturing technologies and their potential impact",
agent=analysis_agent,
# Pass context from previous session
context_variables={"previous_research": str(result1)}
)
agents_session2 = PraisonAIAgents(
agents=[analysis_agent],
tasks=[analysis_task],
session=session2,
verbose=True
)
print("Starting analysis session with previous context...")
result2 = agents_session2.start()
# Save session state
session2.save()
print(f"Session 2 completed and saved. Result preview: {str(result2)[:200]}...")
# Session 3: Recovery Demonstration
print("\n" + "="*70)
print("SESSION 3: RECOVERY DEMONSTRATION")
print("="*70)
# Simulate session recovery after interruption
recovery_session = Session(
session_id="research_project_recovery",
user_id="user_researcher_01",
storage_path=session_dir
)
# Load state from previous sessions
recovery_session.set_state("research_summary", str(result1)[:300])
recovery_session.set_state("analysis_summary", str(result2)[:300])
# Create a synthesis task that uses recovered session state
synthesis_agent = Agent(
name="SynthesisAgent",
role="Research Synthesizer",
goal="Synthesize research and analysis into actionable recommendations",
backstory="You synthesize research and analysis from multiple sessions into comprehensive recommendations.",
instructions="Use the session context to create comprehensive recommendations based on all previous work."
)
synthesis_task = Task(
name="synthesis_report",
description="Create a comprehensive synthesis report with actionable recommendations based on all previous research and analysis",
expected_output="Executive synthesis report with strategic recommendations",
agent=synthesis_agent,
# Access session state
context_variables={
"research_context": recovery_session.get_state("research_summary"),
"analysis_context": recovery_session.get_state("analysis_summary")
}
)
agents_recovery = PraisonAIAgents(
agents=[synthesis_agent],
tasks=[synthesis_task],
session=recovery_session,
verbose=True
)
print("Starting recovery session with full context from previous sessions...")
result3 = agents_recovery.start()
# Save final session
recovery_session.save()
print(f"Recovery session completed. Result preview: {str(result3)[:200]}...")
# Session 4: Multi-User Coordination Demo
print("\n" + "="*70)
print("SESSION 4: MULTI-USER COORDINATION DEMO")
print("="*70)
# Create sessions for different users working on the same project
reviewer_session = Session(
session_id="peer_review_001",
user_id="user_reviewer_01", # Different user
storage_path=session_dir
)
# Reviewer can access shared project context
reviewer_session.set_state("shared_research", str(result1)[:400])
reviewer_session.set_state("shared_analysis", str(result2)[:400])
reviewer_session.set_state("shared_synthesis", str(result3)[:400])
review_agent = Agent(
name="PeerReviewer",
role="Research Peer Reviewer",
goal="Provide expert peer review of research, analysis, and synthesis",
backstory="You are a peer reviewer who evaluates research quality and provides constructive feedback.",
instructions="Review all provided work and provide constructive feedback with specific suggestions for improvement."
)
review_task = Task(
name="peer_review",
description="Conduct peer review of the research project including research, analysis, and synthesis phases",
expected_output="Comprehensive peer review with specific feedback and recommendations for improvement",
agent=review_agent,
context_variables={
"research_to_review": reviewer_session.get_state("shared_research"),
"analysis_to_review": reviewer_session.get_state("shared_analysis"),
"synthesis_to_review": reviewer_session.get_state("shared_synthesis")
}
)
agents_reviewer = PraisonAIAgents(
agents=[review_agent],
tasks=[review_task],
session=reviewer_session,
verbose=True
)
print("Starting peer review session by different user...")
result4 = agents_reviewer.start()
# Save reviewer session
reviewer_session.save()
print(f"Peer review session completed. Result preview: {str(result4)[:200]}...")
# Session Summary and Cleanup
print("\n" + "="*80)
print("SESSION MANAGEMENT DEMONSTRATION SUMMARY")
print("="*80)
# Display session information
print("Sessions created:")
print(f"1. Research Session (ID: research_project_001, User: user_researcher_01)")
print(f"2. Analysis Session (ID: research_project_002, User: user_researcher_01)")
print(f"3. Recovery Session (ID: research_project_recovery, User: user_researcher_01)")
print(f"4. Review Session (ID: peer_review_001, User: user_reviewer_01)")
print("\nSession capabilities demonstrated:")
print("- Session persistence and state management")
print("- Context passing between sessions")
print("- Session recovery after interruption")
print("- Multi-user session coordination")
print("- State sharing across different users")
print("- Session-specific task execution")
# List session files created
session_files = [f for f in os.listdir(session_dir) if f.endswith('.json')]
print(f"\nSession files created: {len(session_files)}")
for file in session_files:
print(f" - {file}")
# Cleanup
import shutil
shutil.rmtree(session_dir)
print(f"\nCleanup completed. Temporary session directory removed.")
@@ -0,0 +1,80 @@
"""
Advanced State Management Patterns Example
This example demonstrates state management using PraisonAI agents
with session-based state tracking and persistence.
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import internet_search
print("=== Advanced State Management Patterns Example ===\n")
# Configure session state for persistence
session_config = {
"session_id": "state_demo_001",
"persist": True
}
# Create agent with state management
state_agent = Agent(
name="State Manager Agent",
role="State-Aware Task Manager",
goal="Demonstrate advanced state management patterns",
backstory="Expert at managing task state and workflow progression with memory",
tools=[internet_search],
memory=True,
verbose=True
)
# Task 1: Initialize state and perform research
init_task = Task(
description="""Initialize project state and research electric vehicle market:
1. Set project phase to 'research'
2. Store initial findings about EV market size and growth
3. Track research progress and key insights
Remember the state for subsequent tasks.""",
expected_output="Research results with initialized state tracking",
agent=state_agent
)
# Task 2: Continue with state awareness
continue_task = Task(
description="""Continue from previous state and expand analysis:
1. Review stored research state from previous task
2. Analyze competitive landscape based on stored information
3. Update project phase to 'analysis'
4. Store competitive insights for next phase
Build upon previously stored state.""",
expected_output="Competitive analysis building on stored state",
agent=state_agent
)
# Task 3: Finalize using accumulated state
finalize_task = Task(
description="""Complete project using all accumulated state:
1. Review all stored research and analysis
2. Create final recommendations based on complete state
3. Set project phase to 'completed'
Use all accumulated state from previous tasks.""",
expected_output="Final recommendations using complete project state",
agent=state_agent
)
# Run with state management
agents_system = PraisonAIAgents(
agents=[state_agent],
tasks=[init_task, continue_task, finalize_task],
memory=True,
verbose=True
)
print("Starting state management demonstration...")
result = agents_system.start()
print(f"\nState Management Result: {result[:200]}...")
print("\n✅ State management patterns complete!")
print("Agent demonstrated persistent state tracking across multiple tasks.")
@@ -0,0 +1,236 @@
"""
Advanced Task Management Example
This example demonstrates sophisticated task management including conditional execution,
validation feedback loops, dynamic task routing, and complex task dependencies.
Features demonstrated:
- Conditional task execution based on results
- Validation feedback loops with retry mechanisms
- Dynamic task routing and decision trees
- Complex task dependencies and context passing
- Quality assurance workflows
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.task import TaskOutput
from praisonaiagents.tools import duckduckgo
from typing import Tuple, Any
import json
# Define validation functions for task outputs
def data_quality_validator(task_output: TaskOutput) -> Tuple[bool, Any]:
"""
Validates data quality and completeness for research tasks.
"""
output_text = str(task_output.raw).lower()
# Check for key quality indicators
quality_indicators = [
'source', 'data', 'research', 'study', 'analysis',
'findings', 'results', 'conclusion', 'evidence'
]
found_indicators = sum(1 for indicator in quality_indicators if indicator in output_text)
if found_indicators >= 4: # Require at least 4 quality indicators
return True, task_output
else:
return False, f"Data quality insufficient. Found {found_indicators} quality indicators but need at least 4. Please include more research sources, data analysis, and evidence."
def completeness_validator(task_output: TaskOutput) -> Tuple[bool, Any]:
"""
Validates that the analysis is complete and comprehensive.
"""
output_text = str(task_output.raw)
word_count = len(output_text.split())
# Check for completeness indicators
has_introduction = 'introduction' in output_text.lower() or output_text.startswith(('In ', 'The ', 'This '))
has_conclusion = any(word in output_text.lower() for word in ['conclusion', 'summary', 'in summary', 'to conclude'])
sufficient_length = word_count >= 100
if has_introduction and has_conclusion and sufficient_length:
return True, task_output
else:
missing = []
if not has_introduction:
missing.append("proper introduction")
if not has_conclusion:
missing.append("conclusion or summary")
if not sufficient_length:
missing.append(f"sufficient detail (need 100+ words, found {word_count})")
return False, f"Analysis incomplete. Missing: {', '.join(missing)}. Please provide a more comprehensive response."
# Create specialized agents for the workflow
research_agent = Agent(
name="ResearchAgent",
role="Senior Research Analyst",
goal="Conduct comprehensive research and gather high-quality data",
backstory="You are a senior research analyst with expertise in data collection and analysis.",
tools=[duckduckgo],
instructions="Conduct thorough research using multiple sources. Provide detailed findings with proper citations and data analysis."
)
quality_checker = Agent(
name="QualityChecker",
role="Quality Assurance Specialist",
goal="Validate research quality and completeness",
backstory="You are a QA specialist who ensures all research meets high standards of quality and completeness.",
instructions="Review research outputs for quality, accuracy, and completeness. Provide specific feedback for improvements."
)
analyst = Agent(
name="DataAnalyst",
role="Data Analysis Expert",
goal="Analyze research data and identify key insights",
backstory="You are a data analysis expert who can identify patterns, trends, and actionable insights from research data.",
instructions="Analyze research data to identify key trends, patterns, and strategic insights. Provide data-driven recommendations."
)
decision_maker = Agent(
name="DecisionMaker",
role="Strategic Decision Maker",
goal="Make strategic decisions based on analysis results",
backstory="You are a strategic decision maker who evaluates analysis results and determines next steps.",
instructions="Review analysis results and make strategic decisions about whether to proceed, modify approach, or conduct additional research."
)
report_writer = Agent(
name="ReportWriter",
role="Executive Report Writer",
goal="Create comprehensive executive reports",
backstory="You are an executive report writer who synthesizes research and analysis into actionable business reports.",
instructions="Create comprehensive executive reports that synthesize research findings and analysis into clear, actionable recommendations."
)
# Define conditional task execution workflow
# Initial research task with quality validation
initial_research = Task(
name="initial_research",
description="Research the current state of renewable energy adoption in the business sector, including trends, challenges, and opportunities",
expected_output="Comprehensive research report on renewable energy adoption in business",
agent=research_agent,
guardrail=data_quality_validator,
max_retries=3
)
# Quality check task - conditional on research quality
quality_check = Task(
name="quality_assessment",
description="Assess the quality and completeness of the research findings. Determine if additional research is needed.",
expected_output="Quality assessment report with go/no-go decision for proceeding to analysis",
agent=quality_checker,
context=[initial_research],
guardrail=completeness_validator,
max_retries=2
)
# Conditional task - only execute if quality check passes
data_analysis = Task(
name="data_analysis",
description="Analyze the research data to identify key trends, market opportunities, and strategic recommendations for renewable energy adoption",
expected_output="Strategic analysis with key insights and recommendations",
agent=analyst,
context=[initial_research, quality_check],
# Conditional execution based on quality check
task_type="decision",
condition={
"proceed": ["final_report"], # If analysis is good, proceed to final report
"needs_more_research": ["additional_research"], # If needs more data, do additional research
"insufficient_data": [] # If data is insufficient, stop workflow
}
)
# Additional research task (conditional execution)
additional_research = Task(
name="additional_research",
description="Conduct additional targeted research to fill gaps identified in the quality assessment",
expected_output="Supplementary research addressing identified gaps",
agent=research_agent,
context=[initial_research, quality_check],
tools=[duckduckgo],
guardrail=data_quality_validator,
max_retries=2
)
# Decision point task
decision_task = Task(
name="strategic_decision",
description="Based on all available research and analysis, make a strategic decision about renewable energy investment recommendations",
expected_output="Strategic decision with clear reasoning and recommended next steps",
agent=decision_maker,
context=[initial_research, quality_check, data_analysis],
# This task determines the workflow path
task_type="decision",
condition={
"high_confidence": ["final_report"],
"medium_confidence": ["risk_analysis"],
"low_confidence": ["additional_research"]
}
)
# Risk analysis task (conditional)
risk_analysis = Task(
name="risk_analysis",
description="Conduct detailed risk analysis for renewable energy investment recommendations",
expected_output="Comprehensive risk assessment with mitigation strategies",
agent=analyst,
context=[initial_research, data_analysis, decision_task]
)
# Final report task
final_report = Task(
name="final_report",
description="Create a comprehensive executive report synthesizing all research, analysis, and strategic recommendations",
expected_output="Executive report with strategic recommendations for renewable energy adoption",
agent=report_writer,
context=[initial_research, quality_check, data_analysis, decision_task],
guardrail=completeness_validator,
max_retries=2
)
# Create workflow with conditional execution
workflow = PraisonAIAgents(
agents=[research_agent, quality_checker, analyst, decision_maker, report_writer],
tasks=[
initial_research,
quality_check,
data_analysis,
additional_research, # Conditional
decision_task,
risk_analysis, # Conditional
final_report
],
process="workflow", # Use workflow process for conditional execution
verbose=True
)
print("="*80)
print("EXECUTING ADVANCED TASK MANAGEMENT WORKFLOW")
print("="*80)
print("This workflow includes:")
print("- Quality validation with retry mechanisms")
print("- Conditional task execution based on results")
print("- Dynamic routing and decision points")
print("- Complex task dependencies")
print("="*80)
# Execute the conditional workflow
result = workflow.start()
print("\n" + "="*80)
print("ADVANCED TASK MANAGEMENT COMPLETED")
print("="*80)
print("This example demonstrated:")
print("- Conditional task execution based on validation results")
print("- Quality validation with specific feedback for improvements")
print("- Dynamic workflow routing with decision points")
print("- Complex task dependencies and context passing")
print("- Retry mechanisms with iterative improvement")
print("- Multi-stage validation and quality assurance")
print(f"\nFinal Result Summary:\n{result}")
@@ -0,0 +1,286 @@
"""
Production Telemetry Example
This example demonstrates comprehensive telemetry and monitoring setup for
production AI agent systems, including metrics collection, performance tracking,
and observability.
Features demonstrated:
- OpenTelemetry integration for distributed tracing
- Custom metrics collection and monitoring
- Performance tracking and analytics
- Error tracking and alerting
- Usage analytics and reporting
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import duckduckgo
from praisonaiagents.telemetry import enable_telemetry
import time
import random
from datetime import datetime
# Initialize telemetry for production monitoring
print("="*80)
print("PRODUCTION TELEMETRY SETUP")
print("="*80)
# Configure telemetry (in production, you'd use actual telemetry backends)
telemetry = enable_telemetry(
backend="opentelemetry",
config={
"service_name": "praisonai_production_agents",
"service_version": "1.0.0",
"environment": "production",
"export_console": True, # For demo purposes
"export_file": True, # Export to file for analysis
"sample_rate": 1.0, # 100% sampling for demo
"attributes": {
"deployment": "cloud",
"region": "us-east-1",
"cluster": "main"
}
}
)
# Create agents for production workflow with telemetry
customer_service_agent = Agent(
name="CustomerServiceAgent",
role="Customer Service Representative",
goal="Provide excellent customer service with fast response times",
backstory="You are a customer service representative focused on resolving customer issues quickly and effectively.",
tools=[duckduckgo],
instructions="Provide helpful, accurate customer service responses. Research solutions when needed."
)
technical_support_agent = Agent(
name="TechnicalSupportAgent",
role="Technical Support Specialist",
goal="Resolve technical issues with detailed solutions",
backstory="You are a technical support specialist who provides detailed technical solutions and troubleshooting.",
instructions="Provide detailed technical solutions with step-by-step instructions."
)
quality_assurance_agent = Agent(
name="QualityAssuranceAgent",
role="Quality Assurance Specialist",
goal="Ensure all customer interactions meet quality standards",
backstory="You review and assess the quality of customer service interactions to ensure high standards.",
instructions="Review customer service interactions and provide quality scores with detailed feedback."
)
# Production workflow simulation with telemetry tracking
def simulate_customer_requests():
"""Simulate various customer requests for telemetry demonstration"""
customer_requests = [
{
"type": "billing_inquiry",
"complexity": "low",
"description": "Customer asking about their monthly bill charges",
"expected_duration": 30
},
{
"type": "technical_issue",
"complexity": "high",
"description": "Customer experiencing connectivity issues with the service",
"expected_duration": 120
},
{
"type": "account_setup",
"complexity": "medium",
"description": "New customer needs help setting up their account",
"expected_duration": 60
},
{
"type": "feature_question",
"complexity": "low",
"description": "Customer asking about product features and capabilities",
"expected_duration": 45
}
]
return customer_requests
# Execute production workflow with comprehensive telemetry
print("Starting production workflow with telemetry tracking...")
customer_requests = simulate_customer_requests()
for i, request in enumerate(customer_requests):
print(f"\n{'='*60}")
print(f"PROCESSING CUSTOMER REQUEST {i+1}: {request['type'].upper()}")
print(f"Complexity: {request['complexity']} | Expected Duration: {request['expected_duration']}s")
print(f"{'='*60}")
# Start telemetry trace for this customer interaction
with telemetry.trace_operation(f"customer_request_{request['type']}") as trace:
# Add custom attributes to the trace
trace.set_attributes({
"request.type": request['type'],
"request.complexity": request['complexity'],
"request.expected_duration": request['expected_duration'],
"customer.id": f"customer_{random.randint(1000, 9999)}",
"agent.assigned": "CustomerServiceAgent"
})
start_time = time.time()
# Create customer service task with telemetry
customer_task = Task(
name=f"customer_request_{i+1}",
description=request['description'],
expected_output="Professional customer service response with solution",
agent=customer_service_agent
)
# Execute with telemetry tracking
try:
# Customer service response
with telemetry.trace_agent_execution("CustomerServiceAgent") as agent_trace:
agents = PraisonAIAgents(
agents=[customer_service_agent],
tasks=[customer_task],
verbose=False # Reduce verbosity for telemetry demo
)
cs_result = agents.start()
agent_trace.set_attributes({
"agent.response_length": len(str(cs_result)),
"agent.tools_used": len(customer_service_agent.tools) if customer_service_agent.tools else 0
})
# Technical support (if needed for high complexity)
if request['complexity'] == 'high':
with telemetry.trace_agent_execution("TechnicalSupportAgent") as tech_trace:
tech_task = Task(
name=f"technical_support_{i+1}",
description=f"Provide detailed technical support for: {request['description']}",
expected_output="Detailed technical solution with troubleshooting steps",
agent=technical_support_agent,
context=[customer_task]
)
tech_agents = PraisonAIAgents(
agents=[technical_support_agent],
tasks=[tech_task],
verbose=False
)
tech_result = tech_agents.start()
tech_trace.set_attributes({
"agent.response_length": len(str(tech_result)),
"agent.escalation": True
})
# Quality assurance check
with telemetry.trace_agent_execution("QualityAssuranceAgent") as qa_trace:
qa_task = Task(
name=f"quality_check_{i+1}",
description=f"Review the quality of customer service provided for: {request['description']}",
expected_output="Quality assessment score and feedback",
agent=quality_assurance_agent
)
qa_agents = PraisonAIAgents(
agents=[quality_assurance_agent],
tasks=[qa_task],
verbose=False
)
qa_result = qa_agents.start()
# Extract quality score (simulated)
quality_score = random.uniform(0.8, 1.0) # Simulated score
qa_trace.set_attributes({
"qa.score": quality_score,
"qa.passed": quality_score >= 0.85
})
# Calculate performance metrics
end_time = time.time()
duration = end_time - start_time
# Record custom metrics
telemetry.record_metric("request_duration", duration, {
"request_type": request['type'],
"complexity": request['complexity']
})
telemetry.record_metric("request_success", 1, {
"request_type": request['type']
})
# Set final trace attributes
trace.set_attributes({
"request.duration_seconds": duration,
"request.status": "completed",
"request.quality_score": quality_score,
"request.escalated": request['complexity'] == 'high'
})
print(f"✅ Request completed successfully in {duration:.2f}s (Quality: {quality_score:.2f})")
except Exception as e:
# Record error metrics
telemetry.record_metric("request_error", 1, {
"request_type": request['type'],
"error_type": type(e).__name__
})
trace.set_attributes({
"request.status": "error",
"request.error": str(e)
})
print(f"❌ Request failed: {str(e)}")
# Add some delay between requests
time.sleep(2)
# Generate telemetry summary
print(f"\n{'='*80}")
print("TELEMETRY SUMMARY AND ANALYTICS")
print(f"{'='*80}")
# Simulated telemetry analytics (in production, this would come from your telemetry backend)
print("📊 Performance Metrics:")
print("- Total Requests Processed: 4")
print("- Average Response Time: 3.2s")
print("- Success Rate: 100%")
print("- Quality Score Average: 0.91")
print("- High Complexity Requests: 25%")
print("\n📈 Usage Analytics:")
print("- Most Common Request Type: technical_issue")
print("- Peak Performance Window: All requests within SLA")
print("- Agent Utilization: CustomerService (100%), TechnicalSupport (25%), QA (100%)")
print("\n🔍 Observability Features Demonstrated:")
print("- Distributed tracing across agent interactions")
print("- Custom metrics for business KPIs")
print("- Performance monitoring and SLA tracking")
print("- Error tracking and alerting")
print("- Quality assurance metrics")
print("- User journey tracking")
print("- Resource utilization monitoring")
print("\n⚙️ Production Monitoring Setup:")
print("- OpenTelemetry integration for standardized observability")
print("- Custom metrics for business-specific KPIs")
print("- Trace correlation across multi-agent workflows")
print("- Performance benchmarking against expected durations")
print("- Quality scoring and automated validation")
print("- Error categorization and alerting")
print(f"\n{'='*80}")
print("TELEMETRY DEMONSTRATION COMPLETED")
print(f"{'='*80}")
print("This example demonstrated comprehensive production telemetry including:")
print("- Request tracing and performance monitoring")
print("- Custom business metrics collection")
print("- Quality assurance tracking")
print("- Error handling and alerting")
print("- Multi-agent workflow observability")
print("- Production-ready monitoring patterns")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are an audio tour creation AI agent. "
"Help users create engaging audio tours, guided experiences, and interactive storytelling content. "
"Provide guidance on script writing, audio production, location-based content, and immersive experiences.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your audio tour creation assistant. "
"How can I help you create captivating audio experiences today?")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a chess AI agent. "
"Help users improve their chess skills, analyze positions, develop strategies, and understand chess theory. "
"Provide move analysis, opening guidance, endgame techniques, and tactical training.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your chess assistant. "
"How can I help you improve your chess game today?")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a creative writing AI agent. "
"Help users develop compelling stories, characters, dialogue, and narrative structures. "
"Provide guidance on plot development, world-building, genre-specific techniques, and creative inspiration.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your creative writing assistant. "
"How can I help you bring your stories and ideas to life today?")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a cybersecurity AI agent. "
"Help users with security assessments, threat analysis, vulnerability management, and security best practices. "
"Provide guidance on penetration testing, secure coding, incident response, and compliance frameworks.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your cybersecurity assistant. "
"How can I help you secure your systems and protect against threats today?")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a data visualization AI agent. "
"Help users create compelling charts, graphs, dashboards, and interactive visualizations. "
"Provide guidance on matplotlib, seaborn, plotly, Tableau, and best practices for effective data storytelling.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your data visualization assistant. "
"How can I help you create stunning visual representations of your data today?")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a 3D PyGame development AI agent. "
"Help users create 3D games, simulations, and interactive experiences using PyGame. "
"Provide code examples, debugging assistance, and best practices for 3D graphics programming.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your 3D PyGame development assistant. "
"How can I help you create amazing 3D games today?")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a self-evolving AI agent. "
"Continuously learn from interactions, adapt your responses, and improve your capabilities. "
"Help users with complex problem-solving, creative tasks, and provide insights that evolve based on context and user needs.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your self-evolving AI assistant. "
"How can I help you today, and how can I learn and improve from our interaction?")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a startup insight AI agent. "
"Help entrepreneurs and startup teams with market analysis, business strategy, funding advice, product development, and growth tactics. "
"Provide actionable insights for building successful startups.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your startup insight assistant. "
"How can I help you build and grow your startup today?")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a system architecture AI agent. "
"Help users design scalable, efficient, and robust system architectures. "
"Provide guidance on microservices, cloud infrastructure, database design, API design, and system integration patterns.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your system architecture assistant. "
"How can I help you design and optimize your system architecture today?")
@@ -0,0 +1,11 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a web scraping AI agent. "
"Help users create efficient and ethical web scrapers, data extraction tools, and automation scripts. "
"Provide guidance on BeautifulSoup, Selenium, Scrapy, and best practices for responsible web scraping.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your web scraping assistant. "
"How can I help you extract and analyze web data today?")
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a competitor intelligence AI agent. "
"Help users analyze competitors, market trends, and business intelligence "
"to provide strategic insights and competitive advantages.",
llm="xai/grok-4"
)
response = agent.start(
"I need to analyze my main competitor's pricing strategy and market positioning. "
"Can you help me gather insights?"
)
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a finance AI agent. "
"Help users with financial analysis, investment strategies, "
"budget planning, and market trend analysis for informed decision making.",
llm="xai/grok-4"
)
response = agent.start(
"I need to analyze my investment portfolio and create a diversification strategy. "
"Can you help me optimize my financial planning?"
)
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a game design AI agent. "
"Help users with game concept development, mechanics design, "
"and creative storytelling for various gaming platforms and genres.",
llm="xai/grok-4"
)
response = agent.start(
"I want to create a mobile puzzle game concept. "
"Can you help me design engaging gameplay mechanics and story elements?"
)
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a legal AI agent. "
"Help users with legal document analysis, contract review, "
"and legal advice while ensuring compliance and risk assessment.",
llm="xai/grok-4"
)
response = agent.start(
"I need to review a software licensing agreement. "
"Can you help me identify potential risks and key terms?"
)
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a recruitment AI agent. "
"Help users with candidate screening, job posting optimization, "
"and recruitment process automation to find the best talent.",
llm="xai/grok-4"
)
response = agent.start(
"I need to create a job posting for a senior software engineer position. "
"Can you help me write an attractive and comprehensive job description?"
)
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are an AI services agency agent. "
"Help users with comprehensive business services including marketing, "
"content creation, strategy, and operational optimization using CrewAI framework.",
llm="xai/grok-4"
)
response = agent.start(
"I need help with my startup's marketing strategy and content creation. "
"Can you provide a comprehensive plan?"
)
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are an AI teaching agent. "
"Help users with educational content creation, lesson planning, "
"and personalized learning experiences across various subjects.",
llm="xai/grok-4"
)
response = agent.start(
"I need to create a lesson plan for teaching Python programming to beginners. "
"Can you help me design an engaging curriculum?"
)
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a data analysis AI agent. Help users analyze datasets, create visualizations, and extract meaningful insights from data.",
llm="xai/grok-4"
)
response = agent.start("I have sales data for the last quarter. Can you help me identify trends and patterns?")
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a deep research AI agent. Conduct comprehensive research, analyze complex topics, and provide detailed insights on various subjects.",
llm="xai/grok-4"
)
response = agent.start("I need to research the impact of artificial intelligence on job markets. Can you provide a comprehensive analysis?")
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a health and fitness AI agent. Help users with workout plans, nutrition advice, wellness tips, and health monitoring guidance.",
llm="xai/grok-4"
)
response = agent.start("I want to lose 20 pounds and build muscle. What's the best workout and nutrition plan for me?")
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are an investment advisor AI agent. Help users with investment strategies, portfolio analysis, risk assessment, and market insights.",
llm="xai/grok-4"
)
response = agent.start("I have $50,000 to invest. What would be a good diversified portfolio for someone in their 30s?")
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a journalist AI agent. Help with news writing, article creation, fact-checking, and content generation for various media platforms.",
llm="xai/grok-4"
)
response = agent.start("I need to write an article about the latest developments in renewable energy. Can you help me structure it?")
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a medical imaging AI agent. Help analyze medical images, provide preliminary assessments, and assist healthcare professionals with diagnostic support.",
llm="xai/grok-4"
)
response = agent.start("I have an X-ray image that needs analysis. Can you help identify any abnormalities?")
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a music generation AI agent. Help users create melodies, lyrics, and musical compositions based on their preferences and requirements.",
llm="xai/grok-4"
)
response = agent.start("I need a catchy jingle for my coffee shop. Can you help me create one?")
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a personal finance AI agent. Help users with budgeting, saving strategies, debt management, and financial planning advice.",
llm="xai/grok-4"
)
response = agent.start("I want to save $10,000 in the next year. What's the best strategy for me?")
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a startup trend analysis AI agent. Help entrepreneurs identify market opportunities, analyze industry trends, and evaluate business ideas.",
llm="xai/grok-4"
)
response = agent.start("I'm thinking of starting a tech startup. What are the current trending opportunities in the market?")
@@ -0,0 +1,8 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a travel planning AI agent. Help users plan trips, find destinations, and create itineraries with budget considerations.",
llm="xai/grok-4"
)
response = agent.start("I want to plan a 7-day trip to Europe with a budget of $3000. What are my best options?")
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a multi MCP AI agent. "
"Help users integrate and coordinate multiple Model Context Protocol agents "
"for complex workflows and cross-platform automation.",
llm="xai/grok-4"
)
response = agent.start(
"I need to coordinate multiple tools and services for my project. "
"Can you help me set up an integrated workflow using MCP agents?"
)
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a multimodal coding AI agent. "
"Help users with code generation, review, and debugging "
"by analyzing both text and visual inputs like screenshots and diagrams.",
llm="xai/grok-4"
)
response = agent.start(
"I have a screenshot of a UI design and need to generate the corresponding HTML/CSS code. "
"Can you help me create the frontend code?"
)
@@ -0,0 +1,13 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a multimodal design AI agent. "
"Help users with graphic design, UI/UX design, and visual content creation "
"by analyzing text descriptions and visual references.",
llm="xai/grok-4"
)
response = agent.start(
"I need to create a logo for my tech startup. "
"Can you help me design a modern and professional logo concept?"
)
@@ -196,4 +196,4 @@ def main():
print("Make sure SearxNG is running at http://localhost:32768")
if __name__ == "__main__":
main()
main()
@@ -0,0 +1,420 @@
#!/usr/bin/env python3
"""
Custom Trafilatura Tools for High-Quality URL Content Extraction
This is an example of creating custom tools for PraisonAI agents.
This tool is not part of the core package - it's a standalone custom tool
that demonstrates how to implement web content extraction using Trafilatura.
Install dependencies:
pip install trafilatura newspaper3k
Usage:
from custom_trafilatura_tools import TrafilaturaTools
tools = TrafilaturaTools()
content = tools.extract_content("https://example.com/article")
metadata = tools.extract_metadata("https://example.com/article")
"""
import logging
from typing import Dict, Any, Optional, Union, List
from importlib import util
import json
from urllib.parse import urlparse
class TrafilaturaTools:
"""Custom tools for extracting high-quality content from URLs using Trafilatura."""
def __init__(self):
"""Initialize TrafilaturaTools and check for required packages."""
self.trafilatura = self._check_and_import_trafilatura()
def _check_and_import_trafilatura(self):
"""Check if trafilatura package is installed and import it."""
if util.find_spec("trafilatura") is None:
raise ImportError(
"trafilatura package is not available. Please install it using: pip install trafilatura"
)
import trafilatura
return trafilatura
def _validate_url(self, url: str) -> bool:
"""
Validate URL to prevent SSRF attacks.
Args:
url: URL to validate
Returns:
bool: True if URL is safe, False otherwise
"""
try:
parsed = urlparse(url)
# Only allow http/https protocols
if parsed.scheme not in ['http', 'https']:
return False
# Reject URLs with no hostname
if not parsed.hostname:
return False
# Reject local/internal addresses
hostname = parsed.hostname.lower()
# Block localhost and loopback
if hostname in ['localhost', '127.0.0.1', '0.0.0.0', '::1']:
return False
# Block private IP ranges
import ipaddress
try:
ip = ipaddress.ip_address(hostname)
if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local:
return False
except ValueError:
# Not an IP address, continue with domain validation
pass
# Block common internal domains
if any(hostname.endswith(domain) for domain in ['.local', '.internal', '.localdomain']):
return False
# Block metadata service endpoints
return hostname not in ['169.254.169.254', 'metadata.google.internal']
except Exception:
return False
def extract_content(
self,
url: str,
include_comments: bool = False,
include_links: bool = True,
output_format: str = 'json',
include_metadata: bool = True,
target_language: Optional[str] = None
) -> Union[Dict[str, Any], str]:
"""
Extract high-quality content from a URL using Trafilatura.
Args:
url: URL to extract content from
include_comments: Include comments in extraction
include_links: Include links in extraction
output_format: Output format ('json', 'text', 'xml')
include_metadata: Include metadata in extraction
target_language: Target language for extraction (None for auto-detect)
Returns:
Dict or str: Extracted content (dict for json format, str for text/xml)
"""
# Validate URL
if not self._validate_url(url):
error_msg = f"Invalid or unsafe URL: {url}"
logging.error(error_msg)
return {"error": error_msg} if output_format == 'json' else error_msg
try:
# Fetch the URL content
downloaded = self.trafilatura.fetch_url(url)
if not downloaded:
error_msg = f"Could not fetch content from URL: {url}"
logging.error(error_msg)
return {"error": error_msg} if output_format == 'json' else error_msg
# Extract content
extracted = self.trafilatura.extract(
downloaded,
include_comments=include_comments,
include_links=include_links,
output_format=output_format,
with_metadata=include_metadata,
url=url,
target_language=target_language
)
if not extracted:
error_msg = f"Could not extract readable content from: {url}"
logging.warning(error_msg)
return {"error": error_msg} if output_format == 'json' else error_msg
# Parse JSON output if requested
if output_format == 'json':
return json.loads(extracted)
else:
return extracted
except Exception as e:
error_msg = f"Error extracting content from {url}: {str(e)}"
logging.error(error_msg)
return {"error": error_msg} if output_format == 'json' else error_msg
def extract_metadata(self, url: str) -> Dict[str, Any]:
"""
Extract metadata from a URL.
Args:
url: URL to extract metadata from
Returns:
Dict: Metadata including title, author, date, etc.
"""
# Validate URL
if not self._validate_url(url):
error_msg = f"Invalid or unsafe URL: {url}"
logging.error(error_msg)
return {"error": error_msg}
try:
# Fetch the URL content
downloaded = self.trafilatura.fetch_url(url)
if not downloaded:
error_msg = f"Could not fetch content from URL: {url}"
logging.error(error_msg)
return {"error": error_msg}
# Extract metadata
metadata = self.trafilatura.extract_metadata(downloaded, url=url)
if not metadata:
return {
"url": url,
"error": "No metadata found"
}
# Convert metadata object to dict
result = {
"url": url,
"title": metadata.title,
"author": metadata.author,
"date": metadata.date,
"description": metadata.description,
"categories": metadata.categories,
"tags": metadata.tags,
"language": metadata.language,
"image": metadata.image,
"pagetype": metadata.pagetype,
"license": metadata.license
}
# Remove None values
result = {k: v for k, v in result.items() if v is not None}
return result
except Exception as e:
error_msg = f"Error extracting metadata from {url}: {str(e)}"
logging.error(error_msg)
return {"error": error_msg}
def extract_text_only(
self,
url: str,
include_comments: bool = False
) -> str:
"""
Extract only the main text content from a URL.
Args:
url: URL to extract text from
include_comments: Include comments in extraction
Returns:
str: Extracted text content
"""
result = self.extract_content(
url=url,
include_comments=include_comments,
include_links=False,
output_format='text',
include_metadata=False
)
return result
def compare_extraction(
self,
url: str,
include_newspaper: bool = True,
include_spider: bool = True
) -> Dict[str, Any]:
"""
Compare Trafilatura extraction with other tools for the same URL.
Args:
url: URL to extract content from
include_newspaper: Include newspaper3k comparison
include_spider: Include spider_tools comparison (if available)
Returns:
Dict: Comparison of extraction results
"""
comparison = {
"url": url,
"trafilatura": None,
"newspaper": None,
"spider": None
}
# Get Trafilatura extraction
try:
comparison["trafilatura"] = self.extract_content(url)
except Exception as e:
comparison["trafilatura"] = {"error": str(e)}
# Get Newspaper extraction if requested
if include_newspaper:
try:
# Try to import and use newspaper3k
if util.find_spec("newspaper") is not None:
import newspaper
article = newspaper.Article(url)
article.download()
article.parse()
comparison["newspaper"] = {
"title": article.title,
"text": article.text,
"authors": article.authors,
"publish_date": str(article.publish_date) if article.publish_date else None,
"top_image": article.top_image,
"summary": article.summary if hasattr(article, 'summary') else None
}
else:
comparison["newspaper"] = {"error": "newspaper3k not installed"}
except Exception as e:
comparison["newspaper"] = {"error": str(e)}
# Get Spider extraction if requested (placeholder for external spider tools)
if include_spider:
try:
# This is a placeholder - you could integrate with other scraping tools here
# For now, we'll use a simple requests + BeautifulSoup approach
if util.find_spec("requests") and util.find_spec("bs4"):
import requests
from bs4 import BeautifulSoup
response = requests.get(url, timeout=10)
soup = BeautifulSoup(response.content, 'html.parser')
# Extract basic content
title = soup.find('title')
title_text = title.get_text().strip() if title else None
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Get text
text = soup.get_text()
# Clean up whitespace
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = ' '.join(chunk for chunk in chunks if chunk)
comparison["spider"] = {
"title": title_text,
"text": text[:2000], # Limit to first 2000 chars
"method": "requests+beautifulsoup"
}
else:
comparison["spider"] = {"error": "requests or beautifulsoup4 not installed"}
except Exception as e:
comparison["spider"] = {"error": str(e)}
return comparison
def get_available_methods(self) -> List[str]:
"""
Get list of available methods in this tool.
Returns:
List[str]: List of method names
"""
return [
'extract_content',
'extract_metadata',
'extract_text_only',
'compare_extraction'
]
# Convenience functions for easier usage
def create_trafilatura_tools() -> TrafilaturaTools:
"""Create and return a TrafilaturaTools instance."""
return TrafilaturaTools()
# Test the tool
if __name__ == "__main__":
# Test URL
test_url = "https://www.python.org/about/"
print("Testing Custom Trafilatura Tools")
print("=" * 50)
try:
# Create tools instance
tools = TrafilaturaTools()
# Test 1: Extract content
print("\n1. Testing extract_content():")
print("-" * 50)
content = tools.extract_content(test_url)
if isinstance(content, dict) and 'error' not in content:
print(f"✓ Title: {content.get('title', 'N/A')}")
print(f"✓ Language: {content.get('language', 'N/A')}")
print(f"✓ Text length: {len(content.get('text', ''))} characters")
print(f"✓ Author: {content.get('author', 'N/A')}")
print(f"✓ Date: {content.get('date', 'N/A')}")
else:
print(f"✗ Error: {content}")
# Test 2: Extract metadata
print("\n2. Testing extract_metadata():")
print("-" * 50)
metadata = tools.extract_metadata(test_url)
if isinstance(metadata, dict) and 'error' not in metadata:
print("✓ Metadata extracted successfully:")
for key, value in metadata.items():
if key != 'url':
print(f" - {key}: {value}")
else:
print(f"✗ Error: {metadata}")
# Test 3: Extract text only
print("\n3. Testing extract_text_only():")
print("-" * 50)
text = tools.extract_text_only(test_url)
if isinstance(text, str) and text and "error" not in text.lower():
print(f"✓ Text extracted: {len(text)} characters")
print(f"✓ Preview: {text[:150]}...")
else:
print(f"✗ Error: {text}")
# Test 4: Test URL validation
print("\n4. Testing URL validation (security):")
print("-" * 50)
unsafe_urls = ["http://localhost/test", "http://127.0.0.1/test"]
for unsafe_url in unsafe_urls:
result = tools.extract_content(unsafe_url)
if isinstance(result, dict) and 'error' in result and 'Invalid or unsafe URL' in result['error']:
print(f"✓ Correctly rejected: {unsafe_url}")
else:
print(f"✗ Failed to reject: {unsafe_url}")
# Test 5: Available methods
print("\n5. Available methods:")
print("-" * 50)
methods = tools.get_available_methods()
for method in methods:
print(f"✓ {method}")
except Exception as e:
print(f"✗ Failed to initialize tools: {e}")
print("\nMake sure to install dependencies:")
print("pip install trafilatura newspaper3k requests beautifulsoup4")
print("\n" + "=" * 50)
print("Custom Trafilatura Tools testing complete!")
@@ -0,0 +1,266 @@
#!/usr/bin/env python3
"""
Example: Using Custom Trafilatura Tools for High-Quality URL Content Extraction
This example demonstrates how to create and use custom Trafilatura tools in PraisonAI
for extracting high-quality content from web pages.
This shows how to create custom tools that are not part of the core package.
Install dependencies:
pip install trafilatura newspaper3k requests beautifulsoup4
"""
import asyncio
from praisonaiagents import Agent, Task, PraisonAIAgents
from custom_trafilatura_tools import TrafilaturaTools, create_trafilatura_tools
# Create tools instance (global for reuse across examples)
tools = None
def get_tools():
"""Get or create tools instance"""
global tools
if tools is None:
tools = create_trafilatura_tools()
return tools
# Example 1: Basic content extraction
async def basic_extraction_example():
"""Extract content from a URL using custom Trafilatura tools"""
tools_instance = get_tools()
# Extract content from a URL
url = "https://www.python.org/about/"
content = await asyncio.to_thread(tools_instance.extract_content, url)
if 'error' not in content:
print(f"Title: {content.get('title', 'N/A')}")
print(f"Author: {content.get('author', 'N/A')}")
print(f"Date: {content.get('date', 'N/A')}")
print(f"Text preview: {content.get('text', '')[:200]}...")
else:
print(f"Error: {content['error']}")
# Example 2: Extract text only
async def text_only_example():
"""Extract only the main text content"""
tools_instance = get_tools()
url = "https://www.python.org/about/"
text = await asyncio.to_thread(tools_instance.extract_text_only, url)
print(f"Extracted text ({len(text)} characters):")
print(f"{text[:300]}...")
# Example 3: Extract metadata
async def metadata_example():
"""Extract metadata from a web page"""
tools_instance = get_tools()
url = "https://www.python.org/about/"
metadata = await asyncio.to_thread(tools_instance.extract_metadata, url)
print("Page metadata:")
for key, value in metadata.items():
if key != 'url':
print(f" {key}: {value}")
# Example 4: Compare extraction methods
async def comparison_example():
"""Compare Trafilatura with other extraction tools"""
tools_instance = get_tools()
url = "https://www.python.org/about/"
comparison = await asyncio.to_thread(
tools_instance.compare_extraction,
url,
include_newspaper=True, # Compare with newspaper3k
include_spider=True # Compare with basic scraping
)
print("Extraction comparison:")
for tool, result in comparison.items():
if tool != 'url' and result:
if isinstance(result, dict) and 'error' not in result:
print(f"\n{tool.upper()}:")
if 'title' in result:
print(f" Title: {result.get('title', 'N/A')}")
if 'text' in result:
text_len = len(result.get('text', ''))
print(f" Text length: {text_len} characters")
else:
print(f"\n{tool.upper()}: {result}")
# Example 5: Using Custom Trafilatura tools with an Agent
async def agent_example():
"""Use custom Trafilatura tools with an AI agent"""
tools_instance = get_tools()
# Create wrapper functions for the agent to use
def extract_content_tool(url: str) -> dict:
"""Extract content from URL using Trafilatura"""
return tools_instance.extract_content(url)
def extract_metadata_tool(url: str) -> dict:
"""Extract metadata from URL using Trafilatura"""
return tools_instance.extract_metadata(url)
# Create a research agent with custom Trafilatura tools
research_agent = Agent(
name="Research Assistant",
role="Web Content Analyzer",
goal="Extract and analyze content from web pages using custom tools",
backstory="You are an expert at extracting and analyzing web content using custom Trafilatura tools",
tools=[extract_content_tool, extract_metadata_tool],
llm="gpt-4o-mini"
)
# Create a task for content analysis
analysis_task = Task(
description="""
Extract content from this URL: https://www.python.org/about/
Use the custom Trafilatura tools to provide a summary of:
1. The main content and purpose of the page
2. Key metadata (author, date, language)
3. The overall quality and structure of the content
""",
expected_output="A comprehensive analysis of the web page content using custom tools",
agent=research_agent
)
# Run the analysis
agents = PraisonAIAgents(
agents=[research_agent],
tasks=[analysis_task]
)
result = await agents.astart()
print("\nAgent Analysis Result:")
print(result)
# Example 6: Content extraction with language specification
async def language_example():
"""Extract content with specific language targeting"""
tools_instance = get_tools()
# Extract content targeting specific language
url = "https://www.python.org/about/"
content = await asyncio.to_thread(
tools_instance.extract_content,
url,
target_language="en", # Target English content
include_links=True, # Include links in extraction
include_comments=False # Exclude comments
)
if 'error' not in content:
print(f"Language: {content.get('language', 'N/A')}")
print(f"Number of links: {len(content.get('links', []))}")
# Example 7: Output format options
async def format_example():
"""Demonstrate different output formats"""
tools_instance = get_tools()
url = "https://www.python.org/about/"
# JSON format (default)
json_content = await asyncio.to_thread(tools_instance.extract_content, url, output_format='json')
print("JSON format - type:", type(json_content))
# Text format
text_content = await asyncio.to_thread(tools_instance.extract_content, url, output_format='text')
print("\nText format - first 200 chars:")
print(text_content[:200] + "...")
# XML format
xml_content = await asyncio.to_thread(tools_instance.extract_content, url, output_format='xml')
print("\nXML format - first 200 chars:")
print(xml_content[:200] + "...")
# Example 8: Show available methods
async def available_methods_example():
"""Show what methods are available in the custom tool"""
tools_instance = get_tools()
methods = tools_instance.get_available_methods()
print("Available methods in custom Trafilatura tools:")
for method in methods:
print(f" - {method}")
# Example 9: Security testing
async def security_example():
"""Test URL validation security features"""
tools_instance = get_tools()
print("Testing URL security validation:")
unsafe_urls = [
"http://localhost/test",
"http://127.0.0.1/test",
"http://169.254.169.254/metadata"
]
for unsafe_url in unsafe_urls:
result = await asyncio.to_thread(tools_instance.extract_content, unsafe_url)
if isinstance(result, dict) and 'error' in result:
print(f"✓ Correctly rejected: {unsafe_url}")
else:
print(f"✗ Failed to reject: {unsafe_url}")
async def main():
"""Run all examples"""
print("=== Custom Trafilatura Tools Examples ===\n")
try:
# First check if we can create the tools
tools_instance = get_tools()
print("✓ Successfully created custom Trafilatura tools\n")
print("1. Available Methods")
print("-" * 40)
await available_methods_example()
print("\n2. Basic Content Extraction")
print("-" * 40)
await basic_extraction_example()
print("\n3. Text-Only Extraction")
print("-" * 40)
await text_only_example()
print("\n4. Metadata Extraction")
print("-" * 40)
await metadata_example()
print("\n5. Tool Comparison")
print("-" * 40)
await comparison_example()
print("\n6. Language-Specific Extraction")
print("-" * 40)
await language_example()
print("\n7. Output Format Options")
print("-" * 40)
await format_example()
print("\n8. Security Testing")
print("-" * 40)
await security_example()
print("\n9. Agent-Based Analysis")
print("-" * 40)
await agent_example()
except ImportError as e:
print(f"✗ Error: {e}")
print("\nPlease install required dependencies:")
print("pip install trafilatura newspaper3k requests beautifulsoup4")
except Exception as e:
print(f"✗ Unexpected error: {e}")
if __name__ == "__main__":
# Run the examples
asyncio.run(main())
+46 -4
View File
@@ -139,10 +139,32 @@ task = Task(
#### Task-Level Guardrails
```python
from typing import Tuple, Any
from praisonaiagents import GuardrailResult
# Function-based guardrail
def validate_output(task_output: TaskOutput) -> Tuple[bool, Any]:
"""Custom validation function."""
# Function-based guardrail (Option 1: Using GuardrailResult)
def validate_output(task_output: TaskOutput) -> GuardrailResult:
"""Custom validation function returning GuardrailResult."""
if "error" in task_output.raw.lower():
return GuardrailResult(
success=False,
result=None,
error="Output contains errors"
)
if len(task_output.raw) < 10:
return GuardrailResult(
success=False,
result=None,
error="Output is too short"
)
return GuardrailResult(
success=True,
result=task_output,
error=""
)
# Function-based guardrail (Option 2: Using Tuple[bool, Any])
def validate_output_tuple(task_output: TaskOutput) -> Tuple[bool, Any]:
"""Custom validation function returning tuple."""
if "error" in task_output.raw.lower():
return False, "Output contains errors"
if len(task_output.raw) < 10:
@@ -170,7 +192,27 @@ task = Task(
#### Agent-Level Guardrails
```python
# Agent guardrails apply to ALL outputs from that agent
def validate_professional_tone(task_output: TaskOutput) -> Tuple[bool, Any]:
# Option 1: Using GuardrailResult
def validate_professional_tone(task_output: TaskOutput) -> GuardrailResult:
"""Ensure professional tone in all agent responses."""
content = task_output.raw.lower()
casual_words = ['yo', 'dude', 'awesome', 'cool']
for word in casual_words:
if word in content:
return GuardrailResult(
success=False,
result=None,
error=f"Unprofessional language detected: {word}"
)
return GuardrailResult(
success=True,
result=task_output,
error=""
)
# Option 2: Using Tuple[bool, Any]
def validate_professional_tone_tuple(task_output: TaskOutput) -> Tuple[bool, Any]:
"""Ensure professional tone in all agent responses."""
content = task_output.raw.lower()
casual_words = ['yo', 'dude', 'awesome', 'cool']
+62
View File
@@ -0,0 +1,62 @@
from praisonaiagents import AutoAgents
from langchain_community.utilities.tavily_search import TavilySearchAPIWrapper
def tavily(query: str):
api_wrapper = TavilySearchAPIWrapper()
results = api_wrapper.results(query=query, max_results=5)
return results
# Create AutoAgents instance
agents = AutoAgents(
instructions="Search for information about AI Agents",
tools=[tavily],
process="sequential",
verbose=True,
max_agents=3 # Maximum number of agents to create
)
# Start the agents
result = agents.start()
print(result)
##or
from praisonaiagents import AutoAgents
from praisonaiagents.tools import (
evaluate, solve_equation, convert_units,
calculate_statistics, calculate_financial
)
def get_stock_price(company_name: str) -> str:
"""
Get the stock price of a company
Args:
company_name (str): The name of the company
Returns:
str: The stock price of the company
"""
if company_name.lower() == "apple" or company_name.lower() == "aapl":
return f"The stock price of {company_name} is 100"
elif company_name.lower() == "google" or company_name.lower() == "googl":
return f"The stock price of {company_name} is 200"
else:
return f"The stock price of {company_name} is 50"
# Create AutoAgents instance
agents = AutoAgents(
instructions="Get the stock price of google and compare it to the stock price of apple",
tools=[evaluate, get_stock_price],
process="sequential",
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
self_reflect=False,
verbose=False,
max_agents=3 # Maximum number of agents to create
)
# Start the agents
result = agents.start()
print(result)
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""
Script to fix the deprecated .dict() usage in Jupyter notebook
"""
import json
import sys
def fix_notebook():
notebook_path = "examples/cookbooks/Programming_Code_Analysis_Agents/ZeroScript_AI_TestExecutor.ipynb"
try:
# Read the notebook
with open(notebook_path, 'r') as f:
notebook = json.load(f)
# Find and fix the cell with .dict() usage
for cell in notebook.get('cells', []):
if cell.get('cell_type') == 'code':
source = cell.get('source', [])
# Convert source to string if it's a list
source_str = ''.join(source) if isinstance(source, list) else source
# Check if this cell contains the problematic .dict() usage or hasattr check
if 'result_obj.dict()' in source_str or 'hasattr(result_obj, "dict")' in source_str:
print(f"Found cell with .dict() usage, fixing...")
# Replace .dict() with .model_dump() and fix hasattr check for backward compatibility
fixed_source = source_str.replace('result_obj.dict()', 'result_obj.model_dump()').replace('hasattr(result_obj, "dict")', 'hasattr(result_obj, "model_dump")')
# Convert back to list format if needed
if isinstance(source, list):
cell['source'] = fixed_source.splitlines(True)
else:
cell['source'] = fixed_source
print("Fixed .dict() usage")
break
# Write the fixed notebook back
with open(notebook_path, 'w') as f:
json.dump(notebook, f, indent=2)
print(f"Successfully updated {notebook_path}")
return True
except Exception as e:
print(f"Error fixing notebook: {e}")
return False
if __name__ == "__main__":
success = fix_notebook()
sys.exit(0 if success else 1)
@@ -0,0 +1,12 @@
from praisonaiagents import Agent
def get_weather(city: str) -> str:
return f"The weather in {city} is sunny"
agent = Agent(
instructions="You are a helpful assistant",
llm="gemini/gemini-1.5-flash-latest",
tools=[get_weather]
)
agent.start("What is the weather in Tokyo?")
+25
View File
@@ -0,0 +1,25 @@
from praisonaiagents import Agent
def get_stock_price(company_name: str) -> str:
"""
Get the stock price of a company
Args:
company_name (str): The name of the company
Returns:
str: The stock price of the company
"""
return f"The stock price of {company_name} is 100"
def multiply(a: int, b: int) -> int:
"""
Multiply two numbers
"""
return a * b
agent = Agent(
instructions="You are a helpful assistant. You can use the tools provided to you to help the user.",
llm="gemini/gemini-2.5-pro",
tools=[get_stock_price, multiply]
)
result = agent.start("what is the stock price of Google? multiply the Google stock price with 2")
@@ -0,0 +1,9 @@
from praisonaiagents import Agent
agent = Agent(
instructions="Research assistant with web search",
llm="gemini/gemini-2.5-flash",
tools=[{"googleSearch": {}}, ]
)
response = agent.start("Who is Mervin Praison?")
+30
View File
@@ -0,0 +1,30 @@
from praisonaiagents import Agent
def get_stock_price(company_name: str) -> str:
"""
Get the stock price of a company
Args:
company_name (str): The name of the company
Returns:
str: The stock price of the company
"""
return f"The stock price of {company_name} is 100"
def multiply(a: int, b: int) -> int:
"""
Multiply two numbers
"""
return a * b
agent = Agent(
instructions="You are a helpful assistant. You can use the tools provided to you to help the user.",
llm="gemini/gemini-2.5-pro",
tools=[get_stock_price, multiply]
)
result = agent.start("what is the stock price of Google? multiply the Google stock price with 2")
print(result)
+25
View File
@@ -0,0 +1,25 @@
from pydantic import BaseModel
from praisonaiagents import Agent, Task, Agents
class Recipe(BaseModel):
recipe_name: str
ingredients: list[str]
agent = Agent(
name="Chef",
role="Recipe Creator",
llm="gemini/gemini-2.5-flash"
)
task = Task(
description="Create a cookie recipe",
agent=agent,
output_pydantic=Recipe # Will use Gemini's native structured output!
)
agents = Agents(
agents=[agent],
tasks=[task]
)
agents.start()
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Test script to verify the Gemini JSON parsing fix."""
from praisonaiagents import Agent
# Test with minimal configuration to isolate the issue
llm_config = {
"model": "gemini/gemini-1.5-flash-latest",
"temperature": 0.7,
"max_tokens": 500,
}
# Create agent with self-reflection enabled
agent = Agent(
instructions="You are a helpful assistant. Be concise and clear.",
llm=llm_config,
verbose=True,
self_reflect=True,
max_reflect=2,
min_reflect=1
)
# Test with a simple prompt
print("Testing Gemini with self-reflection...")
try:
response = agent.start("What is 2+2? Explain briefly.")
print(f"\nFinal response: {response}")
print("\nTest completed successfully!")
except Exception as e:
print(f"\nError occurred: {e}")
import traceback
traceback.print_exc()
+179
View File
@@ -0,0 +1,179 @@
from praisonaiagents import Agent
from praisonaiagents.agent.handoff import handoff, handoff_filters
from pydantic import BaseModel
from typing import Dict, Any
import logging
# Mock data for testing
MOCK_ORDERS = {
"12345": {
"id": "12345",
"status": "shipped",
"items": ["Widget A", "Widget B"],
"total": 99.99,
"tracking_number": "TRK123456789",
"shipping_address": "123 Main St, City, ST 12345"
},
"67890": {
"id": "67890",
"status": "processing",
"items": ["Gadget X"],
"total": 149.99,
"tracking_number": None,
"shipping_address": "456 Oak Ave, Town, ST 67890"
}
}
MOCK_SHIPMENTS = {
"TRK123456789": {
"tracking_number": "TRK123456789",
"status": "in_transit",
"location": "Distribution Center - Chicago",
"estimated_delivery": "2024-01-15",
"updates": [
{"date": "2024-01-10", "status": "picked_up", "location": "Warehouse"},
{"date": "2024-01-12", "status": "in_transit", "location": "Chicago"}
]
}
}
MOCK_TICKETS = []
# Mock tool functions
def check_order_status(order_id: str) -> Dict[str, Any]:
"""Check the status of an order"""
if order_id in MOCK_ORDERS:
return {"success": True, "order": MOCK_ORDERS[order_id]}
return {"success": False, "error": f"Order {order_id} not found"}
def track_shipment(tracking_number: str) -> Dict[str, Any]:
"""Track a shipment by tracking number"""
if tracking_number in MOCK_SHIPMENTS:
return {"success": True, "shipment": MOCK_SHIPMENTS[tracking_number]}
return {"success": False, "error": f"Tracking number {tracking_number} not found"}
def process_refund(order_id: str, reason: str = "customer_request") -> Dict[str, Any]:
"""Process a refund for an order"""
if order_id in MOCK_ORDERS:
order = MOCK_ORDERS[order_id]
return {
"success": True,
"refund_id": f"REF{order_id}",
"amount": order["total"],
"status": "processing",
"estimated_days": 3-5
}
return {"success": False, "error": f"Order {order_id} not found"}
def check_refund_policy(item_type: str = "general") -> Dict[str, Any]:
"""Check refund policy for different item types"""
policies = {
"general": {"days": 30, "condition": "unopened", "shipping": "customer_pays"},
"electronics": {"days": 15, "condition": "original_packaging", "shipping": "free"},
"clothing": {"days": 60, "condition": "tags_attached", "shipping": "customer_pays"}
}
return {"success": True, "policy": policies.get(item_type, policies["general"])}
def diagnose_issue(description: str) -> Dict[str, Any]:
"""Diagnose a technical issue"""
common_solutions = {
"login": "Clear cookies and cache, try password reset",
"payment": "Check card details, try different payment method",
"loading": "Check internet connection, try different browser",
"mobile": "Update app, restart device, check storage space"
}
# Simple keyword matching for demo
for issue_type, solution in common_solutions.items():
if issue_type in description.lower():
return {"success": True, "diagnosis": solution, "severity": "low"}
return {"success": True, "diagnosis": "Please provide more details", "severity": "medium"}
def create_ticket(issue_description: str, priority: str = "medium") -> Dict[str, Any]:
"""Create a support ticket"""
ticket_id = f"TICK{len(MOCK_TICKETS) + 1001}"
ticket = {
"id": ticket_id,
"description": issue_description,
"priority": priority,
"status": "open",
"created_at": "2024-01-13T10:00:00Z"
}
MOCK_TICKETS.append(ticket)
return {"success": True, "ticket": ticket}
def log_escalation(source_agent: str, escalation_data: Dict[str, Any]) -> None:
"""Log escalation for audit purposes"""
logging.info(f"Escalation from {source_agent}: {escalation_data}")
# Escalation with structured input
class EscalationRequest(BaseModel):
issue_type: str
severity: str
description: str
# Specialist agents
order_agent = Agent(
name="Order Management",
instructions="You help with order status and tracking.",
tools=[check_order_status, track_shipment]
)
refund_agent = Agent(
name="Refund Specialist",
instructions="You process refunds and handle return requests.",
tools=[process_refund, check_refund_policy]
)
technical_agent = Agent(
name="Technical Support",
instructions="You solve technical issues and provide guidance.",
tools=[diagnose_issue, create_ticket]
)
escalation_agent = Agent(
name="Senior Manager",
instructions="You handle escalated issues requiring management attention."
)
# Main triage agent
triage_agent = Agent(
name="Customer Service",
instructions="""You are the first point of contact. Route customers to the right specialist:
- Order issues → Order Management
- Refunds → Refund Specialist
- Technical problems → Technical Support
- Complex issues → Escalate to management
""",
handoffs=[
order_agent,
refund_agent,
technical_agent,
handoff(
escalation_agent,
tool_name_override="escalate_to_management",
input_type=EscalationRequest,
on_handoff=lambda src, data: log_escalation(src.name, data)
)
]
)
# Start the service
if __name__ == "__main__":
print("Customer Service Handoff System Demo")
print("=" * 40)
# Test different scenarios
test_queries = [
"I need a refund for order #12345",
"What's the status of order #67890?",
"I'm having trouble logging into my account",
"This is urgent - I need to speak to a manager about a serious billing issue"
]
for query in test_queries:
print(f"\nCustomer: {query}")
response = triage_agent.chat(query)
print(f"Response: {response}")
print("-" * 40)
+6
View File
@@ -0,0 +1,6 @@
from praisonaiagents import Agent, Agents, Tools
research_agent = Agent(name="Research", instructions="You are a research agent to search internet about AI 2024", tools=[Tools.internet_search])
summarise_agent = Agent(name="Summarise", instructions="You are a summarize agent to summarise in points")
agents = Agents(agents=[research_agent, summarise_agent])
agents.launch(path="/agents", port=3030)
+30
View File
@@ -0,0 +1,30 @@
from praisonaiagents import Agent
def get_stock_price(company_name: str) -> str:
"""
Get the stock price of a company
Args:
company_name (str): The name of the company
Returns:
str: The stock price of the company
"""
return f"The stock price of {company_name} is 100"
def multiply(a: int, b: int) -> int:
"""
Multiply two numbers
"""
return a * b
agent = Agent(
instructions="You are a helpful assistant. You can use the tools provided to you to help the user.",
llm="ollama/qwen3",
tools=[get_stock_price, multiply]
)
result = agent.start("what is the stock price of Google? multiply the Google stock price with 2")
print(result)
+30
View File
@@ -0,0 +1,30 @@
from praisonaiagents import Agent
def get_stock_price(company_name: str) -> str:
"""
Get the stock price of a company
Args:
company_name (str): The name of the company
Returns:
str: The stock price of the company
"""
return f"The stock price of {company_name} is 100"
def multiply(a: int, b: int) -> int:
"""
Multiply two numbers
"""
return a * b
agent = Agent(
instructions="You are a helpful assistant. You can use the tools provided to you to help the user.",
llm="gpt-4o",
tools=[get_stock_price, multiply]
)
result = agent.start("what is the stock price of Google? multiply the Google stock price with 2")
print(result)
@@ -2,6 +2,30 @@
Praison AI Agents - A package for hierarchical AI agent task execution
"""
# Configure logging before any other imports
import os
import logging
from rich.logging import RichHandler
# Get log level from environment variable
LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper()
# Configure root logger
logging.basicConfig(
level=getattr(logging, LOGLEVEL, logging.INFO),
format="%(asctime)s %(filename)s:%(lineno)d %(levelname)s %(message)s",
datefmt="[%X]",
handlers=[RichHandler(rich_tracebacks=True)]
)
# Suppress specific noisy loggers
logging.getLogger("litellm").setLevel(logging.WARNING)
logging.getLogger("litellm.utils").setLevel(logging.WARNING)
logging.getLogger("markdown_it").setLevel(logging.WARNING)
logging.getLogger("rich.markdown").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
from .agent.agent import Agent
from .agent.image_agent import ImageAgent
from .agents.agents import PraisonAIAgents
@@ -2,5 +2,6 @@
from .agent import Agent
from .image_agent import ImageAgent
from .handoff import Handoff, handoff, handoff_filters, RECOMMENDED_PROMPT_PREFIX, prompt_with_handoff_instructions
from .router_agent import RouterAgent
__all__ = ['Agent', 'ImageAgent', 'Handoff', 'handoff', 'handoff_filters', 'RECOMMENDED_PROMPT_PREFIX', 'prompt_with_handoff_instructions']
__all__ = ['Agent', 'ImageAgent', 'Handoff', 'handoff', 'handoff_filters', 'RECOMMENDED_PROMPT_PREFIX', 'prompt_with_handoff_instructions', 'RouterAgent']
@@ -27,7 +27,8 @@ from ..main import (
display_self_reflection,
ReflectionOutput,
adisplay_instruction,
approval_callback
approval_callback,
execute_sync_callback
)
import inspect
import uuid
@@ -424,7 +425,13 @@ class Agent:
# Otherwise, fall back to OpenAI environment/name
else:
self.llm = llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o')
self.tools = tools if tools else [] # Store original tools
# Handle tools parameter - ensure it's always a list
if callable(tools):
# If a single function/callable is passed, wrap it in a list
self.tools = [tools]
else:
# Handle all falsy values (None, False, 0, "", etc.) by defaulting to empty list
self.tools = tools or []
self.function_calling_llm = function_calling_llm
self.max_iter = max_iter
self.max_rpm = max_rpm
@@ -444,6 +451,8 @@ class Agent:
self.embedder_config = embedder_config
self.knowledge = knowledge
self.use_system_prompt = use_system_prompt
# NOTE: chat_history is not thread-safe. If concurrent access is needed,
# consider using threading.Lock or other synchronization mechanisms
self.chat_history = []
self.markdown = markdown
self.stream = stream
@@ -711,8 +720,55 @@ Your Goal: {self.goal}
)
return current_response
def _build_system_prompt(self, tools=None):
"""Build the system prompt with tool information.
Args:
tools: Optional list of tools to use (defaults to self.tools)
Returns:
str: The system prompt or None if use_system_prompt is False
"""
if not self.use_system_prompt:
return None
system_prompt = f"""{self.backstory}\n
Your Role: {self.role}\n
Your Goal: {self.goal}"""
# Add tool usage instructions if tools are available
# Use provided tools or fall back to self.tools
tools_to_use = tools if tools is not None else self.tools
if tools_to_use:
tool_names = []
for tool in tools_to_use:
try:
if callable(tool) and hasattr(tool, '__name__'):
tool_names.append(tool.__name__)
elif isinstance(tool, dict) and isinstance(tool.get('function'), dict) and 'name' in tool['function']:
tool_names.append(tool['function']['name'])
elif isinstance(tool, str):
tool_names.append(tool)
elif hasattr(tool, "to_openai_tool"):
# Handle MCP tools
openai_tools = tool.to_openai_tool()
if isinstance(openai_tools, list):
for t in openai_tools:
if isinstance(t, dict) and 'function' in t and 'name' in t['function']:
tool_names.append(t['function']['name'])
elif isinstance(openai_tools, dict) and 'function' in openai_tools:
tool_names.append(openai_tools['function']['name'])
except (AttributeError, KeyError, TypeError) as e:
logging.warning(f"Could not extract tool name from {tool}: {e}")
continue
if tool_names:
system_prompt += f"\n\nYou have access to the following tools: {', '.join(tool_names)}. Use these tools when appropriate to help complete your tasks. Always use tools when they can help provide accurate information or perform actions."
return system_prompt
def _build_messages(self, prompt, temperature=0.2, output_json=None, output_pydantic=None):
def _build_messages(self, prompt, temperature=0.2, output_json=None, output_pydantic=None, tools=None):
"""Build messages list for chat completion.
Args:
@@ -720,17 +776,13 @@ Your Goal: {self.goal}
temperature: Temperature for the chat
output_json: Optional Pydantic model for JSON output
output_pydantic: Optional Pydantic model for JSON output (alias)
tools: Optional list of tools to use (defaults to self.tools)
Returns:
tuple: (messages list, original prompt)
"""
# Build system prompt if enabled
system_prompt = None
if self.use_system_prompt:
system_prompt = f"""{self.backstory}\n
Your Role: {self.role}\n
Your Goal: {self.goal}
"""
# Build system prompt using the helper method
system_prompt = self._build_system_prompt(tools)
# Use openai_client's build_messages method if available
if self._openai_client is not None:
@@ -1048,6 +1100,10 @@ Your Goal: {self.goal}
execute_tool_fn=self.execute_tool,
agent_name=self.name,
agent_role=self.role,
agent_tools=[t.__name__ for t in self.tools] if self.tools else None,
task_name=task_name,
task_description=task_description,
task_id=task_id,
reasoning_steps=reasoning_steps
)
else:
@@ -1064,6 +1120,10 @@ Your Goal: {self.goal}
execute_tool_fn=self.execute_tool,
agent_name=self.name,
agent_role=self.role,
agent_tools=[t.__name__ for t in self.tools] if self.tools else None,
task_name=task_name,
task_description=task_description,
task_id=task_id,
reasoning_steps=reasoning_steps
)
else:
@@ -1097,8 +1157,39 @@ Your Goal: {self.goal}
except Exception as e:
display_error(f"Error in chat completion: {e}")
return None
def _execute_callback_and_display(self, prompt: str, response: str, generation_time: float):
"""Helper method to execute callbacks and display interaction.
This centralizes the logic for callback execution and display to avoid duplication.
"""
# Always execute callbacks regardless of verbose setting (only when not using custom LLM)
if not self._using_custom_llm:
execute_sync_callback(
'interaction',
message=prompt,
response=response,
markdown=self.markdown,
generation_time=generation_time,
agent_name=self.name,
agent_role=self.role,
agent_tools=[t.__name__ for t in self.tools] if self.tools else None,
task_name=None, # Not available in this context
task_description=None, # Not available in this context
task_id=None # Not available in this context
)
# Only display interaction if not using custom LLM (to avoid double output) and verbose is True
if self.verbose and not self._using_custom_llm:
display_interaction(prompt, response, markdown=self.markdown,
generation_time=generation_time, console=self.console,
agent_name=self.name,
agent_role=self.role,
agent_tools=[t.__name__ for t in self.tools] if self.tools else None,
task_name=None, # Not available in this context
task_description=None, # Not available in this context
task_id=None) # Not available in this context
def chat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None, reasoning_steps=False, stream=True):
def chat(self, prompt, temperature=0.2, tools=None, output_json=None, output_pydantic=None, reasoning_steps=False, stream=True, task_name=None, task_description=None, task_id=None):
# Log all parameter values when in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
param_info = {
@@ -1154,10 +1245,27 @@ Your Goal: {self.goal}
tool_param = [openai_tool]
logging.debug(f"Converted MCP tool: {tool_param}")
# Pass everything to LLM class
response_text = self.llm_instance.get_response(
# Store chat history length for potential rollback
chat_history_length = len(self.chat_history)
# Normalize prompt content for consistent chat history storage
normalized_content = prompt
if isinstance(prompt, list):
# Extract text from multimodal prompts
normalized_content = next((item["text"] for item in prompt if item.get("type") == "text"), "")
# Prevent duplicate messages
if not (self.chat_history and
self.chat_history[-1].get("role") == "user" and
self.chat_history[-1].get("content") == normalized_content):
# Add user message to chat history BEFORE LLM call so handoffs can access it
self.chat_history.append({"role": "user", "content": normalized_content})
try:
# Pass everything to LLM class
response_text = self.llm_instance.get_response(
prompt=prompt,
system_prompt=f"{self.backstory}\n\nYour Role: {self.role}\n\nYour Goal: {self.goal}" if self.use_system_prompt else None,
system_prompt=self._build_system_prompt(tools),
chat_history=self.chat_history,
temperature=temperature,
tools=tool_param,
@@ -1172,24 +1280,34 @@ Your Goal: {self.goal}
agent_name=self.name,
agent_role=self.role,
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in (tools if tools is not None else self.tools)],
task_name=task_name,
task_description=task_description,
task_id=task_id,
execute_tool_fn=self.execute_tool, # Pass tool execution function
reasoning_steps=reasoning_steps
)
reasoning_steps=reasoning_steps,
stream=stream # Pass the stream parameter from chat method
)
self.chat_history.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
self.chat_history.append({"role": "assistant", "content": response_text})
# Log completion time if in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.chat completed in {total_time:.2f} seconds")
# Log completion time if in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.chat completed in {total_time:.2f} seconds")
# Apply guardrail validation for custom LLM response
try:
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
return validated_response
# Apply guardrail validation for custom LLM response
try:
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed for custom LLM: {e}")
# Rollback chat history on guardrail failure
self.chat_history = self.chat_history[:chat_history_length]
return None
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed for custom LLM: {e}")
# Rollback chat history if LLM call fails
self.chat_history = self.chat_history[:chat_history_length]
display_error(f"Error in LLM chat: {e}")
return None
except Exception as e:
display_error(f"Error in LLM chat: {e}")
@@ -1197,167 +1315,214 @@ Your Goal: {self.goal}
else:
# Use the new _build_messages helper method
messages, original_prompt = self._build_messages(prompt, temperature, output_json, output_pydantic)
# Store chat history length for potential rollback
chat_history_length = len(self.chat_history)
# Normalize original_prompt for consistent chat history storage
normalized_content = original_prompt
if isinstance(original_prompt, list):
# Extract text from multimodal prompts
normalized_content = next((item["text"] for item in original_prompt if item.get("type") == "text"), "")
# Prevent duplicate messages
if not (self.chat_history and
self.chat_history[-1].get("role") == "user" and
self.chat_history[-1].get("content") == normalized_content):
# Add user message to chat history BEFORE LLM call so handoffs can access it
self.chat_history.append({"role": "user", "content": normalized_content})
final_response_text = None
reflection_count = 0
start_time = time.time()
while True:
try:
if self.verbose:
# Handle both string and list prompts for instruction display
display_text = prompt
if isinstance(prompt, list):
# Extract text content from multimodal prompt
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
if display_text and str(display_text).strip():
# Pass agent information to display_instruction
agent_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
display_instruction(
f"Agent {self.name} is processing prompt: {display_text}",
console=self.console,
agent_name=self.name,
agent_role=self.role,
agent_tools=agent_tools
)
response = self._chat_completion(messages, temperature=temperature, tools=tools if tools else None, reasoning_steps=reasoning_steps, stream=self.stream)
if not response:
return None
response_text = response.choices[0].message.content.strip()
# Handle output_json or output_pydantic if specified
if output_json or output_pydantic:
# Add to chat history and return raw response
self.chat_history.append({"role": "user", "content": original_prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
# Wrap entire while loop in try-except for rollback on any failure
try:
while True:
try:
if self.verbose:
display_interaction(original_prompt, response_text, markdown=self.markdown,
generation_time=time.time() - start_time, console=self.console)
return response_text
# Handle both string and list prompts for instruction display
display_text = prompt
if isinstance(prompt, list):
# Extract text content from multimodal prompt
display_text = next((item["text"] for item in prompt if item["type"] == "text"), "")
if display_text and str(display_text).strip():
# Pass agent information to display_instruction
agent_tools = [t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools]
display_instruction(
f"Agent {self.name} is processing prompt: {display_text}",
console=self.console,
agent_name=self.name,
agent_role=self.role,
agent_tools=agent_tools
)
if not self.self_reflect:
self.chat_history.append({"role": "user", "content": original_prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
if self.verbose:
logging.debug(f"Agent {self.name} final response: {response_text}")
display_interaction(original_prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
# Return only reasoning content if reasoning_steps is True
if reasoning_steps and hasattr(response.choices[0].message, 'reasoning_content'):
# Apply guardrail to reasoning content
try:
validated_reasoning = self._apply_guardrail_with_retry(response.choices[0].message.reasoning_content, original_prompt, temperature, tools)
return validated_reasoning
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed for reasoning content: {e}")
return None
# Apply guardrail to regular response
try:
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed: {e}")
response = self._chat_completion(messages, temperature=temperature, tools=tools if tools else None, reasoning_steps=reasoning_steps, stream=self.stream)
if not response:
# Rollback chat history on response failure
self.chat_history = self.chat_history[:chat_history_length]
return None
reflection_prompt = f"""
response_text = response.choices[0].message.content.strip()
# Handle output_json or output_pydantic if specified
if output_json or output_pydantic:
# Add to chat history and return raw response
# User message already added before LLM call via _build_messages
self.chat_history.append({"role": "assistant", "content": response_text})
# Apply guardrail validation even for JSON output
try:
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed for JSON output: {e}")
# Rollback chat history on guardrail failure
self.chat_history = self.chat_history[:chat_history_length]
return None
if not self.self_reflect:
# User message already added before LLM call via _build_messages
self.chat_history.append({"role": "assistant", "content": response_text})
if self.verbose:
logging.debug(f"Agent {self.name} final response: {response_text}")
# Return only reasoning content if reasoning_steps is True
if reasoning_steps and hasattr(response.choices[0].message, 'reasoning_content'):
# Apply guardrail to reasoning content
try:
validated_reasoning = self._apply_guardrail_with_retry(response.choices[0].message.reasoning_content, original_prompt, temperature, tools)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_reasoning, time.time() - start_time)
return validated_reasoning
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed for reasoning content: {e}")
# Rollback chat history on guardrail failure
self.chat_history = self.chat_history[:chat_history_length]
return None
# Apply guardrail to regular response
try:
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed: {e}")
# Rollback chat history on guardrail failure
self.chat_history = self.chat_history[:chat_history_length]
return None
reflection_prompt = f"""
Reflect on your previous response: '{response_text}'.
{self.reflect_prompt if self.reflect_prompt else "Identify any flaws, improvements, or actions."}
Provide a "satisfactory" status ('yes' or 'no').
Output MUST be JSON with 'reflection' and 'satisfactory'.
"""
logging.debug(f"{self.name} reflection attempt {reflection_count+1}, sending prompt: {reflection_prompt}")
messages.append({"role": "user", "content": reflection_prompt})
"""
logging.debug(f"{self.name} reflection attempt {reflection_count+1}, sending prompt: {reflection_prompt}")
messages.append({"role": "user", "content": reflection_prompt})
try:
# Check if we're using a custom LLM (like Gemini)
if self._using_custom_llm or self._openai_client is None:
# For custom LLMs, we need to handle reflection differently
# Use non-streaming to get complete JSON response
reflection_response = self._chat_completion(messages, temperature=temperature, tools=None, stream=False, reasoning_steps=False)
if not reflection_response or not reflection_response.choices:
raise Exception("No response from reflection request")
reflection_text = reflection_response.choices[0].message.content.strip()
# Clean the JSON output
cleaned_json = self.clean_json_output(reflection_text)
# Parse the JSON manually
reflection_data = json.loads(cleaned_json)
# Create a reflection output object manually
class CustomReflectionOutput:
def __init__(self, data):
self.reflection = data.get('reflection', '')
self.satisfactory = data.get('satisfactory', 'no').lower()
reflection_output = CustomReflectionOutput(reflection_data)
else:
# Use OpenAI's structured output for OpenAI models
reflection_response = self._openai_client.sync_client.beta.chat.completions.parse(
model=self.reflect_llm if self.reflect_llm else self.llm,
messages=messages,
temperature=temperature,
response_format=ReflectionOutput
)
reflection_output = reflection_response.choices[0].message.parsed
try:
# Check if OpenAI client is available
if self._openai_client is None:
# For custom LLMs, self-reflection with structured output is not supported
if self.verbose:
display_self_reflection(f"Agent {self.name}: Self-reflection with structured output is not supported for custom LLM providers. Skipping reflection.", console=self.console)
# Return the original response without reflection
self.chat_history.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
return response_text
reflection_response = self._openai_client.sync_client.beta.chat.completions.parse(
model=self.reflect_llm if self.reflect_llm else self.llm,
messages=messages,
temperature=temperature,
response_format=ReflectionOutput
)
display_self_reflection(f"Agent {self.name} self reflection (using {self.reflect_llm if self.reflect_llm else self.llm}): reflection='{reflection_output.reflection}' satisfactory='{reflection_output.satisfactory}'", console=self.console)
reflection_output = reflection_response.choices[0].message.parsed
messages.append({"role": "assistant", "content": f"Self Reflection: {reflection_output.reflection} Satisfactory?: {reflection_output.satisfactory}"})
if self.verbose:
display_self_reflection(f"Agent {self.name} self reflection (using {self.reflect_llm if self.reflect_llm else self.llm}): reflection='{reflection_output.reflection}' satisfactory='{reflection_output.satisfactory}'", console=self.console)
# Only consider satisfactory after minimum reflections
if reflection_output.satisfactory == "yes" and reflection_count >= self.min_reflect - 1:
if self.verbose:
display_self_reflection("Agent marked the response as satisfactory after meeting minimum reflections", console=self.console)
# User message already added before LLM call via _build_messages
self.chat_history.append({"role": "assistant", "content": response_text})
# Apply guardrail validation after satisfactory reflection
try:
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed after reflection: {e}")
# Rollback chat history on guardrail failure
self.chat_history = self.chat_history[:chat_history_length]
return None
messages.append({"role": "assistant", "content": f"Self Reflection: {reflection_output.reflection} Satisfactory?: {reflection_output.satisfactory}"})
# Check if we've hit max reflections
if reflection_count >= self.max_reflect - 1:
if self.verbose:
display_self_reflection("Maximum reflection count reached, returning current response", console=self.console)
# User message already added before LLM call via _build_messages
self.chat_history.append({"role": "assistant", "content": response_text})
# Apply guardrail validation after max reflections
try:
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
# Execute callback after validation
self._execute_callback_and_display(original_prompt, validated_response, time.time() - start_time)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed after max reflections: {e}")
# Rollback chat history on guardrail failure
self.chat_history = self.chat_history[:chat_history_length]
return None
# If not satisfactory and not at max reflections, continue with regeneration
logging.debug(f"{self.name} reflection count {reflection_count + 1}, continuing reflection process")
messages.append({"role": "user", "content": "Now regenerate your response using the reflection you made"})
# For custom LLMs during reflection, always use non-streaming to ensure complete responses
use_stream = self.stream if not self._using_custom_llm else False
response = self._chat_completion(messages, temperature=temperature, tools=None, stream=use_stream)
response_text = response.choices[0].message.content.strip()
reflection_count += 1
continue # Continue the loop for more reflections
# Only consider satisfactory after minimum reflections
if reflection_output.satisfactory == "yes" and reflection_count >= self.min_reflect - 1:
if self.verbose:
display_self_reflection("Agent marked the response as satisfactory after meeting minimum reflections", console=self.console)
self.chat_history.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
# Apply guardrail validation after satisfactory reflection
try:
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed after reflection: {e}")
return None
# Check if we've hit max reflections
if reflection_count >= self.max_reflect - 1:
if self.verbose:
display_self_reflection("Maximum reflection count reached, returning current response", console=self.console)
self.chat_history.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
display_interaction(prompt, response_text, markdown=self.markdown, generation_time=time.time() - start_time, console=self.console)
# Apply guardrail validation after max reflections
try:
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed after max reflections: {e}")
return None
logging.debug(f"{self.name} reflection count {reflection_count + 1}, continuing reflection process")
messages.append({"role": "user", "content": "Now regenerate your response using the reflection you made"})
response = self._chat_completion(messages, temperature=temperature, tools=None, stream=self.stream)
response_text = response.choices[0].message.content.strip()
reflection_count += 1
continue # Continue the loop for more reflections
except Exception as e:
display_error(f"Error in parsing self-reflection json {e}. Retrying", console=self.console)
logging.error("Reflection parsing failed.", exc_info=True)
messages.append({"role": "assistant", "content": f"Self Reflection failed."})
reflection_count += 1
continue # Continue even after error to try again
except Exception as e:
display_error(f"Error in chat: {e}", console=self.console)
return None
# Log completion time if in debug mode
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.chat completed in {total_time:.2f} seconds")
# Apply guardrail validation before returning
try:
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed: {e}")
if self.verbose:
display_error(f"Guardrail validation failed: {e}", console=self.console)
return None
except Exception as e:
display_error(f"Error in parsing self-reflection json {e}. Retrying", console=self.console)
logging.error("Reflection parsing failed.", exc_info=True)
messages.append({"role": "assistant", "content": "Self Reflection failed."})
reflection_count += 1
continue # Continue even after error to try again
except Exception:
# Catch any exception from the inner try block and re-raise to outer handler
raise
except Exception as e:
# Catch any exceptions that escape the while loop
display_error(f"Unexpected error in chat: {e}", console=self.console)
# Rollback chat history
self.chat_history = self.chat_history[:chat_history_length]
return None
def clean_json_output(self, output: str) -> str:
"""Clean and extract JSON from response text."""
@@ -1406,10 +1571,26 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
prompt = f"{prompt}\n\nKnowledge: {knowledge_content}"
if self._using_custom_llm:
# Store chat history length for potential rollback
chat_history_length = len(self.chat_history)
# Normalize prompt content for consistent chat history storage
normalized_content = prompt
if isinstance(prompt, list):
# Extract text from multimodal prompts
normalized_content = next((item["text"] for item in prompt if item.get("type") == "text"), "")
# Prevent duplicate messages
if not (self.chat_history and
self.chat_history[-1].get("role") == "user" and
self.chat_history[-1].get("content") == normalized_content):
# Add user message to chat history BEFORE LLM call so handoffs can access it
self.chat_history.append({"role": "user", "content": normalized_content})
try:
response_text = await self.llm_instance.get_response_async(
prompt=prompt,
system_prompt=f"{self.backstory}\n\nYour Role: {self.role}\n\nYour Goal: {self.goal}" if self.use_system_prompt else None,
system_prompt=self._build_system_prompt(tools),
chat_history=self.chat_history,
temperature=temperature,
tools=tools,
@@ -1423,19 +1604,32 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
console=self.console,
agent_name=self.name,
agent_role=self.role,
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in self.tools],
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in (tools if tools is not None else self.tools)],
task_name=task_name,
task_description=task_description,
task_id=task_id,
execute_tool_fn=self.execute_tool_async,
reasoning_steps=reasoning_steps
)
self.chat_history.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "assistant", "content": response_text})
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.achat completed in {total_time:.2f} seconds")
return response_text
# Apply guardrail validation for custom LLM response
try:
validated_response = self._apply_guardrail_with_retry(response_text, prompt, temperature, tools)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed for custom LLM: {e}")
# Rollback chat history on guardrail failure
self.chat_history = self.chat_history[:chat_history_length]
return None
except Exception as e:
# Rollback chat history if LLM call fails
self.chat_history = self.chat_history[:chat_history_length]
display_error(f"Error in LLM chat: {e}")
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
@@ -1445,6 +1639,22 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
# For OpenAI client
# Use the new _build_messages helper method
messages, original_prompt = self._build_messages(prompt, temperature, output_json, output_pydantic)
# Store chat history length for potential rollback
chat_history_length = len(self.chat_history)
# Normalize original_prompt for consistent chat history storage
normalized_content = original_prompt
if isinstance(original_prompt, list):
# Extract text from multimodal prompts
normalized_content = next((item["text"] for item in original_prompt if item.get("type") == "text"), "")
# Prevent duplicate messages
if not (self.chat_history and
self.chat_history[-1].get("role") == "user" and
self.chat_history[-1].get("content") == normalized_content):
# Add user message to chat history BEFORE LLM call so handoffs can access it
self.chat_history.append({"role": "user", "content": normalized_content})
reflection_count = 0
start_time = time.time()
@@ -1591,7 +1801,16 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
total_time = time.time() - start_time
logging.debug(f"Agent.achat completed in {total_time:.2f} seconds")
return response_text
# Apply guardrail validation for OpenAI client response
try:
validated_response = self._apply_guardrail_with_retry(response_text, original_prompt, temperature, tools)
return validated_response
except Exception as e:
logging.error(f"Agent {self.name}: Guardrail validation failed for OpenAI client: {e}")
# Rollback chat history on guardrail failure
self.chat_history = self.chat_history[:chat_history_length]
return None
except Exception as e:
display_error(f"Error in chat completion: {e}")
if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
@@ -1707,6 +1926,26 @@ Output MUST be JSON with 'reflection' and 'satisfactory'.
"""Start the agent with a prompt. This is a convenience method that wraps chat()."""
return self.chat(prompt, **kwargs)
def execute(self, task, context=None):
"""Execute a task synchronously - backward compatibility method"""
if hasattr(task, 'description'):
prompt = task.description
elif isinstance(task, str):
prompt = task
else:
prompt = str(task)
return self.chat(prompt)
async def aexecute(self, task, context=None):
"""Execute a task asynchronously - backward compatibility method"""
if hasattr(task, 'description'):
prompt = task.description
elif isinstance(task, str):
prompt = task
else:
prompt = str(task)
return await self.achat(prompt)
async def execute_tool_async(self, function_name: str, arguments: Dict[str, Any]) -> Any:
"""Async version of execute_tool"""
try:
@@ -144,8 +144,17 @@ class ImageAgent(Agent):
config = self.image_config.dict(exclude_none=True)
config.update(kwargs)
# Use llm parameter as the model
config['model'] = self.llm
# Get the model name robustly from the parent Agent's property
model_info = self.llm_model
model_name = model_info.model if hasattr(model_info, 'model') else str(model_info)
# Use the model name in config
config['model'] = model_name
# Check if we're using a Gemini model and remove unsupported parameters
if 'gemini' in model_name.lower():
# Gemini models don't support response_format parameter
config.pop('response_format', None)
with Progress(
SpinnerColumn(),
@@ -154,7 +163,7 @@ class ImageAgent(Agent):
) as progress:
try:
# Add a task for image generation
task = progress.add_task(f"[cyan]Generating image with {self.llm}...", total=None)
task = progress.add_task(f"[cyan]Generating image with {model_name}...", total=None)
# Use litellm's image generation
response = self.litellm(
@@ -0,0 +1,334 @@
"""
Router Agent that can use different LLM models based on task requirements.
This module extends the base Agent class to support multiple models and intelligent
model selection based on task characteristics.
"""
import os
import logging
from typing import Dict, List, Optional, Any, Union
from .agent import Agent
from ..llm.model_router import ModelRouter
from ..llm import LLM
logger = logging.getLogger(__name__)
class RouterAgent(Agent):
"""
An enhanced agent that can dynamically select and use different LLM models
based on task requirements, optimizing for cost and performance.
"""
def __init__(
self,
models: Optional[Union[List[str], Dict[str, Any]]] = None,
model_router: Optional[ModelRouter] = None,
routing_strategy: str = "auto", # "auto", "manual", "cost-optimized", "performance-optimized"
primary_model: Optional[str] = None,
fallback_model: Optional[str] = None,
**kwargs
):
"""
Initialize a RouterAgent.
Args:
models: List of model names or dict mapping model names to configurations
model_router: Custom ModelRouter instance for model selection
routing_strategy: Strategy for model selection
primary_model: Primary model to use (overrides routing for simple tasks)
fallback_model: Fallback model if selected model fails
**kwargs: Additional arguments passed to parent Agent class
"""
# Initialize model router
self.model_router = model_router or ModelRouter()
self.routing_strategy = routing_strategy
self.fallback_model = fallback_model or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o-mini')
# Process models configuration
self.available_models = self._process_models_config(models)
# Set primary model for parent class initialization
if primary_model:
kwargs['llm'] = primary_model
elif self.available_models:
# Use the most cost-effective model as default
cheapest_model = min(
self.available_models.keys(),
key=lambda m: self.model_router.get_model_info(m).cost_per_1k_tokens
if self.model_router.get_model_info(m) else float('inf')
)
kwargs['llm'] = cheapest_model
# Store the original llm parameter for later use
self._llm_config = kwargs.get('llm')
# Store api_key and base_url for LLM initialization
self._base_url = kwargs.get('base_url')
self._api_key = kwargs.get('api_key')
# Initialize parent Agent class
super().__init__(**kwargs)
# Initialize LLM instances for each model
self._llm_instances: Dict[str, LLM] = {}
self._initialize_llm_instances()
# Track usage statistics
self.model_usage_stats = {model: {'calls': 0, 'tokens': 0, 'cost': 0.0}
for model in self.available_models}
def _process_models_config(self, models: Optional[Union[List[str], Dict[str, Any]]]) -> Dict[str, Any]:
"""Process the models configuration into a standardized format."""
if not models:
# Use default models from router
return {m.name: {} for m in self.model_router.models}
if isinstance(models, list):
# Simple list of model names
return {model: {} for model in models}
# Already a dict with model configurations
return models
def _initialize_llm_instances(self):
"""Initialize LLM instances for each available model."""
base_url = self._base_url
api_key = self._api_key
for model_name, config in self.available_models.items():
try:
# Merge base configuration with model-specific config
llm_config = {
'model': model_name,
'base_url': config.get('base_url', base_url),
'api_key': config.get('api_key', api_key),
'verbose': self.verbose,
'markdown': self.markdown,
'stream': self.stream
}
# Add any model-specific parameters
llm_config.update(config)
# Create LLM instance
self._llm_instances[model_name] = LLM(**llm_config)
logger.debug(f"Initialized LLM instance for model: {model_name}")
except Exception as e:
logger.warning(f"Failed to initialize LLM for model {model_name}: {e}")
def _select_model_for_task(
self,
task_description: str,
tools: Optional[List[Any]] = None,
context_size: Optional[int] = None
) -> str:
"""
Select the most appropriate model for a given task.
Args:
task_description: Description of the task
tools: Tools required for the task
context_size: Estimated context size
Returns:
Selected model name
"""
if self.routing_strategy == "manual":
# Use the configured primary model from llm_model property
llm_model = self.llm_model
if hasattr(llm_model, 'model'):
# If it's an LLM instance, get the model name
return llm_model.model
elif isinstance(llm_model, str):
# If it's a string, use it directly
return llm_model
# Fallback if no model is configured
return self.fallback_model
# Determine required capabilities
required_capabilities = []
if tools:
required_capabilities.append("function-calling")
# Determine budget consciousness based on strategy
budget_conscious = self.routing_strategy in ["auto", "cost-optimized"]
# Get tool names for analysis
tool_names = []
if tools:
tool_names = [t.__name__ if hasattr(t, '__name__') else str(t) for t in tools]
# Use router to select model
selected_model = self.model_router.select_model(
task_description=task_description,
required_capabilities=required_capabilities,
tools_required=tool_names,
context_size=context_size,
budget_conscious=budget_conscious
)
# Ensure selected model is available
if selected_model not in self._llm_instances:
logger.warning(f"Selected model {selected_model} not available, using fallback")
return self.fallback_model
return selected_model
def _execute_with_model(
self,
model_name: str,
prompt: str,
context: Optional[str] = None,
tools: Optional[List[Any]] = None,
**kwargs
) -> str:
"""
Execute a task with a specific model.
Args:
model_name: Name of the model to use
prompt: The prompt to send to the model
context: Additional context
tools: Tools to make available
**kwargs: Additional arguments for the LLM
Returns:
Model response
"""
llm_instance = self._llm_instances.get(model_name)
if not llm_instance:
logger.error(f"Model {model_name} not initialized, using fallback")
llm_instance = self._llm_instances.get(self.fallback_model)
model_name = self.fallback_model
if not llm_instance:
raise ValueError("No LLM instance available for execution")
# Prepare the full prompt
full_prompt = prompt
if context:
full_prompt = f"{context}\n\n{prompt}"
try:
# Execute with the selected model
response = llm_instance.get_response(
prompt=full_prompt,
system_prompt=self._build_system_prompt(),
tools=tools,
verbose=self.verbose,
markdown=self.markdown,
stream=self.stream,
agent_name=self.name,
agent_role=self.role,
agent_tools=[t.__name__ if hasattr(t, '__name__') else str(t) for t in (tools or [])],
execute_tool_fn=self.execute_tool if tools else None,
**kwargs
)
# Update usage statistics
self.model_usage_stats[model_name]['calls'] += 1
# TODO: Implement token tracking when LLM.get_response() is updated to return token usage
# The LLM response currently returns only text, but litellm provides usage info in:
# response.get("usage") with prompt_tokens, completion_tokens, and total_tokens
# This would require modifying the LLM class to return both text and metadata
return response
except Exception as e:
logger.error(f"Error executing with model {model_name}: {e}")
# Try fallback model if different
if model_name != self.fallback_model and self.fallback_model in self._llm_instances:
logger.info(f"Attempting with fallback model: {self.fallback_model}")
return self._execute_with_model(
self.fallback_model, prompt, context, tools, **kwargs
)
raise
def execute(
self,
task_description: str,
context: Optional[str] = None,
tools: Optional[List[Any]] = None,
**kwargs
) -> str:
"""
Execute a task with automatic model selection.
This method overrides the parent Agent's execute method to add
intelligent model selection.
Args:
task_description: Description of the task to execute
context: Optional context for the task
tools: Optional tools to use
**kwargs: Additional arguments
Returns:
Task execution result
"""
# Estimate context size in tokens (rough estimate: ~4 chars per token)
# This is a simplified heuristic; actual tokenization varies by model
text_length = len(task_description) + (len(context) if context else 0)
context_size = text_length // 4 # Approximate token count
# Select the best model for this task
selected_model = self._select_model_for_task(
task_description=task_description,
tools=tools,
context_size=context_size
)
logger.info(f"RouterAgent '{self.name}' selected model: {selected_model} for task")
# Execute with the selected model
return self._execute_with_model(
model_name=selected_model,
prompt=task_description,
context=context,
tools=tools,
**kwargs
)
def get_usage_report(self) -> Dict[str, Any]:
"""
Get a report of model usage statistics.
Returns:
Dictionary containing usage statistics and cost estimates
"""
total_cost = 0.0
report = {
'agent_name': self.name,
'routing_strategy': self.routing_strategy,
'model_usage': {}
}
for model, stats in self.model_usage_stats.items():
model_info = self.model_router.get_model_info(model)
if model_info and stats['tokens'] > 0:
cost = self.model_router.estimate_cost(model, stats['tokens'])
stats['cost'] = cost
total_cost += cost
report['model_usage'][model] = stats
report['total_cost_estimate'] = total_cost
report['total_calls'] = sum(s['calls'] for s in self.model_usage_stats.values())
return report
def _build_system_prompt(self) -> str:
"""Build system prompt (inherited from parent but can be customized)."""
base_prompt = super()._build_system_prompt()
# Add multi-model context if needed
if self.routing_strategy == "auto":
base_prompt += "\n\nNote: You are part of a multi-model system. Focus on your specific task."
return base_prompt
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more