Compare commits

...
140 Commits
Author SHA1 Message Date
Mervin Praison dbd6062edf chore: bump praisonai to v2.2.70 and praisonaiagents to v0.0.142 across all files 2025-07-17 01:31:56 +01:00
Mervin Praison 7fc615ff70 Merge pull request #974 from MervinPraison/claude/pr-965-20250716-2356
fix: make TelemetryCollector.stop() consistent with shutdown behavior
2025-07-17 01:24:26 +01:00
Mervin Praison fabac466f9 Merge pull request #966 from MervinPraison/claude/issue-964-20250716-2340
fix: improve Ollama sequential tool execution to prevent redundant calls
2025-07-17 01:22:11 +01:00
github-actions[bot]andMervin Praison 8d98f27f9c fix: correct Ollama early stopping logic placement for sequential tool execution
Fixes critical issues identified in PR review:
- Move early stopping logic from inside ''if tool_calls:'' block to ''else:'' block
- Fix logic placement in both sync and async execution paths
- Remove unreachable code in _generate_ollama_tool_summary()
- Ensure early stopping triggers correctly when Ollama returns empty responses after tool execution

This ensures the fix properly handles the Ollama edge case where it returns
empty responses after successful tool execution, preventing infinite loops
while allowing proper sequential tool calls.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-17 00:02:48 +00:00
github-actions[bot]andMervin Praison cf0af4999d fix: make TelemetryCollector.stop() consistent with shutdown behavior
Ensures TelemetryCollector.stop() calls shutdown() instead of just flush()
for consistency with the main atexit handler and proper PostHog session cleanup.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-17 00:01:42 +00:00
github-actions[bot]andMervin Praison f6ecd3b4db fix: improve Ollama early stopping logic to allow proper sequential tool execution
- Only trigger early stopping when no new tool calls are present in current response
- Prevents premature termination during sequential tool calls like get_stock_price -> multiply
- Maintains backward compatibility while fixing issue #964
- Applied to both sync and async execution paths

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:56:48 +00:00
Mervin Praison a348d186c3 Merge pull request #965 from MervinPraison/claude/issue-963-20250716-2334
fix: properly shutdown telemetry aiohttp sessions to prevent ImportError during Python shutdown
2025-07-17 00:54:16 +01:00
Mervin Praison 30c0f2458f Merge pull request #961 from MervinPraison/claude/issue-958-20250716-2304
fix: ensure consistent Task/Response formatting across all LLM providers
2025-07-17 00:53:53 +01:00
Mervin Praison 668d61344f Merge branch 'main' into claude/issue-958-20250716-2304 2025-07-17 00:47:55 +01:00
github-actions[bot]andMervin Praison e8e9625f22 fix: improve Ollama sequential tool execution to prevent redundant calls
- Add early stopping logic for Ollama after first successful tool execution
- Enhance tool summary generation to create more natural, OpenAI-like responses
- Apply fix to both sync and async execution paths
- Prevent multiple tool calls when execution is complete
- Maintains full backward compatibility

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:47:43 +00:00
Mervin Praison cc721ba0db feat: upgrade praisonai to v2.2.69 and add realtime streaming support 2025-07-17 00:45:38 +01:00
Mervin Praison 07a30ab33d Merge pull request #962 from MervinPraison/claude/issue-956-20250716-2316
fix: enable real-time streaming regardless of verbose setting
2025-07-17 00:41:34 +01:00
github-actions[bot]andMervin Praison 92978fdb1c fix: properly shutdown telemetry aiohttp sessions to prevent ImportError during Python shutdown
- Change atexit handler from flush() to shutdown() in telemetry/__init__.py
- This ensures PostHog aiohttp sessions are properly closed before Python shutdown
- Prevents ''ImportError: sys.meta_path is None, Python is likely shutting down'' error
- Maintains backward compatibility with existing functionality

Fixes #963

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:40:40 +00:00
github-actions[bot]andMervin Praison 15a307dd4e fix: complete streaming fix for all LLM providers and improve console handling
- Fix custom LLM streaming (Gemini/Vertex AI) in llm.py by removing verbose condition
- Improve console parameter consistency when streaming is enabled
- Ensures streaming works for stream=True regardless of verbose setting
- Maintains full backward compatibility

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:38:27 +00:00
Mervin Praison 053ad043b8 Merge pull request #960 from MervinPraison/claude/issue-940-20250716-2252
fix: accumulate tool results across iterations in Ollama sequential execution
2025-07-17 00:35:49 +01:00
github-actions[bot]andMervin Praison 6e664995e8 fix: add missing flag reset in async achat method for consistent display behavior
- Added _final_display_shown = False reset in achat() method to match chat() method
- Ensures proper display flag management for both sync and async agent interactions
- Maintains consistency across all agent conversation entry points

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:32:12 +00:00
github-actions[bot]andMervin Praison ccb1bccf0f chore: remove unused custom_display_fn from agent.py
- Removed unused custom_display_fn function that was defined but never called
- Cleanup after streaming fix to avoid confusion
- No functional changes, streaming fix remains intact

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:31:38 +00:00
Mervin Praison 94c8fc21e6 Merge pull request #959 from MervinPraison/claude/issue-947-20250716-2244
fix: resolve task_name undefined error in async execution
2025-07-17 00:29:30 +01:00
github-actions[bot]andMervin Praison 48575b4ee0 fix: ensure callback execution in all achat() paths
- Enhanced _chat_completion method signature to accept task metadata parameters
- Updated all calls to _chat_completion to pass task context
- Fixed NameError where task_name, task_description, task_id were undefined
- Updated _apply_guardrail_with_retry to propagate task metadata
- Ensures complete task metadata propagation in sync chat execution path

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:28:05 +00:00
github-actions[bot]andMervin Praison 2ce7136d0c refactor: improve Ollama sequential fix with better test and deduplication
- Enhanced test file with comprehensive behavioral validation
- Added proper module import handling and mock-based testing
- Extracted duplicated logic into _handle_ollama_sequential_logic helper
- Eliminated 18-line code duplication between sync and async methods
- Improved maintainability while preserving backward compatibility

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:27:36 +00:00
github-actions[bot]andMervin Praison 3bea2ffb10 fix: enable real-time streaming regardless of verbose setting
- Remove dependency on verbose=True for streaming display function
- Allow stream=True to work with verbose=False for real-time output
- Maintain backward compatibility with existing verbose=True usage
- Fixes issue where Gemini/Google Vertex AI streaming was buffered

Resolves #956

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:22:35 +00:00
Mervin Praison fcbd915a0e docs: move star history section above feature roadmap for better visibility 2025-07-17 00:21:52 +01:00
github-actions[bot]andMervin Praison ae7eb29684 fix: ensure callback execution in all achat() paths
Adds missing callback execution to tool-based responses and JSON/Pydantic
output paths in the achat() method to ensure consistent task metadata
propagation across all execution flows.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:19:57 +00:00
Mervin Praison c5ec1ffea0 refactor: move test files to src/praisonai-agents directory for better organization 2025-07-17 00:19:56 +01:00
Mervin Praison aad5f286e2 chore: bump PraisonAI to v2.2.68 and PraisonAI Agents to v0.0.140 2025-07-17 00:19:32 +01:00
github-actions[bot]andMervin Praison 1aa20de337 fix: ensure consistent Task/Response formatting across all LLM providers
- Modified display condition to show formatted output for both OpenAI and custom LLM providers (like Gemini)
- Added _final_display_shown flag to prevent duplicate displays within same execution
- Reset flag at start of each chat() call for new conversations
- Maintains backward compatibility and existing verbose control behavior

Fixes #958

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:15:08 +00:00
Mervin Praison 3bc185d15d Merge pull request #957 from MervinPraison/claude/comprehensive-task-name-fix-20250716
fix: comprehensive task_name undefined error resolution
2025-07-17 00:14:20 +01:00
github-actions[bot]andMervin Praison 6b8a7110f2 refactor: simplify redundant hasattr checks and fix test formatting
- Remove redundant hasattr checks in agent.py as getattr handles missing attributes
- Fix unnecessary f-string prefixes in test file
- Remove unused variable assignment in test

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:08:04 +00:00
Mervin Praison 5ab0f245c5 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-17 00:03:23 +01:00
Mervin Praison 5baa3f9b96 fix: update LLM model in Ollama sequential agent from qwen3 to llama3.2 for improved performance 2025-07-17 00:03:04 +01:00
github-actions[bot]andMervin Praison 28c6d026f7 fix: resolve task_name undefined error in async execution
Addresses issue #947 where task_name undefined errors occurred during async parallel task execution.

Key Changes:
- Enhanced Agent.achat() method to accept task context parameters (task_name, task_description, task_id)
- Updated aexecute_task() to pass task metadata when calling agent.achat()
- Added callback execution to both async execution paths in achat() method
- Updated callback system to properly propagate task context

Root Cause: Async execution path was missing task metadata propagation to LLM callbacks.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 23:00:34 +00:00
github-actions[bot]andMervin Praison 802716e5ec fix: comprehensive task_name undefined error resolution
- Add task_name, task_description, task_id parameters to achat method signature
- Update all achat call sites in agents.py to pass task parameters where available
- Provide fallback None values for API handler contexts without task context
- Fix Agent.aexecute to extract task info when available
- Resolves NameError: name ''task_name'' is not defined in parallel agent execution

Fixes persistent errors in agentic parallelization workflows where callbacks
expect task context parameters but they were not being passed correctly through
the async execution chain.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 22:58:16 +00:00
github-actions[bot]andMervin Praison 9eaa2731da fix: accumulate tool results across iterations in Ollama sequential execution
- After successful tool execution, give Ollama LLM explicit prompt for final answer
- Only generate tool summary if LLM fails to respond to explicit prompt
- Prevents premature tool summary generation after sequential execution
- Applied to both sync and async tool execution loops
- Preserves infinite loop prevention while enabling natural responses

Fixes #940

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 22:56:02 +00:00
Mervin Praison 0d3e1632a3 Merge pull request #949 from Dhivya-Bharathy/models-providers-reorganization
Reorganize models and providers structure with comprehensive examples
2025-07-16 23:45:08 +01:00
Mervin Praison da14b1d8e9 Merge pull request #955 from MervinPraison/claude/pr-953-20250716-1258
fix: resolve Ollama infinite loop issue with minimal changes
2025-07-16 16:02:48 +01:00
Mervin Praison c0679f4528 Merge pull request #954 from MervinPraison/claude/issue-940-20250716-1247
fix: prevent premature termination in Ollama sequential tool execution
2025-07-16 15:18:42 +01:00
github-actions[bot]andMervin Praison 930555d921 fix: accumulate tool results across iterations in Ollama sequential execution
- Replace hardcoded iteration threshold (3) with class constant OLLAMA_SUMMARY_ITERATION_THRESHOLD
- Add proper constant definition for better maintainability and readability
- Applied consistently to both sync and async methods
- Addresses reviewer feedback about magic numbers
- Ensures proper tool result accumulation across iterations

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 13:24:35 +00:00
Mervin Praison 859fb6a263 chore: bump praisonai to v2.2.67 and praisonaiagents to v0.0.138 across all files 2025-07-16 14:16:30 +01:00
github-actions[bot]andMervin Praison f154dba804 fix: accumulate tool results across iterations in Ollama sequential execution
- Add accumulated_tool_results list to store tool results across all iterations
- Prevents loss of tool execution history when generating summaries
- Applied to both sync (get_response) and async (get_response_async) methods
- Maintains backward compatibility with existing functionality
- Fixes issue where only current iteration''s tool results were available to summary generation

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 13:15:14 +00:00
Mervin Praison fb2a16126f Merge pull request #952 from MervinPraison/claude/issue-947-20250716-1205
fix: resolve task_name undefined error in LLM callback execution
2025-07-16 14:14:52 +01:00
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] ddb547f6a5 cleanup: remove debug test files 2025-07-16 13:08:03 +00:00
github-actions[bot]andMervin Praison 24437b40d9 fix: resolve Ollama infinite loop issue with minimal changes
- Remove redundant length check in _generate_ollama_tool_summary
- Simplify verbose conditional checks in both sync and async methods
- Add safety checks to prevent infinite loops after 5 iterations
- Maintain backward compatibility with other LLM providers
- Add comprehensive test suite to validate fixes

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 13:07:39 +00:00
Dhivya-Bharathy 582049f759 Update model examples to use new clean format with praisonaiagents.Agent 2025-07-16 18:32:35 +05:30
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
github-actions[bot]andMervin Praison e1b93000be fix: prevent premature termination in Ollama sequential tool execution
- Modified tool execution logic to allow at least 3 iterations before triggering summary generation
- This prevents Ollama from prematurely terminating when sequential tool calls are needed
- Applied fix to both conversation() and reasoning() methods in LLM class
- Resolves issue where Ollama would generate tool summaries too early, blocking proper tool chaining

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

Co-Authored-By: Mervin Praison <[email protected]>
2025-07-16 12:51:13 +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 318ececfb4 fix: correct function name in test_fix_verification.py
- Fixed unused variable 'results' in test_fix_verification.py
- Maintained test functionality while removing static analysis warning

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 12:35:26 +00:00
github-actions[bot]andMervin Praison 83afc0891f fix: correct function name in test_fix_verification.py
- Changed register_callback to register_display_callback
- Ensures test runs correctly and validates the fix

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 12:29:42 +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
Dhivya-Bharathy 8dd6494a59 Update all provider examples to use new clean format with praisonaiagents.Agent 2025-07-16 17:54:50 +05:30
github-actions[bot]andMervin Praison 857238a82a fix: resolve task_name undefined error in LLM callback execution
- Fixed 6 direct execute_sync_callback calls missing task-related parameters
- Added agent_name, agent_role, agent_tools, task_name, task_description, task_id
- Ensures consistent callback parameter passing between verbose and non-verbose modes
- Prevents infinite loop errors when callbacks expect task_name parameter
- Maintains backward compatibility with existing functionality

Fixes #947

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-16 12:21:27 +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
Dhivya-Bharathy 1ab09fa259 Reorganize models and providers structure - Move Kimi2 agents to models/kimi with kimi_ prefix - Move Grok4 agents to models/grok with grok_ prefix - Create 10 new Groq agents in models/groq with groq_ prefix - Add provider examples for OpenAI, Anthropic, Google, DeepSeek, Mistral, Cohere, xAI - Remove README files as requested 2025-07-16 16:35:00 +05:30
Dhivya-Bharathy f7f4a6c0bf Add 10 new agents to Kimi2_Intelligent_Agents (aerospace, bioinformatics, blockchain, energy, IoT, metaverse, nanotechnology, quantum AI, quantum computing, robotics) 2025-07-16 15:02:46 +05:30
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
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
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
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
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
158 changed files with 9039 additions and 1132 deletions

No files matched your search

+6 -3
View File
@@ -1,4 +1,4 @@
name: Auto Issue Comment
name: Auto Issue Comment with PR Creation
on:
issues:
@@ -9,6 +9,9 @@ jobs:
runs-on: ubuntu-latest
permissions:
issues: write
contents: write
pull-requests: write
actions: read
steps:
- name: Add automated comment
uses: actions/github-script@v7
@@ -19,5 +22,5 @@ jobs:
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.'
})
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**.'
})
+39 -11
View File
@@ -36,6 +36,25 @@ jobs:
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:
@@ -53,7 +72,7 @@ jobs:
with:
github-token: ${{ secrets.GH_TOKEN }}
script: |
const reviewText = '@claude review if the changes made are as per the requirements';
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;
@@ -111,23 +130,32 @@ jobs:
github-token: ${{ secrets.GH_TOKEN }}
script: |
let issueNumber;
let isPR = false;
// Determine issue/PR number based on event type
// 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
// This is a regular issue - don't post review comment
issueNumber = context.issue.number;
isPR = false;
}
console.log(`Posting review comment on issue/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 are as per the requirements'
});
// 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}`);
}
+4 -4
View File
@@ -120,6 +120,10 @@ agent.start('Write a movie script about a robot in Mars');
![PraisonAI CLI Demo](docs/demo/praisonai-cli-demo.gif)
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=MervinPraison/PraisonAI&type=Date)](https://docs.praison.ai)
## AI Agents Flow
```mermaid
@@ -557,10 +561,6 @@ uv pip install -r pyproject.toml --extra "crewai,autogen"
- 🖼️ Vision Language Model (VLM) Support
- 🎙️ Real-time Voice Interaction
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=MervinPraison/PraisonAI&type=Date)](https://docs.praison.ai)
## Video Tutorials
| Topic | Video |
+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.57" \
"praisonai>=2.2.70" \
"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.57" \
"praisonai>=2.2.70" \
"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.57" \
"praisonai>=2.2.70" \
"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.57" \
"praisonai>=2.2.70" \
"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.57`
- PraisonAI: `>=2.2.70`
- 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.57" "praisonaiagents==0.0.92"
RUN pip install "praisonai==2.2.70" "praisonaiagents==0.0.92"
```
## 🌐 Production Deployment
@@ -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
}
@@ -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,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,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.")
@@ -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,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!
@@ -1,18 +1,12 @@
import asyncio
from praisonaiagents import Agent
async def main():
agent = Agent(
instructions="You are a helpful assistant",
llm="gemini/gemini-1.5-flash-8b",
self_reflect=True,
verbose=True
)
agent = Agent(
instructions="You are a helpful assistant",
llm="gemini/gemini-1.5-flash-8b",
self_reflect=True,
verbose=True
)
# Use achat instead of start/chat for async operation
response = await agent.achat("Why sky is Blue in 1000 words?")
print(response)
if __name__ == "__main__":
# Run the async main function
asyncio.run(main())
# Use achat instead of start/chat for async operation
response = asyncio.run(agent.achat("Why sky is Blue in 1000 words?"))
@@ -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,30 @@
"""
Basic example of using Grok model in PraisonAI
"""
from praisonaiagents import Agent
# Initialize Agent with Grok model
agent = Agent(
instructions="You are a helpful assistant",
llm="xai/grok-beta",
)
# Example conversation
response = agent.start("Hello! Can you explain quantum computing in simple terms?")
# Example with mathematical reasoning
math_task = """
Solve this problem step by step:
If a train travels at 60 mph for 2.5 hours, how far does it travel?
"""
response = agent.start(math_task)
# Example with creative writing
creative_task = """
Write a short story about a robot learning to paint.
Make it engaging and about 100 words.
"""
response = agent.start(creative_task)
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a crisis management and communication AI agent. "
"Help users develop crisis communication strategies, "
"manage reputation during difficult situations, and create effective messaging. "
"Provide guidance on crisis response planning, stakeholder communication, "
"media relations during crises, and reputation recovery strategies.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your crisis management and communication assistant. "
"How can I help you develop effective crisis communication "
"strategies and manage difficult situations today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a digital marketing and SEO optimization AI agent. "
"Help users develop digital marketing strategies, optimize for search engines, "
"and improve online visibility. Provide guidance on SEO best practices, "
"content marketing, social media strategies, PPC campaigns, "
"and analytics interpretation for better ROI.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your digital marketing and SEO optimization assistant. "
"How can I help you improve your online presence, "
"optimize for search engines, or develop marketing strategies today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are an environmental impact assessment AI agent. "
"Help users evaluate environmental impacts of projects, "
"develop sustainability strategies, and ensure compliance with environmental regulations. "
"Provide guidance on environmental risk assessment, sustainability reporting, "
"carbon footprint analysis, and green technology implementation.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your environmental impact assessment assistant. "
"How can I help you evaluate environmental impacts, "
"develop sustainability strategies, or ensure compliance today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are an event planning and management AI agent. "
"Help users plan, organize, and manage successful events of all types. "
"Provide guidance on venue selection, budgeting, vendor coordination, "
"timeline management, marketing strategies, and post-event analysis. "
"Assist with both virtual and in-person event planning.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your event planning and management assistant. "
"How can I help you plan and organize your next successful "
"event today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a healthcare and medical research AI agent. "
"Help users with medical research, healthcare insights, "
"and understanding complex medical information. Provide guidance on medical literature review, "
"healthcare trends analysis, patient care strategies, "
"and medical technology advancements for better healthcare outcomes.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your healthcare and medical research assistant. "
"How can I help you with medical research, healthcare insights, "
"or understanding complex medical information today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a language learning and translation AI agent. "
"Help users learn new languages, translate content accurately, "
"and understand cultural nuances. Provide guidance on language learning strategies, "
"grammar explanations, vocabulary building, pronunciation, "
"and cultural context for effective communication.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your language learning and translation assistant. "
"How can I help you learn new languages, translate content, "
"or understand cultural nuances today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a patent research and innovation AI agent. "
"Help users conduct patent research, analyze intellectual property, "
"identify innovation opportunities, and navigate patent filing processes. "
"Provide guidance on patent searches, prior art analysis, "
"innovation strategy, IP protection, and technology landscape assessment.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your patent research and innovation assistant. "
"How can I help you with patent research, innovation strategy, "
"and intellectual property protection today?")
@@ -0,0 +1,19 @@
"""
Personal Branding & PR Agent using Groq
Specialized agent for managing personal brand and public relations
"""
from praisonaiagents import Agent
agent = Agent(
instructions="You are a personal branding and PR AI agent. "
"Help users build their personal brand, manage public relations, "
"create compelling content strategies, and enhance their online presence. "
"Provide guidance on social media management, content creation, "
"media relations, reputation management, and brand positioning.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your personal branding and PR assistant. "
"How can I help you build your personal brand and "
"manage your public relations today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a product development and innovation AI agent. "
"Help users develop new products, improve existing ones, "
"and drive innovation in their business. Provide guidance on product strategy, "
"market research, user experience design, prototyping, "
"and innovation management for successful product launches.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your product development and innovation assistant. "
"How can I help you develop new products, improve existing ones, "
"or drive innovation in your business today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a supply chain optimization AI agent. "
"Help users optimize their supply chain operations, "
"improve logistics efficiency, reduce costs, and enhance inventory management. "
"Provide guidance on demand forecasting, supplier management, "
"warehouse optimization, transportation planning, and risk mitigation.",
llm="groq/llama3.1-8b-instant"
)
response = agent.start("Hello! I'm your supply chain optimization assistant. "
"How can I help you optimize your supply chain operations "
"and improve your logistics efficiency today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are an aerospace engineering AI agent. "
"Help users understand aerospace engineering concepts, "
"aircraft design, and space technology. Provide guidance on "
"aerodynamics, propulsion systems, materials science, "
"and satellite technology.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your aerospace engineering assistant. "
"How can I help you with aerospace engineering "
"and space technology today?")
@@ -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,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a bioinformatics and genomics AI agent. "
"Help users understand bioinformatics, genomics, "
"and computational biology. Provide guidance on "
"DNA sequence analysis, protein structure prediction, "
"genetic algorithms, and biological data mining.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your bioinformatics and genomics assistant. "
"How can I help you with bioinformatics "
"and genomics research today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a blockchain and DeFi AI agent. "
"Help users understand blockchain technology, "
"decentralized finance, and cryptocurrency. Provide guidance on "
"smart contract development, DeFi protocols, "
"tokenomics, and blockchain security.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your blockchain and DeFi assistant. "
"How can I help you explore blockchain technology "
"and decentralized finance 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,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are an energy and renewables AI agent. "
"Help users understand renewable energy technologies, "
"energy systems, and sustainability. Provide guidance on "
"solar power, wind energy, energy storage, "
"and green technology solutions.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your energy and renewables assistant. "
"How can I help you with renewable energy "
"and sustainability 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,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are an IoT and smart cities AI agent. "
"Help users understand Internet of Things, smart city "
"technologies, and connected systems. Provide guidance on "
"IoT device integration, smart infrastructure, "
"sensor networks, and urban technology solutions.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your IoT and smart cities assistant. "
"How can I help you with IoT and smart city "
"technologies today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a metaverse and virtual reality AI agent. "
"Help users understand metaverse concepts, VR development, "
"and immersive technologies. Provide guidance on "
"3D modeling, VR programming, digital twins, "
"and virtual world design.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your metaverse and VR assistant. "
"How can I help you explore the metaverse "
"and virtual reality today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a nanotechnology and materials AI agent. "
"Help users understand nanotechnology, advanced materials, "
"and material science. Provide guidance on "
"nanomaterials, material properties, fabrication techniques, "
"and applications in various industries.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your nanotechnology and materials assistant. "
"How can I help you with nanotechnology "
"and materials science today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a quantum AI agent. "
"Help users understand quantum artificial intelligence, "
"quantum machine learning, and quantum neural networks. "
"Provide guidance on quantum algorithms for AI, "
"quantum optimization, and hybrid quantum-classical systems.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your quantum AI assistant. "
"How can I help you explore quantum artificial "
"intelligence today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a quantum computing AI agent. "
"Help users understand quantum computing concepts, "
"quantum algorithms, and quantum programming. Provide guidance on "
"quantum circuit design, quantum error correction, "
"quantum machine learning, and quantum cryptography.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your quantum computing assistant. "
"How can I help you explore quantum computing "
"and quantum programming today?")
@@ -0,0 +1,14 @@
from praisonaiagents import Agent
agent = Agent(
instructions="You are a robotics and automation AI agent. "
"Help users understand robotics, automation systems, "
"and industrial applications. Provide guidance on "
"robot programming, automation workflows, "
"sensor integration, and robotic process automation.",
llm="openrouter/moonshotai/kimi-k2"
)
response = agent.start("Hello! I'm your robotics and automation assistant. "
"How can I help you with robotics and "
"automation systems 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,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,31 @@
"""
Basic example of using Anthropic Claude with PraisonAI
"""
from praisonaiagents import Agent
# Initialize Agent with Anthropic Claude
agent = Agent(
instructions="You are a helpful assistant",
llm="anthropic/claude-3-5-sonnet-20241022",
)
# Example conversation
response = agent.start("Hello! Can you help me with a writing task?")
# Example with creative writing
writing_task = """
Write a short story about a time traveler who discovers
they can only travel to moments of great historical significance.
Make it engaging and about 200 words.
"""
response = agent.start(writing_task)
# Example with reasoning
reasoning_task = """
Explain the concept of quantum entanglement in simple terms,
and then discuss its potential applications in quantum computing.
"""
response = agent.start(reasoning_task)
@@ -0,0 +1,36 @@
"""
Basic example of using Cohere with PraisonAI
"""
from praisonaiagents import Agent
# Initialize Agent with Cohere
agent = Agent(
instructions="You are a helpful assistant",
llm="cohere/command-r-plus",
)
# Example conversation
response = agent.start("Hello! Can you help me with a business analysis task?")
# Example with business analysis
business_task = """
Analyze the potential market opportunities for a new AI-powered
productivity tool targeting remote workers. Include market size,
competitive landscape, and go-to-market strategy recommendations.
"""
response = agent.start(business_task)
# Example with document summarization
summary_task = """
Summarize the key points from this business proposal:
Our company proposes to develop an AI-powered customer service chatbot
that can handle 80% of common customer inquiries automatically. The system
will integrate with existing CRM platforms and provide 24/7 support.
Expected ROI is 300% within the first year, with implementation taking
6 months and requiring a team of 5 developers.
"""
response = agent.start(summary_task)
@@ -0,0 +1,37 @@
"""
Basic example of using DeepSeek with PraisonAI
"""
from praisonaiagents import Agent
# Initialize Agent with DeepSeek
agent = Agent(
instructions="You are a helpful assistant",
llm="deepseek/deepseek-chat",
)
# Example conversation
response = agent.start("Hello! Can you help me with a mathematical problem?")
# Example with mathematical reasoning
math_task = """
Solve this calculus problem step by step:
Find the derivative of f(x) = x^3 * e^(2x) using the product rule.
"""
response = agent.start(math_task)
# Example with code optimization
code_task = """
Optimize this Python function for better performance:
def find_duplicates(arr):
duplicates = []
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] == arr[j] and arr[i] not in duplicates:
duplicates.append(arr[i])
return duplicates
"""
response = agent.start(code_task)
@@ -0,0 +1,30 @@
"""
Basic example of using Google Gemini with PraisonAI
"""
from praisonaiagents import Agent
# Initialize Agent with Google Gemini
agent = Agent(
instructions="You are a helpful assistant",
llm="google/gemini-1.5-pro",
)
# Example conversation
response = agent.start("Hello! Can you help me with a research task?")
# Example with research and analysis
research_task = """
Research and provide insights on the latest developments in
renewable energy technology, focusing on solar and wind power innovations.
"""
response = agent.start(research_task)
# Example with multimodal capabilities (text-based for now)
multimodal_task = """
Describe how you would analyze an image of a city skyline
and provide insights about urban development patterns.
"""
response = agent.start(multimodal_task)
@@ -0,0 +1,22 @@
"""
Basic example of using Kimi model with Groq provider in PraisonAI
"""
from praisonaiagents import Agent
# Initialize Agent with Kimi model using Groq provider
agent = Agent(
instructions="You are a helpful assistant",
llm="groq/kimi",
)
# Example conversation
response = agent.start("Hello! Can you help me with a coding task?")
# Example with more complex task
coding_task = """
Write a Python function that calculates the factorial of a number.
Include error handling and documentation.
"""
response = agent.start(coding_task)
@@ -0,0 +1,30 @@
"""
Basic example of using Mistral with PraisonAI
"""
from praisonaiagents import Agent
# Initialize Agent with Mistral
agent = Agent(
instructions="You are a helpful assistant",
llm="mistral/mistral-large-latest",
)
# Example conversation
response = agent.start("Why sky is Blue?")
# Example with language translation
translation_task = """
Translate the following text to French and explain any cultural nuances:
"The early bird catches the worm, but the second mouse gets the cheese."
"""
response = agent.start(translation_task)
# Example with creative content generation
creative_task = """
Write a haiku about artificial intelligence and its impact on society.
Then explain the symbolism in your haiku.
"""
response = agent.start(creative_task)
@@ -0,0 +1,30 @@
"""
Basic example of using OpenAI GPT-4 with PraisonAI
"""
from praisonaiagents import Agent
# Initialize Agent with OpenAI GPT-4
agent = Agent(
instructions="You are a helpful assistant",
llm="openai/gpt-4o",
)
# Example conversation
response = agent.start("Hello! Can you help me with a coding task?")
# Example with code generation
coding_task = """
Write a Python function that implements a binary search algorithm.
Include proper documentation and error handling.
"""
response = agent.start(coding_task)
# Example with analysis
analysis_task = """
Analyze the pros and cons of using microservices architecture
for a large-scale e-commerce application.
"""
response = agent.start(analysis_task)
@@ -0,0 +1,41 @@
"""
Basic example of using xAI Grok with PraisonAI
"""
from praisonaiagents import Agent
# Initialize Agent with xAI Grok
agent = Agent(
instructions="You are a helpful assistant",
llm="xai/grok-beta",
)
# Example conversation
response = agent.start("Hello! Can you help me with a complex reasoning task?")
# Example with complex reasoning
reasoning_task = """
Analyze this scenario step by step:
A company has 100 employees, 60% work remotely, 30% work hybrid, and 10% work in-office.
They want to implement a new AI tool that requires high-speed internet.
What are the challenges and solutions for this implementation?
"""
response = agent.start(reasoning_task)
# Example with creative problem solving
creative_task = """
Design a solution for reducing food waste in urban areas using AI technology.
Consider economic, environmental, and social factors.
Provide a step-by-step implementation plan.
"""
response = agent.start(creative_task)
# Example with humor and personality (Grok's specialty)
humor_task = """
Explain quantum physics using analogies that would make a 10-year-old laugh,
while still being scientifically accurate.
"""
response = agent.start(humor_task)
@@ -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,110 @@
import asyncio
from praisonaiagents import Agent, Task, PraisonAIAgents
# Example tools (replace with real implementations as needed)
def fetch_favorite_article():
# Simulate fetching your favorite morning article
return "Your favorite morning article: 'How to Start Your Day Right'"
def search_trending_kenya():
# Simulate searching for trending news in Kenya
return "Trending in Kenya: 'Kenya launches new tech hub in Nairobi'"
def fetch_twitter_feed():
# Simulate fetching Twitter feed
return "Latest tweet: 'AI is transforming the world!'"
# Agents for each unique task
article_agent = Agent(
name="ArticleAgent",
role="Morning Article Fetcher",
goal="Fetch the user's favorite morning article",
tools=[fetch_favorite_article],
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
verbose=True
)
news_agent = Agent(
name="KenyaNewsAgent",
role="Kenya News Searcher",
goal="Search for trending news in Kenya",
tools=[search_trending_kenya],
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
verbose=True
)
twitter_agent = Agent(
name="TwitterAgent",
role="Twitter Feed Fetcher",
goal="Fetch the latest Twitter feed",
tools=[fetch_twitter_feed],
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
verbose=True
)
aggregator = Agent(
name="Aggregator",
role="Result Aggregator",
goal="Aggregate and summarize all results",
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
verbose=True
)
# Tasks for each agent
article_task = Task(
name="fetch_article",
description="Fetch the user's favorite morning article.",
expected_output="The favorite morning article.",
agent=article_agent,
is_start=True,
async_execution=True
)
news_task = Task(
name="search_kenya_news",
description="Search for trending news in Kenya.",
expected_output="Trending news in Kenya.",
agent=news_agent,
is_start=True,
async_execution=True
)
twitter_task = Task(
name="fetch_twitter",
description="Fetch the latest Twitter feed.",
expected_output="Latest Twitter feed.",
agent=twitter_agent,
is_start=True,
async_execution=True
)
# Aggregator task that depends on the above tasks
aggregate_task = Task(
name="aggregate_results",
description="Summarize the article, news, and Twitter feed results.",
expected_output="A summary of all fetched information.",
agent=aggregator,
context=[article_task, news_task, twitter_task]
)
async def main():
workflow = PraisonAIAgents(
agents=[article_agent, news_agent, twitter_agent, aggregator],
tasks=[article_task, news_task, twitter_task, aggregate_task],
process="workflow",
verbose=True
)
results = await workflow.astart(dict_output=True)
print("\nParallel Processing Results:")
# Handle both string and dictionary return types
if isinstance(results, dict) and "task_results" in results:
for task_id, result in results["task_results"].items():
if result:
print(f"Task {task_id}: {result.raw}")
else:
print("Final result:", results)
if __name__ == "__main__":
asyncio.run(main())
+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)
+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")
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more