Compare commits

...
779 Commits
Author SHA1 Message Date
Mervin Praison d51327effd Release v2.3.46 2025-12-19 12:22:29 +00:00
Mervin Praison 30ce8857e8 fix: suppress crewai.cli.config INFO log at startup 2025-12-19 12:18:23 +00:00
Mervin Praison 397874ccfc Release v2.3.45 2025-12-19 12:16:12 +00:00
Mervin Praison 2016902e9a docs: Add examples README with quick links to docs 2025-12-19 11:14:24 +00:00
Mervin Praison d2d19511da docs: Update README with Model Router info and fix links
- Rename 'Router Agent' to 'Model Router' for consistency
- Fix docs link to point to /features/model-router
- Add model-routing template CLI command
- Add link to Model Router documentation
2025-12-19 11:13:48 +00:00
Mervin Praison bc9579b497 Add Code category with individual examples for external CLI integrations
- Add Code category in Key Features table (like Workflows)
- Add individual examples for each external agent:
  - claude_code_example.py
  - gemini_cli_example.py
  - codex_cli_example.py
  - cursor_cli_example.py
  - external_agents_example.py (all integrations)
  - code_editing_example.py
- Link to individual docs pages for each integration
- Organize code-related features under Code category
2025-12-19 11:07:25 +00:00
Mervin Praison 3161389341 Add External Agents CLI documentation to README
- Add External Agents feature to Key Features table
- Update Code Editing docs link to /code/editing
- Add External Agents CLI section with examples
- Include Python API usage examples
- Add environment variables documentation
- Link to detailed docs at docs.praison.ai/code/external-agents
2025-12-19 11:01:24 +00:00
Mervin Praison b01eb2b8fa Release v2.3.44 2025-12-19 10:50:33 +00:00
Mervin Praison e609fb7425 Release v2.3.43 2025-12-19 10:32:33 +00:00
Mervin Praison 168ef98473 feat: Implement all remaining AutoAgents improvements (TDD)
TODO 2: Single-Agent Option
- Add SingleAgentStructure Pydantic model
- Add single_agent parameter to AutoGenerator and WorkflowAutoGenerator

TODO 3: LLM-Based Pattern Recommendation
- Add PatternRecommendation Pydantic model (pattern, reasoning, confidence)
- Add recommend_pattern_llm() method to WorkflowAutoGenerator

TODO 4: Validation Gates
- Add ValidationGate Pydantic model (criteria, pass_action, fail_action)
- Add optional gates field to WorkflowStructure

TODO 6: Pattern Support for AutoGenerator
- Add pattern parameter to AutoGenerator
- Add recommend_pattern() method to AutoGenerator
- Add pattern-specific guidance in get_user_content()

TODO 7: Merge Support for WorkflowAutoGenerator
- Add merge parameter to generate() method
- Add merge_with_existing_workflow() method

TODO 10: Framework Support for WorkflowAutoGenerator
- Add framework parameter to WorkflowAutoGenerator
- Default framework is 'praisonai'

Test Coverage:
- 51 tests pass (up from 34)
- 17 new tests added using TDD approach
- All tests verify new functionality
2025-12-19 10:29:40 +00:00
Mervin Praison ce2c2926f9 refactor: Add BaseAutoGenerator class and improve WorkflowAutoGenerator
- Create BaseAutoGenerator with shared functionality (DRY principle)
  - Lazy-loaded instructor client (LiteLLM or OpenAI fallback)
  - Environment variable handling for model/API configuration
  - analyze_complexity() static method for task complexity detection
  - get_available_tools() static method for tool list
  - AVAILABLE_TOOLS constant shared between generators

- Update AutoGenerator to inherit from BaseAutoGenerator
  - Removes ~40 lines of duplicate code
  - Maintains all existing functionality

- Update WorkflowAutoGenerator to inherit from BaseAutoGenerator
  - Removes ~40 lines of duplicate code
  - Add dynamic agent count based on task complexity
  - Add tools list to workflow prompts
  - Improved prompt with 3-step analysis

- Add 8 new unit tests for new functionality
  - TestBaseAutoGenerator: complexity analysis, tools list
  - TestWorkflowDynamicAgentCount: prompt improvements

All 34 tests pass with no performance impact.
2025-12-19 10:23:29 +00:00
Mervin Praison 0a569e2b46 docs: Add AutoAgents workflow patterns examples and update README
- Add autoagents_workflow_patterns.py with all 6 workflow patterns
- Update auto_agents_example.py with new features and CLI examples
- Add orchestrator-workers and evaluator-optimizer patterns to README CLI section
- Update pattern options table with all 6 patterns
- Add documentation links to examples
2025-12-19 09:54:05 +00:00
Mervin Praison 054aea8f66 Add MCP Registry badge and ignore MCP tokens 2025-12-18 22:18:33 +00:00
Mervin Praison 34f1293cfc Release v2.3.42 2025-12-18 22:13:08 +00:00
Mervin Praison 7c1e32afc0 upate 2025-12-18 22:11:02 +00:00
Mervin Praison 1125c835ec Release v2.3.41 2025-12-18 22:09:58 +00:00
Mervin Praison 889d04a843 Release v2.3.40 2025-12-18 22:07:54 +00:00
Mervin Praison fba811c477 Release v2.3.39 2025-12-18 21:54:19 +00:00
Mervin Praison df687d86c3 Release v2.3.38 2025-12-18 21:26:34 +00:00
Mervin Praison afa37b0782 Release v2.3.37 2025-12-18 17:41:16 +00:00
Mervin Praison 43a15e6049 Release v2.3.36 2025-12-18 16:42:58 +00:00
Mervin Praison 8bf5a08246 Release v2.3.35 2025-12-18 16:28:02 +00:00
Mervin Praison aa81094ac3 Release v2.3.34 2025-12-18 14:55:33 +00:00
Mervin Praison c74fd7e925 Release v2.3.33 2025-12-18 14:41:36 +00:00
Mervin Praison 249acf7965 docs: Add performance benchmarks and auto-update functionality
Add performance comparison table to README showing PraisonAI as fastest framework for agent instantiation. Include benchmarks for LangGraph and CrewAI frameworks. Implement auto-save functionality to generate BENCHMARK_RESULTS.md and update README.md with latest benchmark results.
2025-12-18 13:30:06 +00:00
Mervin Praison ab68b2d296 Release v2.3.32 2025-12-18 13:17:32 +00:00
Mervin Praison abcc5b3b04 Release v2.3.31 2025-12-18 12:57:05 +00:00
Mervin Praison e584f56099 Release v2.3.30 2025-12-18 11:59:22 +00:00
Mervin Praison b6b01af066 Release v2.3.33 2025-12-18 11:19:29 +00:00
Mervin Praison 9aae3eff86 Release v2.3.32 2025-12-18 10:48:09 +00:00
Mervin Praison f90582c66b Release v2.3.31 2025-12-18 10:27:03 +00:00
Mervin Praison 67a8d65d8e Release v2.3.30 2025-12-18 09:07:42 +00:00
Mervin Praison d60c31a86d Release v2.3.29 2025-12-18 02:47:04 +00:00
Mervin Praison fcb7b2a0d0 fix(tests): Mark test_phase2_refactor tests as @pytest.mark.real
These tests make real API calls and should be excluded from CI.
2025-12-17 13:31:01 +00:00
Mervin Praison 81ad7db679 Release v2.3.28 2025-12-17 13:22:14 +00:00
Mervin Praison 0482c3ebb0 chore: Update dependencies and versioning for PraisonAI
- Bump PraisonAI version to 2.3.28 across Dockerfiles and deployment scripts.
- Update praisonaiagents version to 0.1.7 in pyproject.toml.
- Enhance README with a structured Table of Contents and improved section headers for better navigation.
- Remove outdated README.md from praisonai-agents and link to the main README.
2025-12-17 13:20:29 +00:00
Mervin Praison 3107458016 docs: Enhance README with emoji for section headers for better readability 2025-12-17 13:09:58 +00:00
Mervin Praison 44c8ceebae fix: Fix 15 test failures across multiple test files
Test fixes:
1. Import Errors (5 tests):
   - test_llm_self_reflection_direct.py: Define calculator locally
   - test_self_reflection_comprehensive.py: Define duckduckgo_search locally
   - test_self_reflection_fix_simple.py: Define calculator locally
   - test_self_reflection_fix_verification.py: Define calculator locally
   - test_fix_comprehensive.py: Convert to proper pytest with skipif

2. Workflow Assertion (1 test):
   - test_workflow_agents.py: Check error in results array

3. Ollama Type Assertion (1 test):
   - test_ollama_sequential_fix.py: Accept both str and int types

4. Ollama Missing Fixture (3 tests):
   - test_ollama_fix.py: Add proper pytest functions with skipif
   - test_ollama_async_fix.py: Add proper pytest functions with skipif

5. Memory Stale Data (2 tests):
   - test_file_memory.py: Use unique user_id per test

6. Planning Async Mocks (3 tests):
   - test_planning.py: Use get_response_async instead of achat

Results: 921 passed, 9 failed (down from 12), 16 skipped
2025-12-17 13:05:12 +00:00
Mervin Praison 20c0b02528 fix(ci): Fix Docker publish workflow - trigger on release, update actions 2025-12-17 13:00:51 +00:00
Mervin Praison cfc886b591 docs: Update examples to use canonical field names (agents, instructions) 2025-12-17 12:34:32 +00:00
Mervin Praison 77ac4b7a09 fix: Use _yaml_action from YAML parser when executing workflow steps
The action/description field from YAML was being stored on the agent but not
used when executing the workflow. Now the _normalize_single_step method
checks for _yaml_action and uses it as the prompt.

This fixes the issue where workflow steps were not using the action as the prompt.
2025-12-17 12:33:07 +00:00
Mervin Praison 5897cedc45 docs: Update README examples to use canonical field names 2025-12-17 12:29:47 +00:00
Mervin Praison a4d1079813 feat: Add unified field names with A-I-G-S mnemonic
- Add canonical field name suggestions to CLI validate command
- Document A-I-G-S mnemonic (Agents, Instructions, Goal, Steps)
- Add field name reference table to README
- Add comprehensive tests for field name normalization
- Accept both old and new names: roles/agents, backstory/instructions, description/action, topic/name

Implements 'Accept liberally, suggest canonically' principle
2025-12-17 12:24:11 +00:00
Mervin Praison 4eed985c4d Release v2.3.27 2025-12-17 12:17:02 +00:00
Mervin Praison 0658491072 docs: Update README with workflow features and feature parity
- Add YAML workflow file documentation
- Add workflow auto-generation documentation
- Add complete workflow.yaml reference with all features
- Add feature parity note between agents.yaml and workflow.yaml
- Update workflow CLI options table
2025-12-17 11:52:33 +00:00
Mervin Praison 9f82368b4c feat: Add workflow auto-generation (--auto for workflow.yaml)
- Add WorkflowAutoGenerator class in auto.py with lazy loading
- Support sequential, routing, parallel, loop patterns
- Add 'praisonai workflow auto' CLI command
- Add action_auto to WorkflowHandler
- Add _auto_generate_workflow to main.py
- Uses instructor for structured output generation
- Lazy loading ensures no performance impact when not used

Usage:
  praisonai workflow auto "Research AI trends" --pattern parallel
  praisonai workflow auto "Build a chatbot" --pattern routing
2025-12-17 11:50:02 +00:00
Mervin Praison c267cdda87 Release v2.3.26 2025-12-17 11:47:04 +00:00
Mervin Praison b88bb04090 feat: Add feature parity between agents.yaml and workflow.yaml
Workflow.yaml now supports all agents.yaml features:

Agent-level features:
- framework (praisonai, crewai, autogen)
- process (sequential, hierarchical, workflow)
- manager_llm for hierarchical process
- function_calling_llm
- max_rpm (rate limiting)
- max_execution_time (timeout)
- reflect_llm, min_reflect, max_reflect
- system_template, prompt_template, response_template
- backstory (alias for instructions)

Step-level features:
- expected_output (like agents.yaml tasks)
- context (task dependencies)
- output_json, output_pydantic (structured output)
- create_directory
- callback
- async_execution

Added 14 new TDD tests for feature parity verification.
All 41 YAML parser tests pass.
2025-12-17 11:40:38 +00:00
Mervin Praison 709a35fbdc refactor: Remove duplicate code
- Remove duplicate _convert_roles_to_agents from agents_generator.py
  (YAMLWorkflowParser already handles this conversion)
- Refactor _create_workflow_from_template in main.py to use
  WorkflowHandler.TEMPLATES instead of duplicating templates

This reduces code duplication and ensures single source of truth for:
1. Roles-to-agents conversion logic (in yaml_parser.py)
2. Workflow templates (in workflow.py)
2025-12-17 11:16:51 +00:00
Mervin Praison 8b792424b6 feat: Extend agents.yaml with workflow patterns (Option D)
- Add workflow detection in agents_generator.py (process: workflow)
- Route to YAMLWorkflowParser when workflow mode detected
- Support both 'roles' and 'agents' keys for backward compatibility
- Map 'backstory' to 'instructions' automatically
- Add _convert_roles_to_agents method in YAMLWorkflowParser
- Add _run_yaml_workflow method in AgentsGenerator
- Add 7 new tests for roles-to-agents conversion
- Add extended agents.yaml example with all workflow patterns
- Update README with extended agents.yaml documentation

This allows users to use advanced workflow patterns (route, parallel,
loop, repeat) directly in agents.yaml while maintaining full backward
compatibility with existing agents.yaml files.

Usage:
  praisonai agents.yaml  # Works for both standard and workflow mode
2025-12-17 11:11:46 +00:00
Mervin Praison ef2a8cd658 feat(cli): Add YAML workflow CLI commands
- Add WorkflowHandler for 'praisonai workflow' commands
- Add 'praisonai workflow run <file.yaml>' to run YAML workflows
- Add 'praisonai workflow validate <file.yaml>' to validate YAML workflows
- Add 'praisonai workflow template <name>' to create from templates
- Templates: simple, routing, parallel, loop, evaluator-optimizer
- Support --var key=value for passing variables
- Add unit tests for WorkflowHandler (8 tests)
- Update main.py to support YAML workflow execution
2025-12-17 10:52:23 +00:00
Mervin Praison d41d2dcba2 docs: Add YAML workflow loading documentation to README 2025-12-17 10:43:20 +00:00
Mervin Praison 3bc1786b49 feat(workflows): Add YAMLWorkflowParser for YAML-based workflow definitions
- Add YAMLWorkflowParser class to parse YAML workflow files
- Support all workflow patterns: route(), parallel(), loop(), repeat()
- Support agent definitions with planning, reasoning, tools
- Support workflow config: planning, reasoning, memory_config, verbose
- Support variables, callbacks, and guardrails
- Add load_yaml(), execute_yaml(), aexecute_yaml() to WorkflowManager
- Add comprehensive test suite (20 tests)
- Add example YAML workflow files:
  - simple_workflow.yaml
  - routing_workflow.yaml
  - parallel_workflow.yaml
  - loop_workflow.yaml
  - evaluator_optimizer_workflow.yaml
  - complete_workflow.yaml
- Add example_usage.py demonstrating YAML workflow usage
2025-12-17 10:42:44 +00:00
Mervin Praison 2eec3e2359 fix: exclude real tests from all pattern and fix session test assertions
- test_runner.py: Add '-m not real' to exclude tests requiring API keys when running 'all' pattern
- test_cli_features.py: Fix test_session_get_actions to match actual SessionHandler.get_actions() implementation (list, show, resume, delete instead of start)
2025-12-17 08:33:24 +00:00
Mervin Praison 6168401a69 feat(docs): Simplify workflow documentation to focus on agent-first approach
- Replace WorkflowManager examples with Workflow class
- Emphasize Agent objects as workflow steps
- Streamline pattern examples (route, parallel, loop, repeat) with agent-based usage
- Remove complex WorkflowStep configuration examples
- Consolidate workflow features into clearer, more concise examples
- Remove workflow comparison table and memory config examples
- Focus on core workflow patterns with practical agent examples
2025-12-17 08:30:10 +00:00
Mervin Praison 473fda653d Release v2.3.25 2025-12-17 08:17:15 +00:00
Mervin Praison 30f1a440b6 Release v2.3.24 2025-12-17 08:04:24 +00:00
Mervin Praison f991f37cfe Release v2.3.23 2025-12-17 00:41:48 +00:00
Mervin Praison a43b3ac72c Release v2.3.22 2025-12-17 00:25:14 +00:00
Mervin Praison 06f82249e1 Release v2.3.21 2025-12-17 00:05:40 +00:00
Mervin Praison d3aa78241a Release v2.3.20 2025-12-16 23:46:47 +00:00
Mervin Praison dfb77c39f9 Release v2.3.19 2025-12-16 23:26:53 +00:00
Mervin Praison 7e8f9b0574 Release v2.3.18 2025-12-16 23:18:36 +00:00
Mervin Praison 19bcdcd000 Release v2.3.16 2025-12-16 22:59:29 +00:00
Mervin Praison 8f5160f827 feat(workflows): Add branching, loops, callbacks, and per-step variables
- Add branching support with next_steps and branch_condition fields
- Add loop support with loop_over and loop_var for iterating over variables
- Add on_task_start and on_task_complete callbacks to PraisonAIAgents
- Add variables parameter for global variable substitution across tasks
- Add per-step agent creation from agent_config when no agent assigned
- Add task-level variable substitution in task descriptions
- Refactor workflow
2025-12-16 22:58:56 +00:00
Mervin Praison 3574a4d2c0 Release v2.3.15 2025-12-16 22:50:37 +00:00
Mervin Praison b552843fa9 docs: Update README workflow CLI with new features
- Add inline workflow examples (--workflow 'step1,step2')
- Add planning mode example (--planning)
- Add tools and save examples (--tools, --save)
- Update to use global flags instead of workflow-specific flags
2025-12-16 21:46:30 +00:00
Mervin Praison 0461a133df fix(workflow): Actually use planning mode when --planning is enabled
Before: --planning flag was stored but never used, agent.chat() was called
After: --planning flag creates agent with planning=True and calls agent.start()

The agent.start() method checks if planning is enabled and calls
_start_with_planning() which:
1. Creates a plan using PlanningAgent
2. Displays the generated plan
3. Executes each step with context passing
4. Compiles results into final output
2025-12-16 19:12:28 +00:00
Mervin Praison b33857de33 refactor(cli): Use global flags for workflow instead of workflow-specific flags
BREAKING CHANGE: Removed workflow-specific flags in favor of global flags

Before:
  praisonai workflow run 'name' --workflow-tools tavily --workflow-save --workflow-verbose

After:
  praisonai workflow run 'name' --tools tavily --save --verbose

This simplifies the CLI by reusing existing global flags:
- --llm (instead of --workflow-llm)
- --tools (instead of --workflow-tools)
- --planning (instead of --workflow-planning)
- --memory (instead of --workflow-memory)
- --save (instead of --workflow-save)
- --verbose (instead of --workflow-verbose)

Only --workflow-var remains workflow-specific for variable substitution.
2025-12-16 19:09:52 +00:00
Mervin Praison 433c643f6c feat(cli): Add inline workflow support without .md template
Usage: praisonai 'prompt' --workflow 'step1:action1,step2:action2'

Example:
  praisonai 'What is AI?' --workflow 'Research:Research the topic,Summarize:Write a summary' --workflow-save

Features:
- Parse inline workflow steps from --workflow flag
- Sequential execution with context passing
- All workflow options work: --workflow-tools, --workflow-save, etc.
- No .md template file required
2025-12-16 19:05:20 +00:00
Mervin Praison 214119a063 feat(cli): Add complete workflow CLI options
- Add --workflow-llm for LLM model selection
- Add --workflow-tools for tools (comma-separated)
- Add --workflow-planning for planning mode
- Add --workflow-memory for memory support
- Add --workflow-stream for streaming output
- Add --workflow-verbose for verbose output
- Add --workflow-save to save output to file
- Show final output after workflow completion
- Save all step outputs to markdown file
- Update help text with all options
2025-12-16 19:01:57 +00:00
Mervin Praison 989a9f6fc5 Release v2.3.14 2025-12-16 18:50:59 +00:00
Mervin Praison cf276a5640 feat(workflows): Add context passing, per-step agents, async execution
## New Features:
- Context passing between workflow steps with {{previous_output}} and {{step_name_output}}
- Per-step agent configuration with role, goal, backstory, and tools
- Per-step tools support
- Async execution with aexecute() method
- Planning mode at workflow level
- Enhanced markdown parser for agent/tools blocks

## WorkflowStep Enhancements:
- agent_config: Optional[Dict] - Per-step agent configuration
- tools: Optional[List] - Per-step tools
- context_from: Optional[List[str]] - Specific steps to include context from
- retain_full_context: bool - Include all previous outputs vs only last
- output_variable: Optional[str] - Custom variable name for step output

## Workflow Enhancements:
- default_llm: Optional[str] - Default LLM for all steps
- planning: bool - Enable planning mode
- planning_llm: Optional[str] - LLM for planning
- memory_config: Optional[Dict] - Memory configuration

## Execute Method Enhancements:
- default_agent parameter (executor now optional)
- default_llm, memory, planning, stream, verbose parameters

## Tests:
- 74 new tests covering all features
2025-12-16 18:49:43 +00:00
Mervin Praison b5134ffb2f Add --final-agent flag for post-processing output with specialized agent 2025-12-16 16:40:22 +00:00
Mervin Praison 5664036712 Release v2.3.13 2025-12-16 16:33:03 +00:00
Mervin Praison 6c2ca64cbe Remove unused --compile-results flag 2025-12-16 16:32:42 +00:00
Mervin Praison 08c742287c Fix: Pass max_tokens as dict config to Agent 2025-12-16 16:27:29 +00:00
Mervin Praison 4ee32b8eb2 Improve planning mode: compile all step results into comprehensive final report 2025-12-16 16:22:44 +00:00
Mervin Praison 35f07e5653 Add --max-tokens flag and improve planning mode output compilation 2025-12-16 16:22:37 +00:00
Mervin Praison 6481aec376 Add --tools support for all agents including planning mode 2025-12-16 16:14:39 +00:00
Mervin Praison 98c846ef78 Improve: Dynamic tool instructions from docstrings instead of hardcoded search 2025-12-16 16:01:30 +00:00
Mervin Praison 6e4a9faaf8 Fix: Instruct PromptExpanderAgent to use tools for context gathering 2025-12-16 15:59:46 +00:00
Mervin Praison 05d62db355 Reorganize README.md by moving Prompt Expansion, Web Search/Fetch, and MCP sections after CLI Features table, adding comprehensive programmatic usage examples and feature comparison tables for better documentation structure and clarity. 2025-12-16 15:52:36 +00:00
Mervin Praison 375c8c9826 Fix CLI docs links to use /docs/cli/ path 2025-12-16 15:41:42 +00:00
Mervin Praison c6977c8221 Add CLI Features table with docs links 2025-12-16 15:19:29 +00:00
Mervin Praison d407c83cf3 Add comprehensive CLI feature documentation to README.md, including Guardrail, Metrics, Image Processing, Telemetry, MCP, Fast Context, Knowledge, Session, Tools, Handoff, Auto Memory, Todo, Router, Flow Display, and Prompt Expansion with usage examples and command options for each feature. 2025-12-16 15:06:41 +00:00
Mervin Praison 214add68d9 Release v2.3.12 2025-12-16 15:03:23 +00:00
Mervin Praison 6d2cb9676d Update README.md to consolidate and enhance the Supported Providers section, adding new AI providers and their corresponding example links for improved documentation and user guidance. 2025-12-16 11:54:00 +00:00
Mervin Praison c519cb1379 Add supported providers section to README.md, listing various AI providers with example links for each, enhancing documentation and usability. 2025-12-16 11:52:19 +00:00
Mervin Praison 356dc4909a Update README.md to refine feature table, enhancing clarity by renaming 'Automated AI Agents Creation' to 'Single Agent' and reorganizing agent types for better categorization. 2025-12-16 11:25:42 +00:00
Mervin Praison dc278ad07b Enhance README.md with new agent types and advanced features, including Image Generation, Data Analyst, and Finance Agents, along with updates to existing feature descriptions and examples. 2025-12-16 11:22:23 +00:00
Mervin Praison 5cc53eb4bb Add advanced features section to README.md, detailing new capabilities including Deep Research Agents, Query Rewriter Agent, and various MCP enhancements. 2025-12-16 11:13:38 +00:00
Mervin Praison b72576d086 Refactor feature table in README.md for improved clarity and consistency, updating formatting and links for AI agent capabilities. 2025-12-16 11:11:04 +00:00
Mervin Praison 30314b1573 Update README.md to include detailed feature table with example code and documentation links for each AI agent capability. 2025-12-16 11:05:51 +00:00
Mervin Praison f721bd5e9a Add Fast Context feature to README highlights 2025-12-16 10:52:37 +00:00
Mervin Praison d00ea3e3c3 Release v2.3.11 2025-12-16 10:45:36 +00:00
Mervin Praison 67dbd1007a Release v2.3.10 2025-12-16 09:54:57 +00:00
Mervin Praison cf2a5a135f workflow 2025-12-16 09:23:49 +00:00
Mervin Praison bc23d3a104 Release v2.3.9 2025-12-16 08:18:09 +00:00
Mervin Praison bb4e1d8b9e Release v2.3.8 2025-12-16 07:55:55 +00:00
Mervin Praison 69740baa7c Release v2.3.7 2025-12-16 07:46:40 +00:00
Mervin Praison 5035978a29 fix: resolve Mintlify parsing errors
- Fix corrupted/duplicated database service in docker-compose.dev.yml
- Fix MDX parsing error in tests/README.md (<1s -> under 1s)
2025-12-15 23:11:04 +00:00
Mervin Praison 4ddb043324 Release v2.3.7 2025-12-15 22:49:12 +00:00
Mervin Praison 337014f4db planning example 2025-12-15 22:25:09 +00:00
Mervin Praison 35c371b25e update 2025-12-15 22:22:42 +00:00
Mervin Praison bba75d9fdd Release v2.3.6 2025-12-15 22:16:57 +00:00
Mervin Praison bf8cd488da feat: add planning tools and reasoning mode for research-enabled plan creation
- Add planning_tools and planning_reasoning parameters to PraisonAIAgents
- Add RESEARCH_TOOLS list for safe planning research tools (web_search, read_file, etc.)
- Add tools, reasoning, and max_reasoning_steps parameters to PlanningAgent
- Add _get_agent() method to PlanningAgent for tool-enabled planning with Agent.chat()
- Update plan creation to use Agent with tools when available, fallback to bare LLM
- Add Planning
2025-12-15 22:07:59 +00:00
Mervin Praison 28905db46d g 2025-12-15 21:27:32 +00:00
Mervin Praison 3e7aa44dfa docs: simplify feature descriptions by removing tool comparisons
- Remove references to Cursor, Windsurf, Claude Code, Gemini CLI, Codex CLI, and Cascade from feature descriptions
- Keep feature descriptions focused on PraisonAI's own capabilities
- Update Planning Mode, Agent Memory, Rules & Instructions, Auto-Generated Memories, Workflows, and Hooks sections
2025-12-15 21:26:04 +00:00
Mervin Praison 2f7a65ab92 update 2025-12-15 21:25:41 +00:00
Mervin Praison e6e2379b02 update 2025-12-15 21:25:29 +00:00
Mervin Praison f31f9a04aa update 2025-12-15 21:23:46 +00:00
Mervin Praison 5a8adf295e Release v2.3.5 2025-12-15 21:04:45 +00:00
Mervin Praison 8dc243fd4f feat: Add Planning Mode - plan before execution like Cursor, Windsurf, Claude Code
- Add planning module with PlanningAgent, Plan, PlanStep, TodoList, TodoItem
- Add PlanStorage for persisting plans to .praison/plans/
- Add ApprovalCallback for plan approval flow
- Add plan_mode to Agent for read-only tool filtering
- Add planning, planning_llm, auto_approve_plan params to PraisonAIAgents
- Add 71 comprehensive tests for planning mode
- Update READMEs with Planning Mode documentation
- Bump version to 0.0.181
2025-12-15 17:51:08 +00:00
Mervin Praison 548b4afb88 Release v2.3.4 2025-12-15 16:39:58 +00:00
Mervin Praison ffa938b3df docs: add advanced rules features and new memory capabilities
- Add local override files support (PRAISON.local.md, CLAUDE.local.md) with higher priority
- Add @import syntax for including other files in rules (like Claude Code)
- Add git root discovery for monorepo support with fallback to subprocess
- Add auto-discovery of modular rules directories (.claude/rules/, .windsurf/rules/, .cursor/rules/)
- Add character limits (12000) for context window management with truncation
- Add AutoMemory for
2025-12-15 16:39:04 +00:00
Mervin Praison 8a9beed264 docs: add advanced memory features and rules management system
- Add session save/resume, context compression, and checkpointing (inspired by Gemini CLI)
- Add RulesManager for auto-discovery of instruction files (CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .windsurfrules)
- Add slash commands for memory management (/memory show, /memory save, /memory compress, etc.)
- Add rules context injection into agent system prompts with activation modes (always, glob, manual, ai_decision)
- Add program
2025-12-15 16:17:25 +00:00
Mervin Praison daca5a1762 test: add multi-agent memory sharing and integration tests
- Add TestMultiAgentMemorySharing class with tests for shared/isolated memory between agents
- Test agents with same user_id share memory (short_term, long_term, entities)
- Test agents with different user_id have isolated memory
- Test memory context injection into system prompt
- Test memory display info shows correct counts
- Add TestMultiAgentMemoryIntegration class for LLM integration tests
- Test multi-agent memory sharing with OpenA
2025-12-15 15:00:16 +00:00
Mervin Praison b183ac5cbd Release v2.3.3 2025-12-15 14:55:30 +00:00
Mervin Praison 5f57e1d2f1 feat: add memory info display and improve memory integration with system prompts
- Add _display_memory_info() method to show memory stats in rich panel (long-term, short-term, entities, storage path)
- Disable system prompt caching when memory is enabled (dynamic context)
- Inject memory context into system prompt with "## Memory" section
- Display memory info on first chat when verbose=True
- Add integration tests for memory with OpenAI API (injection and persistence)
- Update README with zero
2025-12-15 14:52:09 +00:00
Mervin Praison 5114165944 feat: add zero-dependency file-based memory system for all agents
- Add FileMemory class with JSON-based persistent storage (no extra dependencies)
- Add _init_memory(), get_memory_context(), store_memory() methods to Agent class
- Support memory types: short_term, long_term, entity, episodic
- Add memory=True/False/"file"/"sqlite"/"chromadb"/"mem0" configuration options
- Add lazy import for Memory class to avoid dependency issues
- Update README with memory usage examples and provider comparison
2025-12-15 14:37:33 +00:00
Mervin Praison 389442ea04 feat: add Claude Memory Tool support for persistent cross-conversation memory
- Add claude_memory parameter to Agent and LLM classes
- Add ClaudeMemoryTool with file-based persistent memory in .praison/claude_memory/
- Add _supports_claude_memory(), _is_memory_tool_call(), _execute_memory_tool_call() methods
- Add automatic beta header injection for Anthropic models
- Add memory tool definition to completion params when enabled
- Add ClaudeMemoryTool to TOOL_MAPPINGS with class-level import
- Update
2025-12-15 13:48:35 +00:00
Mervin Praison 6d7cc9c3ba Release v2.3.2 2025-12-15 13:34:15 +00:00
Mervin Praison 690e4497cc feat: add --save support for direct prompts
- Save output to output/prompts/ folder with timestamped filename
- Works with all flags: --web-search, --expand-prompt, etc.

Usage:
  praisonai 'latest AI trends' --web-search --save
  praisonai 'write a poem' --expand-prompt --save
2025-12-15 13:33:28 +00:00
Mervin Praison 041f5f0b08 fix: add current date to PromptExpanderAgent for time-sensitive context
- Add datetime import and current_date to all expansion prompts
- Ensures expanded prompts reference the correct current date (e.g., December 15, 2025)
- Fixes issue where prompts defaulted to outdated year references
2025-12-15 13:26:13 +00:00
Mervin Praison bc0d9a6213 feat: add CLI flags for web-search, web-fetch, and prompt-caching
- Add --web-search flag for native web search (OpenAI, Gemini, Anthropic, xAI, Perplexity)
- Add --web-fetch flag for URL content retrieval (Anthropic only)
- Add --prompt-caching flag to reduce costs (OpenAI, Anthropic, Bedrock, Deepseek)
- Update README with CLI and programmatic usage examples

Usage:
  praisonai 'latest AI news' --web-search --llm openai/gpt-4o-search-preview
  praisonai 'summarize https://example.com' --web-fetch --llm anthropic/claude-sonnet-4-20250514
  praisonai 'analyze...' --prompt-caching --llm anthropic/claude-sonnet-4-20250514
2025-12-15 12:56:02 +00:00
Mervin Praison a4427fa135 Release v2.3.1 2025-12-15 12:45:22 +00:00
Mervin Praison 51e8c65c8c feat: refactor model capabilities to use LiteLLM helper functions
- Replace static model lists with LiteLLM's built-in capability checks (supports_response_schema, supports_function_calling, supports_parallel_function_calling, supports_web_search)
- Add supports_function_calling() and supports_parallel_function_calling() functions
- Keep static list for web_fetch (no LiteLLM helper available yet)
- Update documentation to reference LiteLLM as primary source
- Add Web Fetch feature to README features
2025-12-15 12:32:09 +00:00
Mervin Praison 285ed672c5 feat: add native web search and web fetch documentation to README
- Add Native Web Search section with supported providers (OpenAI, Anthropic, Gemini, xAI, Perplexity)
- Add Web Fetch section for Anthropic models with configuration options
- Add code examples for web_search and web_fetch parameters
- Document web_fetch options (max_uses, allowed_domains, citations)
2025-12-15 12:20:41 +00:00
Mervin Praison c03e51e337 feat: add native web fetch support for Anthropic Claude models
- Add web_fetch parameter to Agent and LLM classes
- Add model_capabilities.py with MODELS_SUPPORTING_WEB_FETCH list (Claude 3.5+, 4+)
- Add supports_web_fetch() function to check model capabilities
- Add web_fetch tool definition with configurable options (max_uses, allowed_domains, blocked_domains, citations, max_content_tokens)
- Add _model_supports_web_fetch() method to Agent class
- Add warning log for unsupported models when web_
2025-12-15 12:18:08 +00:00
Mervin Praison f3ba05f6aa feat: expand structured outputs support for OpenAI, Anthropic, and Gemini models
- Add comprehensive list of OpenAI models with structured outputs (gpt-4o-2024-08-06+, gpt-4.1+, gpt-5+, o-series)
- Add Anthropic Claude 4+ models with structured outputs support (Sonnet 4.5, Opus 4.1/4.5, Haiku 4.5)
- Add all Google Gemini models (2.5-pro, 2.5-flash, 2.0-flash, 1.5-pro/flash)
- Add auto-detection for newer model versions (gpt-4.1+, gpt-5+, o-series, Claude 4+, all Gemini)
- Add azure/ prefix support
2025-12-15 12:07:46 +00:00
Mervin Praison 9cea3edcd6 feat: add native web search support for OpenAI, Gemini, Anthropic, xAI, and Perplexity models
- Add web_search parameter to Agent and LLM classes
- Add model_capabilities.py with MODELS_SUPPORTING_WEB_SEARCH list
- Add supports_web_search() function to check model capabilities
- Add automatic DuckDuckGo fallback for unsupported models
- Add web_search_options to LiteLLM completion params
- Remove incompatible parameters (temperature, top_p, etc.) for web search models
- Update README with Native
2025-12-15 11:59:19 +00:00
Mervin Praison 02a3bd3597 chore: add uv cache clean before uv lock in release.py 2025-12-15 11:26:08 +00:00
Mervin Praison 128c77926d chore: add uv cache clean before uv lock in bump_and_release.py 2025-12-15 11:25:42 +00:00
Mervin Praison 3aa1b825e4 Release v2.3.0 2025-12-15 11:24:46 +00:00
Mervin Praison b4ee30d837 chore: bump praisonaiagents version to 0.0.170 2025-12-15 11:11:46 +00:00
Mervin Praison 825648aead docs: add PromptExpanderAgent to README 2025-12-15 11:11:04 +00:00
Mervin Praison 1532c31e72 feat: add PromptExpanderAgent for detailed prompt expansion
- Add PromptExpanderAgent class with expansion strategies (BASIC, DETAILED, STRUCTURED, CREATIVE, AUTO)
- Add ExpandStrategy enum and ExpandResult dataclass
- Add CLI flags --expand-prompt and --expand-tools
- Add 20 unit tests for PromptExpanderAgent
- Export from praisonaiagents package

Usage:
  praisonai 'write a movie script' --expand-prompt
  praisonai 'AI blog' --expand-prompt --expand-tools tools.py
2025-12-15 11:09:25 +00:00
Mervin Praison b313fefd86 fix: QueryRewriterAgent preserves task intent instead of converting to questions 2025-12-15 10:57:53 +00:00
Mervin Praison 435e1afb55 test: add OPENAI_API_KEY environment variable to comprehensive test workflow and verify its presence 2025-12-15 10:47:29 +00:00
Mervin Praison 4cb3c0565a test: add skipif decorator for OPENAI_API_KEY check in CrewAI environment test 2025-12-15 10:42:00 +00:00
Mervin Praison a7634b66dc Release v2.2.99 2025-12-15 10:36:34 +00:00
Mervin Praison 3f0eaccbcb Release v2.2.98 2025-12-15 10:28:42 +00:00
Mervin Praison 47713d933a test: convert test assertions to pytest format and add TaskOutput descriptions
- Replace return True/False with pytest assertions in test_context_agent.py
- Add pytest.mark.skip decorators for unimplemented ContextAgent methods
- Add missing description parameter to TaskOutput instances in test_validation_feedback.py
2025-12-15 10:25:23 +00:00
Mervin Praison c82bfccd1d docs: add custom tools documentation with decorator, BaseTool class, and pip installable package examples 2025-12-15 10:20:11 +00:00
Mervin Praison ef7d1264e2 feat: add plugin system with tool registry and BaseTool support for external tool packages 2025-12-15 10:10:06 +00:00
Mervin Praison 2799304270 Release v2.2.97 2025-12-15 08:25:56 +00:00
Mervin Praison 4a85c135a6 Release v2.2.96 2025-12-15 07:57:25 +00:00
Mervin Praison cdb42a3f08 feat: add custom tools support to research command with file and built-in tool loading 2025-12-15 07:33:52 +00:00
Mervin Praison c8378118e7 docs: add query rewrite flag to research command and bump version to 2.2.94 2025-12-13 12:49:38 +00:00
Mervin Praison 0213764057 feat: add Query Rewriter Agent with multiple rewrite strategies and bump version to 0.0.166 2025-12-13 12:44:21 +00:00
Mervin Praison 2220114809 feat: add --save flag to research command for markdown output and bump version to 2.2.93 2025-12-13 11:58:36 +00:00
Mervin Praison 9fe4dbc172 chore: bump version to 2.2.92 and update praisonaiagents dependency to 0.0.165 2025-12-13 02:19:22 +00:00
Mervin Praison 180503fcd5 feat: add default research instructions to DeepResearchAgent and bump version to 0.0.165 2025-12-13 02:18:42 +00:00
Mervin Praison 0d8f936b19 chore: bump version to 2.2.91 and update praisonaiagents dependency to 0.0.164 2025-12-13 02:09:12 +00:00
Mervin Praison 8b53ebf5e3 docs: add Deep Research CLI documentation and bump version to 2.2.90 2025-12-13 01:44:52 +00:00
Mervin Praison 504c5a9759 chore: bump version to 2.2.89 and update praisonaiagents dependency to 0.0.163 2025-12-13 01:17:52 +00:00
Mervin Praison 8fef42fc03 feat: add Deep Research Agent support with OpenAI and Gemini integration 2025-12-13 01:15:07 +00:00
Mervin Praison 2f18cc1ea2 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-12-13 01:13:29 +00:00
Mervin Praison ff7969cdbf docs: rewrite README from MCP SSE implementation to comprehensive PraisonAI Agents documentation 2025-12-13 01:13:28 +00:00
Mervin Praison 5fa84dc3eb Merge pull request #1084 from Dhivya-Bharathy/feature/agentic-rag
feat: Add Agentic RAG Example to Cookbooks
2025-11-03 14:14:46 +00:00
Mervin Praison 4bf8b980ed Merge pull request #1085 from Dhivya-Bharathy/feat/agentic-rag-tools
feat: Add Agentic RAG Tools Implementation
2025-11-03 14:14:24 +00:00
Mervin Praison 53e0fd19ab feat: add async run support and example scripts for multi-turn conversations 2025-08-30 11:54:59 +01:00
Dhivya-Bharathy 0cb6307d3c Add agentic_rag_gpt5 example with GPT-5 integration 2025-08-29 13:11:08 +05:30
Dhivya adce94410b Add files via upload 2025-08-29 13:01:08 +05:30
Dhivya-Bharathy 42aec561b1 Add agentic RAG Python implementation to tools 2025-08-28 14:09:09 +05:30
Dhivya acc805768d Update PraisonAI_RecipeAgent.ipynb 2025-08-28 13:00:50 +05:30
Dhivya-Bharathy 6d9fa167e3 Add agentic_rag example to cookbooks 2025-08-28 06:43:41 +00:00
Mervin Praison 9e178b70e6 chore: bump PraisonAI to v2.2.88 and update dependencies across Dockerfiles and project files 2025-08-08 19:24:43 +01:00
Mervin Praison ed406973cd refactor: optimise ChatOpenAI instantiation by using a dictionary for parameters and enforce temperature for gpt-5 models 2025-08-08 19:17:45 +01:00
Mervin Praison f91918f4f6 chore: bump PraisonAI to v2.2.87, PraisonAI Agents to v0.0.161 and increase default temperature to 1.0 2025-08-08 13:44:29 +01:00
Mervin Praison ee21df9a6a chore: bump praisonai to v2.2.86 and praisonaiagents to v0.0.160 2025-08-08 12:18:30 +01:00
Mervin Praison c9159337fa refactor: replace all instances of gpt-5-mini with gpt-5-nano across codebase 2025-08-08 12:17:18 +01:00
Mervin Praison 2258685c32 chore: bump PraisonAI to v2.2.85 and PraisonAI Agents to v0.0.159 2025-08-08 08:20:25 +01:00
Mervin Praison 7210788135 refactor: replace gpt-4o model references with gpt-5-mini across codebase 2025-08-08 08:17:23 +01:00
Mervin Praison 3f58e3b1ad chore: bump PraisonAI to v2.2.84 and PraisonAI Agents to v0.0.158 across all files 2025-08-08 07:54:22 +01:00
Mervin Praison 561c32ddd5 refactor: update model name from gpt-4o-mini to gpt-5-nano across all files 2025-08-08 07:52:37 +01:00
Mervin Praison 79d934eec4 feat: bump praisonai to 2.2.83 and add xml-toolcall-agent implementation 2025-08-05 07:44:47 +01:00
Mervin Praison 144c7edc4a Merge pull request #1079 from MervinPraison/claude/issue-1077-20250805-0109
feat: make XML tool call parsing dynamic and configurable
2025-08-05 02:31:08 +01:00
Mervin Praison 4425e2b743 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-08-05 02:28:00 +01:00
Mervin Praison eb8dfc02cd feat: optimize OpenAIClient with lazy loading and tool caching 2025-08-05 02:27:59 +01:00
github-actions[bot]andMervin Praison 27b6193b90 fix: improve XML tool call parsing robustness and type handling
- Fix type inconsistency in xml_tool_format handling (now supports True/''true''/''True'')
- Simplify _is_qwen_provider() by removing redundant logic
- Add proper XML parsing with ElementTree as primary method
- Improve regex fallback pattern for nested JSON in XML tags
- Add graceful error handling for malformed XML
- Import xml.etree.ElementTree at module level for better performance

Co-authored-by: Mervin Praison <[email protected]>
2025-08-05 01:26:48 +00:00
github-actions[bot]andMervin Praison b0aa9dfe58 feat: make XML tool call parsing dynamic and configurable
- Add xml_tool_format configuration parameter (auto/true/false)
- Replace static Qwen detection with dynamic _supports_xml_tool_format() method
- Add fallback XML detection for any model outputting <tool_call> tags
- Maintain backward compatibility with existing Qwen auto-detection
- Support manual XML format enabling for any model

Fixes #1077

Co-authored-by: Mervin Praison <[email protected]>
2025-08-05 01:13:22 +00:00
Mervin Praison 89d4f52327 Merge pull request #1075 from MervinPraison/claude/issue-1074-20250731-1148
fix: Fix RAG integration tests to respect lazy loading pattern
2025-07-31 13:05:47 +01:00
github-actions[bot]andMervin Praison da545f2e49 fix: Fix RAG integration tests to respect lazy loading pattern
- Fixed test_agent_with_knowledge_config and test_ollama_rag_integration
- Tests now properly check for lazy loading behavior instead of expecting immediate knowledge availability
- Verifies knowledge sources are stored and manually triggers processing before checking knowledge availability
- Preserves performance optimization of lazy loading while ensuring correct test behavior
- All RAG integration tests now pass (11/11)

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-31 11:53:01 +00:00
Mervin Praison e794992d7b feat: optimize LLM performance with caching and lazy loading 2025-07-31 12:39:37 +01:00
Mervin Praison a958162704 perf: optimize agent performance with lazy loading and caching strategies 2025-07-31 12:19:17 +01:00
Mervin Praison 3b47f7be7f chore: update MongoDB connection strings from localhost to remote cluster 2025-07-31 07:59:51 +01:00
Mervin Praison 0b8da8b4c4 Merge pull request #1072 from MervinPraison/claude/issue-1071-20250729-0039
fix: resolve MongoDB SearchIndexModel missing definition argument
2025-07-29 08:07:23 +01:00
github-actions[bot]andMervinPraison 092ea67732 fix: apply SearchIndexModel compatibility fix to memory.py and mongodb_tools.py
Extends the PyMongo 4.6+ compatibility fix from knowledge.py to other files
that also use create_search_index(). Applies the same backward-compatible
pattern using SearchIndexModel with graceful fallback for older PyMongo versions.

- memory.py: Fix _create_vector_search_indexes() method
- mongodb_tools.py: Fix create_vector_index() method

Maintains zero performance overhead and full backward compatibility.

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

Co-authored-by: MervinPraison <[email protected]>
2025-07-29 00:54:57 +00:00
github-actions[bot]andMervin Praison 5931ad00be fix: resolve MongoDB SearchIndexModel missing definition argument
- Import SearchIndexModel from pymongo.operations for PyMongo 4.6+ compatibility
- Use SearchIndexModel with definition parameter in _create_vector_index()
- Add backward compatibility fallback for older PyMongo versions
- Maintains zero performance overhead and preserves existing functionality

Fixes #1071

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-29 00:44:36 +00:00
Mervin Praison b7676cf6c3 update github actions 2025-07-29 01:38:33 +01:00
Mervin Praison 8ec4f5efa2 Merge pull request #1070 from MervinPraison/claude/issue-1069-20250728-2326
fix: resolve MongoDB vector search index creation error (missing embedding_model_name)
2025-07-29 01:33:58 +01:00
github-actions[bot]andMervin Praison f459c192d6 fix: initialize embedding model before MongoDB to resolve missing embedding_model_name attribute
Fixed initialization order in MongoDBMemory class where _create_vector_index()
was trying to access self.embedding_model_name before it was initialized.

- Moved _init_embedding_model() before _init_mongodb() in __init__
- Added explanatory comment for the dependency order
- Resolves AttributeError: ''MongoDBMemory'' object has no attribute ''embedding_model_name''
- Maintains full backward compatibility

Fixes #1069

Co-authored-by: Mervin Praison <[email protected]>
2025-07-28 23:31:01 +00:00
Mervin Praison 18b85aada0 chore: bump package versions and reorganize test files 2025-07-28 18:43:53 +01:00
Mervin Praison a3c77692fd Merge pull request #1068 from MervinPraison/claude/aiohttp-session-fix-v2
fix: comprehensive aiohttp session cleanup to resolve persistent warnings
2025-07-28 18:31:47 +01:00
github-actions[bot]andMervin Praison 4a06ee3626 perf: eliminate blocking timeout in close() method to restore zero-overhead cleanup
- Remove blocking future.result(timeout=2.0) that could block execution
- Restore non-blocking behavior with callback-based fallback cleanup
- Maintain reliability with async cleanup + force cleanup fallback
- Ensure zero performance impact on normal execution paths

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 20:05:52 +00:00
Mervin Praison 776e83100e Merge pull request #1067 from MervinPraison/claude/fix-token-tracking-metrics-20250726
fix: enable token tracking by passing metrics parameter from Agent to LLM
2025-07-26 21:00:43 +01:00
github-actions[bot]andMervin Praison f718d89ba4 test: add verification test for performance optimization
- Confirms zero method calls when metrics=False
- Verifies method still called when metrics=True
- Demonstrates performance benefit of optimization

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 19:40:17 +00:00
github-actions[bot]andMervin Praison 3469335d02 perf: optimize token tracking to eliminate overhead when metrics disabled
- Move metrics check to call sites instead of inside _track_token_usage()
- Eliminates function call overhead when metrics=False (default)
- Add performance test to verify zero overhead implementation
- Maintains full functionality when metrics=True

Performance impact:
- metrics=False (default): zero function call overhead
- metrics=True: unchanged functionality

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 19:39:46 +00:00
Mervin Praison 929a6e733d chore: bump praisonai to v2.2.79 and praisonaiagents to v0.0.153 across all files 2025-07-26 20:38:11 +01:00
github-actions[bot]andMervin Praison 6caa825706 fix: comprehensive aiohttp session cleanup in MCP HTTP client
- Add global client registry with weakref tracking for reliable cleanup
- Implement multi-layer cleanup strategy: immediate, force, finalizer, and exit
- Add atexit handler to ensure session cleanup on program termination
- Implement direct connector closing for emergency cleanup scenarios
- Maintain zero performance impact with non-blocking operations
- Fix persistent ''Unclosed client session'' warnings in praisonaiagents

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 19:38:03 +00:00
Mervin Praison 4baf6288ed Merge pull request #1066 from MervinPraison/claude/issue-1065-20250726-1904
fix: properly close aiohttp sessions in MCP HTTP stream transport
2025-07-26 20:33:27 +01:00
github-actions[bot]andMervin Praison 65a23df7a2 fix: enable token tracking by passing metrics parameter from Agent to LLM
Fixes the persistent issue where Agent(metrics=True) showed 0 tokens
despite the LLM instance access fix in PR #1064.

Root Cause:
- Agent.metrics=True was stored but never passed to LLM constructor
- LLM class had token tracking capability but no way to enable it
- Token collector received no data because LLM didn''t track tokens

Solution:
- Pass metrics=self.metrics to all 4 LLM constructor calls in agent.py
- Add self.metrics property to LLM class from extra_settings
- Only track tokens when self.metrics=True in _track_token_usage()

Verified:
- All LLM creation patterns (string, dict, provider/model) work
- Agent(metrics=True) properly enables LLM token tracking
- Zero performance impact when metrics=False (default)

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 19:25:50 +00:00
github-actions[bot]andMervin Praison ea0cb8b59a perf: optimize aiohttp session cleanup to eliminate execution overhead
- Remove flawed weakref finalizer that couldn''t run async code properly
- Make synchronous close() non-blocking to prevent 5-second delays
- Simplify __del__ methods to reduce garbage collection overhead
- Focus cleanup on proper async context manager usage
- Maintain backward compatibility while eliminating performance impact

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 19:23:09 +00:00
Mervin Praison d0d2e60618 feat: add API key validation and improved error handling for Tavily search integration 2025-07-26 20:21:34 +01:00
Mervin Praison 8eca3359cf Merge pull request #1064 from MervinPraison/claude/pr-1063-20250726-1818
fix: resolve zero token metrics by fixing agent LLM instance access
2025-07-26 20:17:56 +01:00
github-actions[bot]andMervin Praison 41272ddd24 fix: properly close aiohttp sessions in MCP HTTP stream transport
- Add weakref.finalize for reliable session cleanup during garbage collection
- Add explicit close() and aclose() methods for manual resource cleanup
- Add __del__ methods with proper error handling for both HTTPStreamTransport and HTTPStreamMCPClient
- Add double-close protection to prevent cleanup errors
- Preserve backward compatibility - no API changes, only additions

Fixes #1065

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 19:11:35 +00:00
Mervin Praison 47d8e54fa5 feat: add token tracking and langtrace integration modules with demo scripts 2025-07-26 20:09:18 +01:00
github-actions[bot]andMervin Praison 0d42787a86 perf: eliminate redundant getattr calls in token metrics collection
- Remove duplicate llm variable definitions in aexecute_task and execute_task
- Reuse existing llm variable instead of redefining with getattr calls
- Reduces function call overhead without changing functionality
- Addresses code duplication identified in PR review

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 19:08:58 +00:00
Mervin Praison 99a4b84e6a Merge pull request #1062 from MervinPraison/claude/issue-1059-20250726-1321
perf: optimize telemetry performance with thread pools and queue-based processing
2025-07-26 19:57:49 +01:00
github-actions[bot]andMervin Praison 1b70e295b4 feat: enable PostHog telemetry by default with actual event posting
- Change default behavior from performance_mode=True to performance_mode=False
- PostHog events are now actually posted by default instead of zero overhead mode
- Add PRAISONAI_PERFORMANCE_MODE=true environment variable for minimal overhead
- Create comprehensive PERFORMANCE_IMPACT.md documentation
- Performance impact: ~0.5-1.5ms per operation with async, non-blocking PostHog calls
- Memory overhead: +756KB one-time PostHog client initialization
- Maintains full backward compatibility with existing disable options

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 18:46:25 +00:00
github-actions[bot]andMervin Praison abc8d63b75 feat: enable PostHog telemetry by default with minimal performance impact
- Enable PostHog by default using performance_mode=True for zero overhead
- Add granular environment variable controls:
  - PRAISONAI_DISABLE_TELEMETRY=true (disable completely)
  - PRAISONAI_FULL_TELEMETRY=true (enable detailed tracking)
  - DO_NOT_TRACK=true (respects privacy standard)
- Maintain backward compatibility with existing disable flags
- Performance impact: <0.05ms overhead in default mode
- Preserves existing PRAISONAI_AUTO_INSTRUMENT behavior

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 18:29:22 +00:00
github-actions[bot]andMervin Praison 10e58e033a fix: resolve zero token metrics by fixing agent LLM instance access
- Fixed 4 locations in agents.py where token tracking failed due to incorrect attribute access
- Use getattr pattern to check both ''llm'' and ''llm_instance'' attributes on agents
- Ensures proper agent name attribution for token tracking
- Zero performance impact - maintains existing execution flow
- Fixes issue where agents.run() with metrics=True showed 0 tokens

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 18:28:30 +00:00
Mervin Praison e36feed53e Merge pull request #1061 from MervinPraison/claude/performance-monitoring-disabled-by-default-20250726-1324
feat: make performance monitoring disabled by default
2025-07-26 15:22:42 +01:00
github-actions[bot]andMervin Praison f01b3f4251 optimize: achieve true zero overhead when performance monitoring is disabled
Key optimizations implemented:
- Extract environment checking into shared cached function
- Make PostHog imports lazy to eliminate import overhead
- Optimize constructors for immediate exit when disabled
- Reduce code duplication from 4x to single implementation
- Add caching for environment variable checks

Performance improvements:
- Zero PostHog import overhead when disabled
- ~50% reduction in constructor overhead via fast-path
- Eliminates repeated environment variable lookups
- Reduces memory footprint when monitoring disabled

All telemetry modules now achieve true zero overhead when
performance monitoring is disabled by default.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 14:21:56 +00:00
github-actions[bot]andMervin Praison e2ca69327c fix: critical performance issues - ensure zero overhead for existing users
### Critical Fixes Applied:

1. **Remove Auto-Instrumentation Overhead** (__init__.py)
   - Auto-instrumentation now opt-in only via PRAISONAI_AUTO_INSTRUMENT=true
   - Prevents telemetry overhead being added to ALL existing users by default
   - Ensures zero performance impact for existing code paths

2. **Fix NameError Bug** (integration.py:22)
   - Move _performance_mode_enabled definition before function definitions
   - Fixes enable_performance_mode() and disable_performance_mode() functions
   - Resolves critical runtime error identified by Cursor bot

3. **Enhanced Error Handling** (integration.py:82-86, 123-127)
   - Replace silent exception handling with structured logging
   - Use logging.debug() for non-disruptive debugging support
   - Maintains application stability while enabling troubleshooting

4. **Implement Performance Context Manager** (integration.py:129-142)
   - Complete previously incomplete _performance_mode_context() function
   - Provides temporary performance mode switching capability
   - Removes dead code identified in review

5. **Configurable Resource Cleanup** (integration.py:600-610)
   - Make shutdown timeout configurable via PRAISONAI_TELEMETRY_SHUTDOWN_TIMEOUT
   - Enhanced error logging for resource cleanup issues
   - Improves reliability across different deployment environments

### Performance Guarantee:
✅ Zero overhead for existing users (no auto-instrumentation)
✅ Telemetry is now truly opt-in only
✅ All existing APIs work identically
✅ No breaking changes to function signatures

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 14:20:17 +00:00
Mervin Praison cc8994f19c Merge pull request #1063 from MervinPraison/claude/issue-1060-20250726-1321
fix: add run() method alias to PraisonAIAgents for consistent API
2025-07-26 15:18:43 +01:00
github-actions[bot]andMervin Praison 89277d14c4 clean: remove test files from repository
🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 14:17:29 +00:00
github-actions[bot]andMervin Praison 9513173837 fix: remove redundant run() alias to prevent code duplication
- Remove line 1535 that created redundant run = start alias
- Keep proper run() method implementation with correct parameter handling
- Maintain full backward compatibility
- Zero performance overhead

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 14:17:18 +00:00
Mervin Praison 5b83af82db Merge branch 'main' into claude/issue-1059-20250726-1321 2025-07-26 15:12:51 +01:00
github-actions[bot]andMervin Praison 0539c337ab perf: optimize telemetry performance with thread pools and queue-based processing
- Replace per-call thread creation with shared ThreadPoolExecutor (2 workers)
- Implement queue-based batch processing for telemetry events
- Add performance_mode parameter for zero-overhead operation in critical scenarios
- Add non-blocking event queuing with overflow protection (drops events vs blocking)
- Use async PostHog mode by default in batch processing
- Add resource cleanup functions for proper shutdown
- Maintain 100% backward compatibility with existing APIs

Performance benefits:
- ~90% reduction in thread creation overhead under load
- Eliminates blocking on network calls during normal operation
- Memory-bounded telemetry storage prevents resource leaks
- Graceful degradation under high load
- Zero impact when performance_mode=True

Fixes #1059

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 13:29:41 +00:00
github-actions[bot]andMervin Praison c6977cf541 feat: make performance monitoring disabled by default
- NEW BEHAVIOR: Performance monitoring now DISABLED BY DEFAULT
- Requires explicit opt-in via PRAISONAI_PERFORMANCE_ENABLED=true
- Maintains backward compatibility with legacy disable flags
- Zero performance overhead when disabled (unchanged)

Environment Variables:
- PRAISONAI_PERFORMANCE_ENABLED=true (new: enables monitoring)
- PRAISONAI_TELEMETRY_ENABLED=true (new: enables telemetry)
- Legacy disable flags still work for backward compatibility

Files updated:
- telemetry.py: Modified _is_monitoring_disabled() logic
- performance_monitor.py: Updated fallback logic
- performance_utils.py: Updated fallback logic
- integration.py: Updated fallback logic
- README.md: Updated documentation

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 13:27:33 +00:00
github-actions[bot]andMervin Praison b0e9eec33b fix: add run() method alias to PraisonAIAgents for consistent API
- Add run() method to PraisonAIAgents that delegates to start()
- Ensures token metrics display works when users call agents.run()
- Provides API consistency with Agent class which already has run() alias
- Fixes issue where metrics=True wasn''t showing token usage summary
- Backward compatible change, no existing functionality affected

Fixes #1060

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 13:27:20 +00:00
Mervin Praison 2cb61ce529 Merge pull request #1058 from MervinPraison/claude/issue-1057-20250726-1242
fix: reduce monitoring overhead with performance optimizations
2025-07-26 14:22:17 +01:00
github-actions[bot]andMervin Praison 4055c9c983 fix: resolve critical performance monitoring bugs and ensure zero overhead
Critical fixes:
- Fixed ThreadPoolExecutor.shutdown() invalid timeout parameter (telemetry.py:396)
- Added consistent disable checks in get_function_performance() and get_api_call_performance()
- Fixed thread safety issue by creating copy instead of modifying input data
- Extracted environment variable checking to shared utility function
- Ensured true zero overhead when PRAISONAI_PERFORMANCE_DISABLED=true

Performance guarantees:
✅ Zero overhead when monitoring disabled - decorators return original functions
✅ No impact on existing feature execution speed - early exits prevent processing
✅ Backward compatibility maintained - all existing APIs preserved
✅ Thread safety improved - no input parameter modification

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 13:20:37 +00:00
github-actions[bot]andClaude 376b4d95f1 feat: reduce monitoring overhead with performance optimizations
- Add PRAISONAI_PERFORMANCE_DISABLED environment variable to disable all performance monitoring overhead
- Make expensive flow analysis opt-in only via PRAISONAI_FLOW_ANALYSIS_ENABLED
- Add export_metrics_for_external_apm() method for DataDog/New Relic integration
- Function decorators return original functions when disabled (zero overhead)
- Maintain full backward compatibility with existing monitoring features

Addresses performance overhead issues by allowing users to completely disable
monitoring when not needed, while providing lightweight external APM export
for production monitoring without expensive flow analysis operations.

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

Co-Authored-By: Claude <[email protected]>
2025-07-26 12:54:06 +00:00
github-actions[bot]andClaude 2ae47e4208 optimize: reduce telemetry monitoring overhead for production use
Address performance bottlenecks identified in issue #1057:

1. **Early exit optimizations**: Add environment variable checks at the start of
   instrumentation functions to avoid all overhead when telemetry is disabled

2. **Thread pool optimization**: Replace individual thread creation with a
   reusable ThreadPoolExecutor to reduce thread creation overhead (5-10ms per call)

3. **Flow analysis optimization**: Limit analysis to 1000 most recent events
   instead of processing up to 10,000 events to avoid O(n²) complexity

4. **Performance monitoring controls**: Add PRAISONAI_PERFORMANCE_DISABLED
   environment variable to disable performance monitoring separately from telemetry

5. **No-op optimizations**: Make monitoring decorators and context managers
   return unmodified functions/no-op when disabled to eliminate runtime overhead

Key changes:
- Zero instrumentation overhead when DO_NOT_TRACK=true or PRAISONAI_TELEMETRY_DISABLED=true
- Thread pool reuse reduces background thread creation by 90%
- Flow analysis processes max 1000 events instead of unlimited
- Maintains full backward compatibility
- No impact on existing functionality when telemetry is enabled

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

Co-Authored-By: Claude <[email protected]>
2025-07-26 12:50:10 +00:00
Mervin Praison 6b2814eb26 Merge pull request #1056 from MervinPraison/claude/simplified-metrics-20250726
feat: Simplify token metrics to Agent(metrics=True)
2025-07-26 13:19:15 +01:00
github-actions[bot]andMervin Praison 852765412a fix: clean up debug files and improve exception handling
- Remove temporary debugging scripts (check_*.py, test_*.py)
- Improve exception handling in metrics display with specific error types
- Fix unused variable in cost estimation example
- Maintain zero performance overhead for existing features

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 12:15:19 +00:00
github-actions[bot]andMervin Praison b4db6421f7 feat: Simplify token metrics to Agent(metrics=True)
- Add metrics parameter to Agent class with auto-display capability
- Fix missing run() method in PraisonAIAgents (add alias to start)
- Auto-display token usage when any agent has metrics=True
- Simplify all examples to use single parameter approach
- Maintain zero performance impact with O(1) operations
- Keep backward compatibility with existing methods

BREAKING: Massively simplified API - just Agent(metrics=True)!

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 12:00:54 +00:00
Mervin Praison 22ecf6963f Merge pull request #1055 from MervinPraison/claude/issue-1054-20250725-1714
feat: Add comprehensive token metrics tracking for PraisonAI agents
2025-07-26 08:32:11 +01:00
github-actions[bot]andMervin Praison 5cea1f5702 feat: add comprehensive token metrics usage examples
Add 5 detailed examples demonstrating token tracking features:
- Basic token tracking for simple workflows
- Session metrics across multiple agents
- Cost estimation and budget management
- Telemetry integration for enterprise monitoring
- Advanced agent integration with real-time analysis

Each example includes documentation and best practices
for production usage. Examples are self-contained and
demonstrate zero-performance-impact implementation.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 07:24:17 +00:00
Mervin Praison 36d7a2b489 feat: add performance impact check requirement to GitHub workflow comments 2025-07-26 08:17:46 +01:00
github-actions[bot]andMervin Praison 2c9ae32e13 fix: add missing token tracking call and provider metadata
- Add missing token tracking call after reasoning response (line 957)
- Add provider metadata to token tracking as per original requirements
- Ensures all LLM completion calls are properly tracked

Co-authored-by: Mervin Praison <[email protected]>
2025-07-26 06:38:39 +00:00
github-actions[bot]andMervin Praison d2d7fab0e0 feat: add comprehensive token metrics tracking system
- Add TokenMetrics dataclass for tracking individual interactions
- Add SessionTokenMetrics for aggregated session data
- Add TokenCollector for thread-safe global collection
- Add TokenTelemetryBridge for existing telemetry integration
- Integrate token tracking into LLM responses
- Add token_metrics field to TaskOutput class
- Add agent name setting for proper token attribution
- Add token usage methods to PraisonAIAgents class
- Maintain backward compatibility with graceful fallbacks
- Keep core application performance unchanged
- Support all token types: input/output/cached/reasoning/audio

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-25 17:23:07 +00:00
Mervin Praison f4ef434610 fix: reset interaction_displayed flag to ensure final summary is shown in LLM responses 2025-07-25 18:09:39 +01:00
Mervin Praison d63b437eca feat: add workflow visualization with FlowDisplay and bump version to 2.2.77 2025-07-25 12:05:41 +01:00
Mervin Praison 04aac1c2d5 fix: skip display output for empty Gemini responses and bump version to 0.0.150 2025-07-25 09:51:56 +01:00
Mervin Praison eca66f9213 feat: bump praisonai to v2.2.76 and praisonaiagents to v0.0.149 with callback refactor 2025-07-25 09:41:04 +01:00
Mervin PraisonandClaude f83f3eae0b fix: ensure consistent display output between OpenAI and Gemini models
- Added execute_sync_callback call in custom LLM path to match OpenAI behavior
- Fixed issue where Gemini/custom LLM responses were not triggering callbacks
- Prevents duplicate display by relying on LLM class to handle verbose display
- Ensures both paths execute callbacks for consistent behavior

The issue was that custom LLM providers (like Gemini) were not calling
_execute_callback_and_display after guardrail validation, while OpenAI
path was. This caused missing Task/Response display boxes for Gemini.

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

Co-Authored-By: Claude <[email protected]>
2025-07-25 08:31:38 +01:00
Mervin Praison 68dd9fb5f1 feat: enable httpx debug logging when LOGLEVEL=debug and remove Ollama handling docs 2025-07-24 10:00:41 +01:00
Mervin Praison e0531cedf7 feat: optimize LLM tool handling and response generation for Ollama and Gemini models 2025-07-24 01:53:54 +01:00
Mervin Praison 197e98d3ff refactor: consolidate warning and logging configuration with minimal overhead 2025-07-24 01:06:10 +01:00
Mervin Praison 3b7fd3688c update 2025-07-24 00:59:36 +01:00
Mervin Praison dd7bfa39f4 refactor: centralize logging configuration in new _logging.py module 2025-07-24 00:27:12 +01:00
Mervin Praison fca801c3f7 chore: remove test files for display generating and streaming fixes 2025-07-23 23:57:08 +01:00
Mervin Praison 33c81861c0 feat: implement comprehensive agent monitoring system with streaming enhancements 2025-07-23 23:56:19 +01:00
Mervin Praison b49b6d567f Merge pull request #1050 from MervinPraison/claude/pr-1049-20250723-0902
fix: Remove display_generating when stream=false to prevent streaming-like behavior
2025-07-23 10:45:49 +01:00
github-actions[bot]andMervin Praison 8c1677556c fix: Complete display_generating fix for consistency across all code paths
- Fix inconsistency in custom LLM path (line 1116) to match OpenAI path behavior
- Update test script to verify all three fix locations (2 OpenAI + 1 custom LLM)
- Ensure no streaming-like behavior when stream=False regardless of LLM provider
- Maintain backward compatibility and existing functionality

Co-authored-by: Mervin Praison <[email protected]>
2025-07-23 09:34:50 +00:00
github-actions[bot]andMervin Praison a656ea2bca fix: Remove display_generating when stream=false to prevent streaming-like behavior
When stream=false but verbose=true, the system was incorrectly showing
streaming-like visual behavior (Generating... X.Xs) due to display_generating
being used even when users explicitly set stream=false.

Fixed by changing display_fn from display_generating to None when stream=false
in both locations (lines 1073 and 1172) in agent.py.

This ensures true non-streaming behavior when stream=false is set, regardless
of verbose setting.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-23 09:07:13 +00:00
Mervin Praison 02846b0efd Merge pull request #1049 from MervinPraison/claude/pr-1048-20250723-0615
Fix: Add display_generating support for OpenAI non-streaming mode
2025-07-23 07:30:21 +01:00
github-actions[bot]andMervin Praison 8d463e6897 Improve display_generating fix for OpenAI non-streaming mode
- Add missing display_fn support to async version (achat_completion_with_tools)
- Add proper error handling with try-catch around Live context manager
- Add safer content access with length checks for choices array
- Add console cleanup (console.print()) consistent with streaming mode
- Maintain backward compatibility with fallback to regular completion

Co-authored-by: Mervin Praison <[email protected]>
2025-07-23 06:23:50 +00:00
github-actions[bot]andClaude b47021d98f Fix: Add display_generating support for OpenAI non-streaming mode
🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
2025-07-23 06:19:44 +00:00
Mervin Praison ab4561d7a4 Merge pull request #1048 from MervinPraison/claude/pr-1046-20250722-2152
PR #1046: Changes from Claude
2025-07-22 23:19:32 +01:00
Mervin Praison 81af51f3e7 Merge pull request #1047 from MervinPraison/claude/pr-1045-20250722-2138
fix: resolve display_generating issue by ensuring stream parameter is correctly passed
2025-07-22 23:02:46 +01:00
github-actions[bot]andMervin Praison 550d9c30d4 fix: restore display_generating visibility in verbose streaming mode
- Modified streaming logic to show display_generating during verbose streaming
- Preserves non-verbose streaming behavior (no display_generating)
- Fixes user-reported issue where display_generating disappeared in basic-agents.py
- Maintains full backward compatibility with existing code
- Addresses display functionality regression from streaming fallback changes

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 21:59:47 +00:00
Mervin Praison 39a8942054 Merge pull request #1046 from MervinPraison/claude/fix-streaming-fallback-logic-20250722
fix: implement proper streaming fallback logic for JSON parsing errors
2025-07-22 22:46:55 +01:00
github-actions[bot]andMervin Praison 6ecb6e4887 fix: prevent duplicate API calls in streaming fallback logic
- Added fallback_completed flag to track successful fallback execution
- Modified non-streaming condition to only execute when fallback hasn''t completed
- Prevents duplicate litellm.completion calls that waste API quota and increase latency
- Addresses critical bug identified by Cursor bot review

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 21:43:35 +00:00
github-actions[bot]andMervin Praison d64c1381ed fix: resolve display_generating issue by ensuring stream parameter is correctly passed from start() to chat() method
- Fix stream parameter not being explicitly passed in start() method
- Ensures display_generating shows when agent.start() is called with default settings
- Agent defaults: verbose=True, stream=False should show ''Generating...'' message
- Resolves issue where chat() method default stream=True overrode agent''s stream=False setting
- Tested logic flow: (not stream and verbose) now correctly evaluates to True

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 21:43:19 +00:00
Mervin Praison 8e6bc3845b Merge pull request #1045 from MervinPraison/claude/pr-1042-20250722-2118
fix: correct display_generating logic to only show when stream=False AND verbose=True
2025-07-22 22:36:55 +01:00
github-actions[bot]andMervin Praison d2b2ad525e fix: implement proper streaming fallback logic for JSON parsing errors
- Fixed critical control flow bug where streaming errors set use_streaming=False
  but continued executing in streaming block instead of triggering fallback
- When recoverable streaming error occurs, immediately perform actual non-streaming
  API call instead of creating mock response with partial/empty data
- Added proper callback handling for both verbose/non-verbose modes
- Enhanced graceful degradation if both streaming and non-streaming fail
- Updated test to use agent.llm_model instead of agent.llm property

Fixes: Issue #1043 streaming JSON parsing errors causing "Response: None"

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

Co-Authored-By: Mervin Praison <[email protected]>
2025-07-22 21:35:49 +00:00
github-actions[bot]andMervin Praison 60508ba410 fix: correct hardcoded True to stream variable in display_generating logic
Fixed critical bug where (not True and self.verbose) was always False,
preventing display_generating from ever being called in one code path.
Changed to (not stream and self.verbose) to match intended logic.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 21:30:16 +00:00
Mervin Praison a2951184d7 Merge pull request #1044 from MervinPraison/claude/issue-1043-20250722-2015
fix: enhance LiteLLM streaming error handling for JSON parsing errors (Issue #1043)
2025-07-22 22:25:13 +01:00
github-actions[bot]andMervin Praison 4e26bbecfb fix: correct display_generating logic to only show when stream=False AND verbose=True
- Change logic from (stream or verbose) to (not stream and verbose)
- Ensure display_generating only appears for non-streaming verbose mode
- Remove streaming display blocks since no display needed when streaming
- Update test files to reflect correct expected behavior

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 21:24:01 +00:00
github-actions[bot]andMervin Praison f77583c64f fix: resolve critical fallback logic and display_generating behavior
- Fix broken streaming fallback: now properly calls non-streaming LLM instead of creating mock responses
- Update display_generating behavior per requirements:
  * stream=true (any verbose): no display_generating
  * stream=false + verbose=true: show display_generating
  * stream=false + verbose=false: no display_generating
- Clean up unnecessary f-strings without placeholders
- Maintain backward compatibility and existing functionality

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 21:23:42 +00:00
github-actions[bot]andMervin Praison 6071850401 fix: enhance LiteLLM streaming error handling for JSON parsing errors
- Add iterator-level error handling in get_response_stream method
- Wrap for chunk in stream_iterator loops with JSON parsing error recovery
- Add error handling to both verbose/non-verbose streaming in get_response
- Leverage existing _is_streaming_error_recoverable() logic for consistency
- Maintain automatic fallback to non-streaming mode on repeated errors
- Preserve backward compatibility with no breaking API changes
- Add comprehensive test script for Issue #1043 scenario

Fixes #1043: Error parsing chunk - JSON parsing error in Gemini streaming

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 20:23:51 +00:00
Mervin Praison 6ce4363e92 Merge pull request #1042 from MervinPraison/claude/issue-981-20250722-1946
fix: ensure display_generating is called when verbose=True regardless of streaming mode
2025-07-22 21:13:02 +01:00
github-actions[bot]andMervin Praison 3622838f9f fix: complete display_generating fix for both OpenAI and custom LLM paths
- Extend fix to custom LLM providers (Anthropic, Groq, local models)
- Add Live display wrapper for non-streaming custom LLM path
- Ensure consistent behavior: display when (stream OR verbose)
- Maintain backward compatibility for all existing functionality
- Add comprehensive test coverage for both agent paths

Fixes #981 completely for all LLM provider types

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 20:07:35 +00:00
github-actions[bot]andMervin Praison 60f0cb308a fix: ensure display_generating is called when verbose=True regardless of streaming mode
- Fix issue where display_generating was only called during streaming
- Now display_generating is called when either stream=True OR verbose=True
- Resolves user issue where verbose=True with default stream=False wasn''t showing ''Generating...'' display
- Add logic tests to verify the fix

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 19:49:49 +00:00
Mervin Praison a3afd4f7fd Merge pull request #1041 from MervinPraison/claude/pr-1039-20250722-1308
PR #1039: Logging
2025-07-22 20:42:51 +01:00
github-actions[bot]andMervin Praison 7118b9a47b perf: optimize litellm logger suppression using hierarchical logging
Remove redundant loops that iterate over all loggers to suppress litellm
submodules. Python''s hierarchical logging automatically propagates the
CRITICAL level from parent ''litellm'' logger to all child loggers
(litellm.utils, litellm.proxy, etc.).

Changes:
- Remove 3 redundant loops in __init__.py and llm/__init__.py
- Remove explicit configuration of child loggers (litellm.utils, etc.)
- Maintain litellm_logging as separate hierarchy (not a child of litellm)
- Add explanatory comments about hierarchical logging inheritance
- Preserve backward compatibility and DEBUG mode behavior

Performance: Eliminates unnecessary iteration over all existing loggers
while maintaining identical logging suppression behavior.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 19:35:02 +00:00
Mervin Praison 3fa0173bf8 refactor: reorganize test files and add MongoDB memory/knowledge integrations 2025-07-22 14:44:51 +01:00
Mervin Praison b9ea6accf9 Merge pull request #1040 from MervinPraison/claude/pr-1038-20250722-1255
PR #1038: Monitoring examples
2025-07-22 14:43:58 +01:00
github-actions[bot]andClaude 80d2491a59 fix: resolve critical issues in monitoring examples
- Fix ZeroDivisionError in 02_multi_agent_workflow_monitoring.py by adding zero-check for call counts
- Improve async handling in 04_async_agent_monitoring.py with better simulation and timing
- Fix UnboundLocalError in 05_error_handling_monitoring.py by correcting variable references
- Add zero-check protection in 07_hierarchical_agents_monitoring.py to prevent division errors
- Remove unused json import from 08_custom_tools_monitoring.py
- Remove unused timedelta import from 09_streaming_monitoring.py
- Fix UnboundLocalError in 10_comprehensive_dashboard.py by initializing avg_function_time variable

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

Co-Authored-By: Claude <[email protected]>
2025-07-22 13:33:04 +00:00
github-actions[bot]andMervin Praison 52f23b87c9 fix: Remove logger disabling to allow DEBUG mode re-enabling
- Remove `disabled = True` from logger configuration to prevent permanent disabling
- Keep CRITICAL level suppression but allow dynamic re-enabling in DEBUG mode
- Maintain backward compatibility while fixing DEBUG mode functionality
- Add comprehensive test to verify dynamic mode switching works correctly
- Addresses reviewer concerns about permanent logger disabling

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 13:24:56 +00:00
github-actions[bot]andMervin Praison 70a3d2df34 feat: Add 10 comprehensive performance monitoring examples
- Create examples/python/monitoring/ directory with 10 diverse examples
- Cover basic monitoring, multi-agent workflows, tools, async, errors, memory, hierarchical, custom tools, streaming, and comprehensive dashboard
- Each example demonstrates different aspects of the performance monitoring system
- Include detailed README with usage patterns and best practices
- Show practical integration of @monitor_function and track_api_call
- Demonstrate performance analytics, reporting, and optimization insights

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 13:04:17 +00:00
Mervin Praison d3c08660f5 Merge pull request #1039 from MervinPraison/claude/fix-litellm-warnings-20250722-1151
Fix: Comprehensive LiteLLM deprecation warning suppression
2025-07-22 13:58:24 +01:00
github-actions[bot]andMervin Praison 4e09b7c878 fix: clean up warning suppression implementation
- Fix LLM module _should_suppress_warnings() consistency by adding missing test detection
- Remove redundant warning filters in main module (lines 74-76 duplicated lines 63-65)
- Remove duplicate sys import in main module
- All tests now pass: DEBUG mode properly respects LOGLEVEL=DEBUG
- Maintains backward compatibility and existing functionality

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 12:54:07 +00:00
Mervin Praison 6bc6ff79dd Merge pull request #1038 from MervinPraison/claude/issue-1035-20250722-1143
feat: Add comprehensive performance monitoring system
2025-07-22 13:44:08 +01:00
github-actions[bot]andMervin Praison ab78189601 fix: implement DEBUG mode support for warning suppression (issue #1033)
- Implement missing DEBUG mode functionality as specified in PR description
- Add _should_suppress_warnings() function to respect LOGLEVEL=DEBUG
- Fix overly broad global warning suppression (now module-specific)
- Remove unsafe pydantic.warnings.warn monkey-patching
- Improve test detection with pytest module checks
- Add comprehensive test scripts for validation

Key improvements:
• Warnings are suppressed in normal mode (LOGLEVEL=INFO)
• Warnings are shown when LOGLEVEL=DEBUG (as per PR requirement)
• More targeted warning suppression (module-specific vs global)
• Safer pydantic warning handling with specific filters
• Better backward compatibility and security

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

Co-Authored-By: Mervin Praison <[email protected]>
2025-07-22 12:35:18 +00:00
github-actions[bot]andMervin Praison 54c29a6ffe fix: address code quality issues in performance monitoring
- Remove unused imports (inspect, timedelta, time, deque, etc.)
- Fix division by zero error in performance trend analysis
- Improve call chain building algorithm for better efficiency and accuracy
- Replace bare except clauses with specific Exception handling
- Use collections.deque with maxlen instead of manual truncation
- Remove unused variables and loop variables
- Fix f-strings without placeholders
- Replace magic numbers with named constants
- Improve error handling specificity

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 12:33:33 +00:00
Mervin Praison afb32705dc Merge pull request #1037 from MervinPraison/claude/pr-1030-20250722-1138
fix: correct tool call argument parsing in streaming mode
2025-07-22 13:23:45 +01:00
github-actions[bot]andMervin Praison 9f9a373c31 feat: Add comprehensive performance monitoring system for function and API call analysis
This implementation addresses all requirements from Issue #1035:

Features Added:
- PerformanceMonitor class for function performance evaluation with detailed statistics
- FunctionFlowAnalyzer for execution flow visualization and bottleneck identification
- API call tracking and performance comparison (fast vs slow calls)
- Real-time performance reporting and comprehensive analytics
- CLI interface for easy command-line access to performance data
- Full backward compatibility with existing telemetry system

Key Capabilities:
1. Function Performance Evaluation: Decorators and context managers for automatic timing
2. Function Flow Analysis: Visual execution flow with bottleneck detection
3. Execution Speed Analysis: Min/max/average timing with trend analysis
4. API Call Performance: Success rates, response times, reliability metrics
5. API Call Visibility: Complete tracking and history of all API interactions

Files Modified:
- Enhanced telemetry/__init__.py to expose new performance tools
- Added performance_monitor.py with core monitoring functionality
- Added performance_utils.py with advanced analysis and visualization
- Added performance_cli.py for command-line interface
- Added comprehensive demo and examples

Integration:
- Seamless integration with existing PraisonAI telemetry infrastructure
- Zero breaking changes to existing functionality
- Optional import structure for graceful degradation
- Thread-safe operations with memory management

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:57:58 +00:00
github-actions[bot]andMervin Praison 2c16131770 fix: comprehensive suppression of litellm deprecation warnings
- Add environment variables to suppress warnings at source (LITELLM_TELEMETRY, HTTPX_DISABLE_WARNINGS)
- Implement global deprecation warning filters before imports
- Add specific message filters for exact warning text patterns
- Set aggressive logging levels (CRITICAL) for all litellm loggers
- Configure runtime litellm settings to disable debug output
- Apply comprehensive suppression across main and LLM modules
- Addresses remaining warnings from httpx content parameter and pydantic dict method usage

Resolves issue with persistent litellm warnings after initial fix

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:53:45 +00:00
github-actions[bot]andMervin Praison bc0d58104c enhance: improve JSON parsing error handling for tool arguments
- Add explicit JSON parsing error handling in both streaming and non-streaming modes
- Remove redundant import json statement in streaming mode (already imported at module level)
- Ensure graceful fallback to empty dict when JSON parsing fails
- Maintain backward compatibility while improving robustness

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:50:29 +00:00
Mervin Praison a11990fa40 Merge pull request #1034 from MervinPraison/claude/issue-1033-20250722-1128
Fix litellm deprecation warnings for issue #1033
2025-07-22 12:44:09 +01:00
github-actions[bot]andMervin Praison e1f6601137 refactor: consolidate and document warning filters for issue #1033
- Centralized warning suppression in main __init__.py with comprehensive comments
- Removed duplicated warning filters from llm/__init__.py
- Improved pydantic regex specificity and added module targeting
- Added clear documentation explaining why each warning is suppressed

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:43:27 +00:00
github-actions[bot]andMervin Praison 05dc3b5223 fix: correct tool call argument parsing in streaming mode
- Fix critical bug where tool_call[''function''][''arguments''] was passed as JSON string instead of parsed dict to execute_tool
- Add proper JSON parsing with fallback to empty dict for missing arguments
- Resolves tool execution failures during streaming when tools are called
- Maintains backward compatibility and error handling

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:42:01 +00:00
Mervin Praison c8fdab5885 Merge pull request #1032 from MervinPraison/claude/issue-1031-20250722-1110
fix: eliminate streaming pause caused by telemetry tracking
2025-07-22 12:40:04 +01:00
8f1c18da70 Fix litellm deprecation warnings for issue #1033
Added comprehensive deprecation warning filters to suppress warnings from:
- litellm module and event loop related warnings
- httpx module deprecation warnings
- Pydantic model_dump deprecation warnings

This resolves the noisy deprecation warnings that were cluttering the output
when using PraisonAI agents with newer versions of dependencies.

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

Co-Authored-By: Claude <[email protected]>
Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:36:17 +00:00
Mervin Praison 739c25cbea Merge pull request #1030 from MervinPraison/claude/fix-streaming-display-bypass-20250722
fix: bypass display_generation for OpenAI streaming to enable raw chunk output
2025-07-22 12:25:03 +01:00
github-actions[bot]andMervin Praison bbbb77ba5c feat: enhance streaming implementation with proper tool call support
- Fix critical OpenAI client access bug: use sync_client instead of client
- Reduce code duplication by consolidating completion creation logic
- Improve test script: remove unused imports and properly test generator consumption
- Verify comprehensive tool call handling in streaming mode is working correctly
- All automated review feedback addressed while maintaining backward compatibility

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:17:54 +00:00
github-actions[bot] 00b81080a3 merge: accept comprehensive async telemetry fix from remote
The remote branch already implements a more comprehensive solution using
threading at the integration level, which addresses the streaming pause issue
more thoroughly than the async_mode parameter approach.

Remote changes include:
- All telemetry tracking made asynchronous using background threads
- Special handling for streaming generators in agent.start()
- Better error handling with try/catch blocks
- Maintains the async_mode parameter in telemetry.py for future use

Resolves streaming pause issue #1031
2025-07-22 11:17:41 +00:00
github-actions[bot]andMervin Praison 2c7cbdf0c9 fix: eliminate streaming pause caused by synchronous telemetry tracking
- Add async_mode parameter to track_agent_execution() to enable background PostHog capture
- Update telemetry integration to auto-detect streaming agents and use async mode
- Maintains backward compatibility for non-streaming agents
- Resolves pause issue after "execution tracked: success=True" message in streaming workflows

Fixes #1031

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:16:58 +00:00
github-actions[bot]andMervin Praison 112a7248ca fix: Eliminate telemetry pause in streaming responses
- Make telemetry tracking asynchronous in all agent methods (chat, start, run)
- For streaming responses, defer telemetry tracking until after generator consumption
- Use separate daemon threads to prevent blocking on PostHog capture calls
- Add comprehensive test script to verify fix works
- Fixes issue where ~20 second pause occurred after ''execution tracked: success=True''

This resolves the streaming performance issue where telemetry calls were
blocking the start of streaming responses, causing users to wait before
seeing any output when using agent.start() with stream=True.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:15:50 +00:00
github-actions[bot]andMervin Praison ce214edd99 feat: enhance streaming implementation with proper tool call support
- Add comprehensive tool call handling in OpenAI streaming mode
- Properly accumulate and execute tool calls during streaming
- Maintain chat history integrity with tool call results
- Preserve backward compatibility and existing functionality
- Add error handling for tool execution failures in streaming

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:12:51 +00:00
Mervin Praison ab8932be28 Merge pull request #1029 from MervinPraison/claude/fix-gemini-streaming-json-parsing-20250722
fix: enhance Gemini streaming robustness with graceful JSON parsing error handling
2025-07-22 12:08:02 +01:00
github-actions[bot]andMervin Praison 47c91ae624 fix: correct critical bugs in Gemini streaming error handling
- Fix error counter reset bug: only reset after successful chunk processing
- Fix error masking bug: non-recoverable errors are re-raised immediately
- Add proper exception chaining with ''from chunk_error''
- Remove unnecessary f-string prefix
- Move test to proper location in tests/ directory
- Remove hardcoded sys.path in test script

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:04:14 +00:00
github-actions[bot]andMervin Praison 626260f787 fix: bypass display_generation for OpenAI streaming to enable raw chunk output
This fix modifies Agent._start_stream() to handle OpenAI-style models with direct
streaming that bypasses the display_generation UI, allowing users to get raw
streaming chunks when stream=True.

Key changes:
- Replace self.chat() fallback with direct OpenAI client streaming
- Add proper knowledge search and tool handling for OpenAI path
- Use _build_messages helper for consistent message formatting
- Yield raw chunks without display function interference
- Add robust error handling with chat history rollback
- Preserve fallback to simulated streaming on errors

Fixes streaming behavior where chunks were wrapped in display_generation
instead of being yielded directly to user code.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 11:03:23 +00:00
github-actions[bot]andMervin Praison c0b8aba75b fix: enhance Gemini streaming robustness with graceful JSON parsing error handling
- Add chunk-level error handling in get_response_stream() to catch malformed JSON chunks
- Implement smart error recovery that skips recoverable errors (JSON parsing) vs non-recoverable (connection)
- Add consecutive error limit (3) with automatic fallback to non-streaming mode
- Enhance error logging with specific categorization for better debugging
- Add _is_streaming_error_recoverable() helper method for error classification
- Create test script to validate streaming robustness improvements

Fixes issue where Gemini streaming fails with ''Expecting property name enclosed in double quotes''
when receiving incomplete JSON chunks like ''{'' during streaming responses.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 08:56:50 +00:00
Mervin Praison e3b0b3830e Merge pull request #1028 from MervinPraison/claude/fix-real-time-streaming-20250722
fix: implement real-time streaming for Agent.start() method
2025-07-22 09:47:33 +01:00
github-actions[bot]andMervin Praison 8c3e1f8569 fix: add comprehensive tool call support to streaming implementation
- Remove erroneous temperature parameter from _build_messages() call in get_response_stream()
- Fix critical bug that would cause TypeError during streaming
- Tool call handling already implemented with _process_stream_delta helper
- Real-time streaming now works with content and tool execution
- Follow-up responses after tool completion properly handled
- Backward compatibility maintained with stream=False default

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 08:10:27 +00:00
github-actions[bot]andMervin Praison ab01fe2965 fix: add comprehensive tool call support to streaming implementation
Fixes critical gap in get_response_stream method where tool calls were
completely ignored during streaming. The method now properly:

- Accumulates tool calls during streaming using _process_stream_delta
- Executes tool calls after streaming completes if execute_tool_fn provided
- Continues conversation with follow-up response after tool execution
- Handles both Ollama and other providers correctly
- Maintains real-time content streaming while adding tool support

This makes streaming fully functional for agents that use tools, which
is essential for PraisonAI''s core functionality.

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

Co-Authored-By: Mervin Praison <[email protected]>
2025-07-22 07:58:31 +00:00
github-actions[bot]andMervin Praison e6472b5052 fix: restore backward compatibility by defaulting stream=False
- Change Agent constructor default: stream=True -> stream=False
- Update documentation to clarify backward compatibility priority
- Ensure existing code agent.start(''prompt'') returns string not generator
- Maintain streaming capability when explicitly enabled with stream=True

Fixes backward compatibility issue where basic usage would return generator
instead of expected string response, breaking existing codebases.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 06:40:27 +00:00
github-actions[bot]andMervin Praison a178abe759 fix: implement real-time streaming for Agent.start() method
- Add get_response_stream() generator method to LLM class for true real-time streaming
- Modify Agent._start_stream() to use new streaming generator for custom LLMs
- Replace simulated streaming with actual LiteLLM streaming chunks
- Maintain backward compatibility for OpenAI-style models (temporary fallback)
- Add comprehensive error handling and chat history management
- Include test files for validation

Fixes the issue where streaming was simulated by chunking complete responses
instead of yielding real-time chunks from the underlying LLM.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-22 06:32:17 +00:00
Mervin Praison b139ea98ba Merge pull request #1027 from MervinPraison/claude/issue-981-20250721-1557
fix: implement real-time streaming for Agent.start() method
2025-07-22 07:17:42 +01:00
github-actions[bot]andMervin Praison 589650029b refactor: simplify streaming implementation to eliminate code duplication
- Replace duplicated logic in _custom_llm_stream() and _openai_stream() with single _start_stream() method
- Reuse existing chat() method logic to maintain all features (tools, knowledge, MCP, etc.)
- Improve error handling and consistency across LLM types
- Maintain backward compatibility and all existing functionality
- Reduce maintenance burden by eliminating 150+ lines of duplicated code

Co-authored-by: Mervin Praison <[email protected]>
2025-07-21 16:42:18 +00:00
github-actions[bot]andMervin Praison 97b25f5003 fix: implement real-time streaming for Agent.start() method
- Fix streaming issue where Agent.start() was not yielding real-time chunks
- Add streaming generator support with proper type hints
- Implement _start_stream() method that routes to appropriate handlers
- Add _custom_llm_stream() for custom LLM providers with simulated chunking
- Add _openai_stream() for OpenAI client with true streaming chunks
- Maintain backward compatibility for existing non-streaming usage
- Support both OpenAI and custom LLM streaming with graceful error handling
- Preserve chat history management and proper conversation state

The user''s code pattern now works as expected:
for chunk in agent.start(prompt, stream=True):
    print(chunk, end='''', flush=True)

Fixes #981

Co-authored-by: Mervin Praison <[email protected]>
2025-07-21 16:02:10 +00:00
Mervin Praison 5d30ce9a1b Merge pull request #1026 from MervinPraison/claude/issue-1025-20250721-0849
feat: add context CLI command with --url and --goal parameters
2025-07-21 12:17:40 +01:00
github-actions[bot]andMervin Praison 5ad39b5f1b refactor: improve context CLI command with minor code enhancements
- Fix f-string formatting issues by removing unnecessary f prefix
- Add return type hint to handle_context_command method
- Enhance docstring with return type documentation
- Maintain backward compatibility with existing usage

Co-authored-by: Mervin Praison <[email protected]>
2025-07-21 10:12:16 +00:00
github-actions[bot]andMervin Praison 28c60d52f5 feat: enhance context CLI command with configurable options
- Add --auto-analyze flag for user control over analysis mode
- Use environment MODEL_NAME/OPENAI_MODEL_NAME instead of hardcoded model
- Update usage messages to include new optional flag
- Follow existing CLI patterns for model configuration
- Maintain backward compatibility with defaults

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-21 10:08:48 +00:00
github-actions[bot]andMervin Praison 3a9e26670f feat: add context CLI command with --url and --goal parameters
- Add ''context'' to special_commands list
- Add --url and --goal CLI arguments
- Add handle_context_command method to create ContextAgent
- Maintains backward compatibility
- Implements exact functionality requested in issue #1025

Usage: praisonai context --url <url> --goal <goal>

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-21 08:54:53 +00:00
Mervin Praison 209793bdb1 feat: add MongoDB integration examples and context engineering improvements 2025-07-20 03:47:29 +01:00
Mervin Praison aa965cf719 Merge pull request #1024 from MervinPraison/fix-knowledge-verbose-headers
fix: remove verbose knowledge headers from AI agent prompts
2025-07-19 13:06:45 +01:00
Mervin Praison 4927f24d4a Merge pull request #1021 from MervinPraison/claude/issue-1018-20250719-0632
Implement Context Engineering - Add ContextAgent for AI Context Generation
2025-07-19 09:45:51 +01:00
github-actions[bot]andMervin Praison 2a3240156d fix: add backward compatibility for embedding_db_config key in knowledge context processing
- Support both ''vector_store'' and ''embedding_db_config'' keys for knowledge context
- Maintains backward compatibility with existing test files
- No functional changes to the verbose header removal functionality

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-19 08:43:17 +00:00
github-actions[bot]andClaude 77e8ccb3c9 Transform hardcoded analysis to Agent-based dynamic analysis
This commit transforms all hardcoded analysis methods in ContextAgent to use specialized AI agents for dynamic analysis. The changes enable more flexible, intelligent, and adaptable context processing by leveraging agent-based approaches instead of static analysis patterns.

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

Co-Authored-By: Claude <[email protected]>
2025-07-19 08:42:49 +00:00
github-actions[bot]andMervin Praison 031c73c7d3 fix: remove verbose knowledge headers from AI agent prompts
- Remove ''[DB Context]:'' and ''[Vector DB Error]:'' prefixes from agent outputs
- Add debug logging to preserve troubleshooting information
- Return clean content without verbose headers in terminal display
- Hide error details from AI prompts while preserving debug logs
- Consistent with memory.py verbose header removal approach

Co-authored-by: Mervin Praison <[email protected]>
2025-07-19 08:33:29 +00:00
Mervin Praison 82b6f9c5ff Merge pull request #1023 from MervinPraison/claude/pr-1020-20250719-0708
fix: remove verbose memory context headers from AI agent prompts
2025-07-19 09:06:01 +01:00
github-actions[bot]andMervin Praison 22449a35b7 feat: hide memory content from terminal display unless debug logging enabled
- Add include_in_output parameter to build_context_for_task() method
- Memory content now only included in output when logging level is DEBUG
- Memory is always logged for debugging regardless of output inclusion
- Preserves AI agent functionality while hiding memory from user display
- Addresses user requirement to hide memory items from terminal by default

Co-authored-by: Mervin Praison <[email protected]>
2025-07-19 07:55:41 +00:00
Mervin Praison 75bf3ac73b Merge pull request #1022 from MervinPraison/claude/issue-1019-20250719-0623
fix: move embedding debug logs to trace level
2025-07-19 08:52:32 +01:00
4d3e19462b Reorganize TRACE logging test files and improve test structure
- Move test_embedding_logging.py from root to tests/ directory for better organization
- Improve test structure with comprehensive TRACE logging validation
- Ensure proper test isolation and cleanup
- Maintain backward compatibility while improving code organization

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

Co-Authored-By: Mervin Praison <[email protected]>
Co-Authored-By: Claude <[email protected]>
2025-07-19 07:42:08 +00:00
github-actions[bot]andClaude efaff8845d Fix Context Engineering implementation: Complete functionality and async support
- Fixed core ContextAgent functionality with proper imports and async support
- Added comprehensive error handling and robust implementation
- Cleaned up imports and fixed async method patterns
- Moved test file from root to proper tests/ directory location
- Made implementation fully functional with all required methods
- Enhanced examples with working context engineering workflows

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

Co-Authored-By: Claude <[email protected]>
2025-07-19 07:15:22 +00:00
github-actions[bot]andMervin Praison a4e7a1bdbc fix: remove verbose memory context headers from AI agent prompts
- Remove ''Short-term Memory (X items)'' and ''Long-term Memory (X items)'' headers from AI prompts
- Remove ''Relevant Memory Context:'' and ''Previous task'' prefixes from agent context
- Keep actual memory content and task results for AI functionality
- Move verbose information to debug logging only
- Prevents AI agents from echoing memory context headers in terminal output

This fixes the issue where memory context headers were still appearing in terminal
displays even after the original PR moved verbose information to debug logging.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-19 07:14:37 +00:00
Mervin Praison fd346b410d Merge pull request #1020 from MervinPraison/claude/fix-context-display-issues
fix: move verbose context information from live display to debug logging
2025-07-19 07:53:34 +01:00
github-actions[bot]andMervin Praison 9acff8f977 Implement Context Engineering - Add ContextAgent for AI Context Generation
- Add ContextAgent class with comprehensive Context Engineering capabilities
- Implements automated context generation for AI coding assistants
- Features: codebase analysis, pattern extraction, validation loops, PRP generation
- 10x better than prompt engineering, 100x better than vibe coding
- Includes factory function create_context_agent() for easy instantiation
- Add comprehensive examples in agents/ and concepts/ directories
- Full backward compatibility maintained with existing PraisonAI functionality
- Complete test suite with 7/7 tests passing

Co-authored-by: Mervin Praison <[email protected]>
2025-07-19 06:46:51 +00:00
github-actions[bot]andMervin Praison 4bc3ad97a1 fix: restore AI agent access to actual memory and task context content
- agents.py: Restore actual task result content and memory context in AI prompts
- task.py: Include actual task context results for proper task chaining
- memory.py: Return actual memory content with clean formatting instead of placeholders
- Fix f-string formatting issue in agents.py

This fixes critical functionality bugs where AI agents were receiving placeholder
messages instead of actual content, breaking memory access and task dependencies.
AI agents now get full context while debug logging is preserved.

Resolves issues identified by automated reviews while maintaining backward compatibility.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-19 06:45:55 +00:00
Claude Code a91228b46e Add custom TRACE logging level to reduce embedding data in debug output
- Add TRACE_LEVEL (5) below DEBUG (10) for fine-grained logging control
- Implement trace() method on logging.Logger class for backward compatibility
- Convert 4 embedding-related debug statements to use trace level
- Embedding data now only appears when logging level set to TRACE or lower
- Maintains full backward compatibility with existing debug logging
- Addresses issue where sensitive embedding data cluttered terminal output

Test coverage:
- Add test_embedding_logging.py to validate implementation functionality
- Verify TRACE level behavior and message filtering

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

Co-Authored-By: Claude <[email protected]>
2025-07-19 06:45:31 +00:00
Mervin Praison 74403501ed Merge pull request #1017 from MervinPraison/claude/issue-1016-20250719-0556
fix(knowledge): resolve 'list' object has no attribute 'get' error
2025-07-19 07:17:56 +01:00
github-actions[bot]andClaude c1703dd234 Fix backward compatibility issue in knowledge.py memory result handling
- Add type checking for memory_result in _process_single_input method
- Handle both dict and list formats for backward compatibility
- Gracefully handle unexpected types with warning instead of crashing
- Resolves issue #1016 where MongoDB memory provider returns dict while Chroma returns list

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

Co-Authored-By: Claude <[email protected]>
2025-07-19 06:08:08 +00:00
github-actions[bot]andClaude 256ad050e4 fix: move verbose context information from live display to debug logging
This commit addresses live display context issues by moving detailed content
from user-facing prompts to debug logging while maintaining functionality:

- agents.py line 653: Memory context now logged via logger.debug() with
  brief user-facing note in prompt instead of full content
- agents.py line 84: Previous task results logged via logger.debug() with
  brief completion status returned instead of full raw content
- task.py line 406: Previous task results logged via logger.debug() with
  brief completion message appended instead of full raw content
- memory.py: Memory section headers now use brief titles with item counts
  and log detailed content via logger.debug() instead of showing full content

These changes maintain backward compatibility and functionality while
improving user experience by reducing verbose output in live displays.
Detailed information remains available through debug logging for debugging
and troubleshooting purposes.

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

Co-Authored-By: Claude <[email protected]>
2025-07-19 06:01:11 +00:00
github-actions[bot]andMervin Praison 4ca844e667 fix(knowledge): resolve ''list'' object has no attribute ''get'' error
Fixed line 717 in knowledge.py where memory_result.get(''results'', [])
was called on a list instead of a dict. Both MongoDBMemory.add() and
CustomMemory._add_to_vector_store() return lists directly, so changed
to all_results.extend(memory_result) for proper list concatenation.

Resolves #1016

Co-authored-by: Mervin Praison <[email protected]>
2025-07-19 06:00:09 +00:00
Mervin Praison 7e473dcb14 Merge pull request #1015 from MervinPraison/claude/issue-1014-20250719-0501
fix: show context only when loglevel=debug
2025-07-19 06:29:23 +01:00
Mervin Praison 0188c6bf77 docs: add llms.md documentation and update MongoDB example to use local knowledge file 2025-07-19 06:27:15 +01:00
github-actions[bot]andClaude df304df3cf Fix logger configuration to support DEBUG level for verbose >= 3
- Add DEBUG logging level when verbose >= 3
- Maintain INFO level for verbose >= 5
- Keep WARNING level for verbose < 3
- This makes the verbose flag functional for debugging purposes

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

Co-Authored-By: Claude <[email protected]>
2025-07-19 05:22:03 +00:00
Claude CodeandMervin Praison 82cdda36d7 fix: show context only when loglevel=debug
Changed logger.info to logger.debug for context content display
in agents.py to reduce log noise while maintaining the ability
to see context information when debug logging is enabled.

Changes:
- agents.py:315 - Context content logging moved to debug level
- agents.py:638 - Context content logging moved to debug level

Maintains backward compatibility as context count logging remains
at INFO level, only the actual context content is moved to DEBUG.

Fixes #1014

Co-authored-by: Mervin Praison <[email protected]>
2025-07-19 05:08:27 +00:00
Mervin Praison 9d6c6d7ab2 refactor: improve result handling and display in MongoDB example files 2025-07-19 06:01:20 +01:00
Mervin Praison e47c6b4278 feat: upgrade praisonaiagents to 0.0.144 and add MongoDB support 2025-07-18 22:28:29 +01:00
Mervin Praison aab077ce92 refactor: optimise agent initialisation and streamline function calls
- Removed unnecessary force_shutdown_telemetry() call from basic-agents.py to enhance clarity.
- Updated llm parameter in gemini-sequential.py from "gemini-2.5-pro" to "gemini-2.5-flash" for improved performance.
- Simplified the for loop in realtime-streaming.py by removing the return_generator=True argument, maintaining functionality while improving readability.

These changes aim to enhance code efficiency and maintainability without altering existing functionality.
2025-07-18 22:17:02 +01:00
Mervin Praison 6d717d59b1 Merge pull request #1013 from MervinPraison/claude/issue-1011-20250718-1758
fix: prevent PostHog shutdown errors during interpreter shutdown
2025-07-18 22:12:19 +01:00
github-actions[bot]andMervin Praison 07cc581c04 refactor: remove duplicate threading import in _is_interpreter_shutting_down method
- Remove redundant ''import threading'' since threading is already imported at module level
- Addresses reviewer feedback on code duplication
- Maintains all functionality while improving code cleanliness

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 20:59:52 +00:00
github-actions[bot]andMervin Praison 283282d98b refactor: improve telemetry shutdown error handling and reduce code duplication
- Add centralized _SHUTDOWN_ERROR_PHRASES constant for consistent error detection
- Create _is_shutdown_related_error() helper method to eliminate code duplication
- Remove duplicate import threading in _is_interpreter_shutting_down()
- Remove redundant _posthog = None assignment handled by finally block
- Ensure all shutdown error detection uses consistent phrase list

Addresses reviewer feedback on duplicate imports, inconsistent error handling,
and code duplication while maintaining full backward compatibility.

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 20:54:58 +00:00
github-actions[bot]andMervin Praison c231d625c3 fix: prevent PostHog shutdown errors during interpreter shutdown
- Add interpreter shutdown detection using sys.is_finalizing() and thread tests
- Skip PostHog operations when interpreter is shutting down to prevent:
  - cannot schedule new futures after interpreter shutdown errors
  - can''t register atexit after shutdown errors
  - Event loop and threading errors during shutdown
- Enhanced error handling with specific shutdown error message filtering
- Apply shutdown prevention to flush, thread cleanup, and shutdown operations
- Maintain full backward compatibility with existing API
- Add comprehensive debug logging for shutdown scenarios

Fixes issue #1011 where PostHog telemetry was causing shutdown errors
when force_shutdown_telemetry() was called during interpreter shutdown.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 18:03:08 +00:00
Mervin Praison d1b4ab0d95 Merge pull request #1010 from MervinPraison/claude/issue-1009-20250718-1740
fix: prevent telemetry shutdown from hanging indefinitely
2025-07-18 18:56:25 +01:00
github-actions[bot]andMervin Praison c0d5eec2a7 fix: enhance telemetry shutdown robustness and prevent critical issues
- Add thread safety with shutdown locks to prevent concurrent shutdown calls
- Fix double thread pool shutdown issue that could cause undefined behavior
- Implement memory leak prevention with bounded metrics storage (max 1000 entries)
- Replace unsafe daemon threads with ThreadPoolExecutor for better control
- Increase flush timeout from 2s to 5s for improved reliability
- Add comprehensive error handling with proper logging levels
- Split shutdown logic into maintainable helper methods
- Maintain full backward compatibility with existing API

These changes address critical thread safety issues while preserving all
existing functionality and ensuring reliable telemetry shutdown behavior.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 17:53:46 +00:00
github-actions[bot]andMervin Praison 94f7edaae4 fix: prevent telemetry shutdown from hanging indefinitely
- Added timeout-based flush operation in MinimalTelemetry.shutdown()
- Replaced blocking PostHog flush with threaded timeout approach
- Prevents indefinite blocking during program termination
- Maintains backward compatibility and data integrity
- Fixes issue where PostHog queue.join() would hang on exit

Resolves #1009

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 17:43:38 +00:00
Mervin Praison 6607b6279e refactor: streamline chat method by consolidating logging and error handling
- Simplified logging of parameters in debug mode for better clarity.
- Enhanced error handling during LLM calls and reflections to ensure robust rollback mechanisms.
- Improved structure for handling knowledge search and prompt normalization.
- Reduced code duplication by integrating common functionalities into streamlined processes.
2025-07-18 18:32:34 +01:00
Mervin Praison d1cf53c543 Merge pull request #998 from MervinPraison/claude/pr-996-20250718-1439
Fix: Correct indentation in chat method try-finally block
2025-07-18 18:22:55 +01:00
Mervin Praison 4dcc72a02b Merge branch 'main' into claude/pr-996-20250718-1439 2025-07-18 18:22:19 +01:00
Mervin Praison d2a70c45ab Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-18 18:11:56 +01:00
Mervin Praison a3cfaaabec refactor: reorganize test files into src directory and add telemetry cleanup 2025-07-18 18:11:06 +01:00
Mervin Praison 4743ba20be Merge pull request #1006 from MervinPraison/revert-1005-claude/pr-1002-20250718-1556
Revert "PR #1002: Changes from Claude"
2025-07-18 17:36:26 +01:00
Mervin Praison 81d4042578 Revert "PR #1002: Changes from Claude" 2025-07-18 17:36:18 +01:00
Mervin Praison 9a6b156b6e Merge pull request #1005 from MervinPraison/claude/pr-1002-20250718-1556
PR #1002: Changes from Claude
2025-07-18 17:35:55 +01:00
github-actions[bot]andMervin Praison fbbee806d1 Refactor telemetry cleanup to use try...finally pattern
- Replace 13 scattered _cleanup_telemetry() calls with single try...finally block
- Ensure cleanup happens on ALL exit paths regardless of success/failure
- Standardize test tolerances to 2 threads across all test files
- Improve test error messages to show specific thread details
- Maintain backward compatibility and all existing functionality
- Reduce code duplication by 95% in chat method

🤖 Generated with Claude Code

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 16:32:22 +00:00
Mervin Praison 2241ecbdde Merge pull request #1004 from MervinPraison/claude/issue-1003-20250718-1604
Fix: Agent.start() now auto-consumes generator for better UX
2025-07-18 17:14:00 +01:00
github-actions[bot]andMervin Praison 0501a85b9e Fix: Agent.start() now auto-consumes generator for better UX
- Modified Agent.start() method to automatically consume the generator by default
- Added return_generator=True parameter for backwards compatibility
- Made MCP import optional to prevent import errors
- Updated examples to demonstrate new behavior
- Fixes issue where basic-agents.py would stop without producing output

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 16:13:19 +00:00
github-actions[bot]andMervin Praison c5c728e148 Fix: Enhance telemetry cleanup to prevent agent termination hang
- Added comprehensive telemetry cleanup calls in agent.py at all return points
- Ensures proper cleanup after guardrail validation failures
- Prevents hanging during agent termination by forcing telemetry shutdown
- Added test files to validate telemetry cleanup functionality
- Addresses hanging issues in async agent execution flows

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

Co-Authored-By: Mervin Praison <[email protected]>
2025-07-18 16:04:37 +00:00
Mervin Praison 6d4c1d71fb Merge pull request #1002 from MervinPraison/claude/pr-999-20250718-1529
Fix: Add comprehensive telemetry cleanup to prevent agent termination hang
2025-07-18 16:47:38 +01:00
Mervin Praison 31435c454f Merge pull request #1001 from MervinPraison/claude/pr-997-20250718-1454
Fix: Add telemetry cleanup to execute() and aexecute() methods to prevent hanging
2025-07-18 16:46:47 +01:00
github-actions[bot]andMervin Praison 00e722aae1 Fix: Add comprehensive telemetry cleanup to prevent agent termination hang
- Fixed 7 missing telemetry cleanup calls in agent.py
- Added cleanup to all return paths in chat() and achat() methods
- Added cleanup to custom LLM guardrail validation paths
- Added cleanup to reasoning content validation paths
- Added cleanup to exception handlers in achat() method
- Ensures proper termination of telemetry threads
- Prevents hanging after agent task completion
- Maintains full backward compatibility
- Comprehensive testing shows all agents now terminate properly

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 15:40:17 +00:00
Mervin Praison 76a65b3667 Merge pull request #1000 from MervinPraison/claude/fix-telemetry-termination-20250718
Fix: Comprehensive telemetry cleanup to prevent agent termination hang
2025-07-18 16:30:42 +01:00
github-actions[bot]andMervin Praison cd5459d4dc Fix: Comprehensive telemetry cleanup to prevent agent termination hang
This commit addresses the critical issue where PraisonAI agents would not
terminate properly after completing their tasks, requiring manual interruption.

Root Cause: PostHog telemetry client running in async mode creates
background threads that persist after standard shutdown() calls.

Solution:
- Enhanced telemetry shutdown mechanism with comprehensive thread cleanup
- Added force_shutdown_telemetry() function for robust cleanup
- Implemented timeout-based thread termination with proper error handling
- Updated agent._cleanup_telemetry() to use the new robust cleanup method

Impact:
- Agents now terminate cleanly without hanging
- Maintains full backward compatibility
- Comprehensive thread cleanup prevents resource leaks
- Timeout mechanism prevents infinite waiting

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 15:27:44 +00:00
Mervin Praison 326390863f Merge pull request #999 from MervinPraison/claude/issue-987-20250718-1504
Fix: Resolve agent termination issue by adding comprehensive telemetry cleanup
2025-07-18 16:18:33 +01:00
github-actions[bot]andMervin Praison d1e6706427 Fix: Resolve agent termination issue by adding comprehensive telemetry cleanup
- Added _cleanup_telemetry() calls to all return paths in chat() and achat() methods
- Ensures proper program termination without requiring Ctrl+C
- Maintains full backward compatibility with existing APIs
- Addresses syntax error concerns by implementing clean, error-free code
- Added test script to verify the fix works correctly

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 15:16:38 +00:00
github-actions[bot]andMervin Praison 7f0f8d5ed9 Fix: Add telemetry cleanup to execute() and aexecute() methods to prevent hanging
- Add try-finally blocks to execute() and aexecute() methods
- Ensures telemetry cleanup happens for all public entry points
- Prevents programs from hanging due to PostHog background threads
- Maintains backward compatibility
- Addresses critical gaps identified in PR reviews

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 14:57:09 +00:00
github-actions[bot]andMervin Praison 556d1298f1 Fix: Correct indentation in chat method try-finally block
- Fixed syntax error at line 1197 where code was outside try block
- Properly indented all main logic to be inside try block
- Ensures telemetry cleanup finally block executes correctly
- Maintains backward compatibility
- No breaking changes

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 14:49:41 +00:00
Mervin Praison 48acfce433 Merge pull request #994 from MervinPraison/claude/issue-992-20250718-1345
feat: integrate MongoDB as memory and knowledge provider
2025-07-18 15:44:44 +01:00
Mervin Praison 1ddcafbaa4 Merge branch 'main' of https://github.com/MervinPraison/PraisonAI 2025-07-18 15:43:11 +01:00
Mervin Praison eb2073fe77 Enhance workflow configurations by adding a timeout of 15 minutes to all job definitions in the CI/CD pipeline. This change aims to improve resource management and prevent long-running jobs from hanging indefinitely. 2025-07-18 15:43:10 +01:00
Mervin Praison 732e4e6c75 Merge pull request #997 from MervinPraison/revert-996-claude/pr-990-20250718-1429
Revert "Fix: Comprehensive telemetry cleanup to prevent agent termination issues"
2025-07-18 15:39:49 +01:00
Mervin Praison 7f01facb36 Revert "Fix: Comprehensive telemetry cleanup to prevent agent termination issues" 2025-07-18 15:39:39 +01:00
Mervin Praison b2cc7ebfd9 Merge pull request #996 from MervinPraison/claude/pr-990-20250718-1429
Fix: Comprehensive telemetry cleanup to prevent agent termination issues
2025-07-18 15:38:31 +01:00
github-actions[bot]andMervin Praison 3c51b6f644 Fix: Comprehensive telemetry cleanup to prevent agent termination issues
- Added telemetry cleanup to all agent entry points (chat, achat, execute, aexecute)
- Fixed streaming issue by adding cleanup to _start_stream method
- Removed duplicate cleanup from convenience methods
- Ensures proper program termination regardless of which method is used

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 14:36:46 +00:00
Mervin Praison 44f02cdf43 Merge pull request #990 from MervinPraison/claude/issue-987-20250718-1031
Fix: Resolve agent termination issue by properly cleaning up telemetry system
2025-07-18 15:24:30 +01:00
Mervin Praison 55668c9510 Merge branch 'main' into claude/issue-987-20250718-1031 2025-07-18 15:24:03 +01:00
github-actions[bot]andMervin Praison 28e95388f9 fix: resolve MongoDB integration issues
- Fix ID generation consistency between MongoDB and SQLite storage
- Fix inconsistent error handling in memory operations
- Fix security issue with hardcoded API key placeholders in examples
- Fix unused imports in mongodb_tools.py
- Fix pymongo version to >= 4.6.3 to address security vulnerabilities
- Improve datetime import organization
- Ensure consistent storage order for better reliability

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 14:18:53 +00:00
github-actions[bot]andMervin Praison 663150a0ee fix: resolve MongoDB integration issues
- Fix memory record citation duplication (lines 861, 880, 933 in memory.py)
- Make vector dimensions configurable based on embedding model
- Add _get_embedding_dimensions method for proper dimension detection
- Support multiple embedding models (text-embedding-3-small, 3-large, ada-002)
- Improve citation format to use record IDs instead of duplicating text

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 14:13:14 +00:00
github-actions[bot]andMervin Praison 225ce7b9f2 feat: integrate MongoDB as memory and knowledge provider
Add comprehensive MongoDB integration for PraisonAI agents including:

**Memory Provider**:
- MongoDB as persistent memory storage option
- Vector search capabilities with Atlas Vector Search
- Support for both key-value and vector operations
- Quality scoring and filtering
- User-specific memory isolation
- Graceful fallback to existing SQLite/ChromaDB

**Knowledge Store**:
- MongoDB as vector store for knowledge base
- Document processing with embeddings
- Vector similarity search for knowledge retrieval
- Chunking and metadata management
- Compatible with existing Mem0/ChromaDB workflow

**Tools Integration**:
- Complete MongoDB tools suite (CRUD operations)
- Vector search and text search capabilities
- Collection management and indexing
- Production-ready connection handling
- Error handling and logging

**Examples**:
- Memory provider example with persistent storage
- Knowledge store example with vector search
- Tools integration example with database operations
- Comprehensive business scenario simulation
- Complete documentation and best practices

**Technical Details**:
- Optional dependency: pip install ''praisonaiagents[mongodb]''
- Backward compatibility maintained
- Supports both local MongoDB and Atlas
- Configurable connection pooling and timeouts
- Comprehensive error handling

Resolves #992

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

Co-Authored-By: Mervin Praison <[email protected]>
2025-07-18 14:02:34 +00:00
Mervin Praison b2cacb243f Merge pull request #991 from MervinPraison/claude/issue-981-20250718-1032
fix: implement real-time streaming for Agent.start() method
2025-07-18 15:01:30 +01:00
github-actions[bot]andMervin Praison 9e25572c84 fix: resolve critical issues in streaming implementation
- Fix chat_history_length initialization bug in both streaming methods
- Add safe array access checks for chunk.choices in OpenAI client
- Add JSON parsing error handling for malformed tool arguments
- Remove unused imports and variables
- Update test files to use mock LLM instead of real APIs
- Ensure robust error handling throughout streaming pipeline

These fixes address all critical issues identified by code review bots
while maintaining backward compatibility and streaming functionality.

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 13:53:45 +00:00
Mervin Praison 801aedc00a Merge pull request #989 from MervinPraison/claude/issue-988-20250718-1318
fix: Add tool usage time tracking to MCP execution
2025-07-18 14:50:48 +01:00
github-actions[bot]andMervin Praison f18103f66b fix: Add thread safety and fix initialization timeout bug in tool timing
- Add thread locks to MCPToolRunner._tool_timings and MinimalTelemetry._metrics
- Fix initialization timeout bug where telemetry tracking was bypassed
- Move timing measurement after initialization check for accuracy
- Ensure telemetry is captured for all tool execution outcomes

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 13:48:22 +00:00
Mervin Praison a75745729b Merge pull request #986 from MervinPraison/claude/issue-985-20250717-1851
fix: resolve vertex_ai parameter compatibility issue for image generation
2025-07-18 14:29:00 +01:00
github-actions[bot]andMervin Praison 2bc61a1d55 fix: Add tool usage time tracking to MCP execution
- Enhanced telemetry.track_tool_usage() to accept execution_time parameter
- Added timing instrumentation to MCPToolRunner.call_tool() method
- Tool usage timing is now captured and stored in telemetry metrics
- Maintains backward compatibility with no breaking changes
- Addresses issue #988 where tool usage time was always 0

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 13:24:36 +00:00
github-actions[bot]andMervin Praison a3877c34e5 improve: enhance image agent parameter filtering robustness
- Replace overly broad exception handling with specific exceptions
- Consolidate duplicated gemini parameter filtering logic
- Add debug logging for provider detection failures
- Improve code readability with better variable separation
- Maintain backward compatibility and safety mechanisms

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 10:42:15 +00:00
github-actions[bot]andMervin Praison ff1022bdb6 fix: implement real-time streaming for Agent.start() method
- Add streaming generator support to Agent.start() method
- Implement _start_stream() method for streaming logic
- Add _chat_stream() method to route streaming to appropriate handlers
- Add _custom_llm_stream() for custom LLM streaming support
- Add _openai_stream() for OpenAI client streaming support
- Add chat_completion_with_tools_stream() method to OpenAI client
- Maintain backward compatibility for existing code
- Add proper error handling and chat history management

Fixes #981

Co-authored-by: Mervin Praison <[email protected]>
2025-07-18 10:40:49 +00:00
github-actions[bot]andClaude 22e9904aef fix: resolve agent termination issue by properly cleaning up telemetry system
- Add proper cleanup in Agent.start() and Agent.astart() methods using try-finally blocks
- Implement _cleanup_telemetry() method to ensure telemetry system shutdown
- Prevent hanging after agent execution by properly shutting down background threads
- Add test files to verify the termination fix works correctly

Fixes #987

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

Co-Authored-By: Claude <[email protected]>
2025-07-18 10:36:19 +00:00
Mervin Praison e5b7f7b740 Merge pull request #983 from Dhivya-Bharathy/models-providers-reorganization
feat: Add comprehensive provider examples for all major LiteLLM providers with clean API structure
2025-07-18 11:30:39 +01:00
github-actions[bot]andMervin Praison 3a137fb71e fix: resolve vertex_ai parameter compatibility issue for image generation
- Add provider-aware parameter filtering for image generation
- Filter out unsupported ''style'' parameter for vertex_ai models
- Maintain backward compatibility for other providers (OpenAI, Gemini)
- Add drop_params=True safety mechanism
- Resolves litellm.UnsupportedParamsError for gemini-2.0-flash-preview-image-generation

Co-authored-by: Mervin Praison <[email protected]>
2025-07-17 19:01:41 +00:00
Dhivya-Bharathy 8e09f5e4b4 Add comprehensive model examples with 5 agents per model: Llama, Claude, GPT 2025-07-17 13:46:49 +05:30
Dhivya-Bharathy 82e6673488 Add 3 more provider examples: Moonshot AI, Databricks, AI21 2025-07-17 13:17:30 +05:30
Dhivya-Bharathy dd9b24597a Add comprehensive provider examples for all major LiteLLM providers 2025-07-17 13:01:08 +05:30
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
Mervin Praison 000bdf3418 refactor: move test files to src/praisonai-agents and bump version to 2.2.57 2025-07-14 18:40:18 +01:00
github-actions[bot]andMervin Praison 826ff56fc5 refactor: simplify LLMGuardrail string handling and consolidate imports
- Remove redundant if/else logic in string LLM initialization
- Consolidate duplicate LLM imports using _get_llm_class helper
- Maintain all functionality while improving code clarity
- Addresses code review feedback for cleaner, more maintainable code

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #876

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

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

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

Fixes #870

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

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

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

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

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

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

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

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

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

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

Fixes #878

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

Fixes #871

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

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

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

Fixes #872

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

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

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

Fixes #874

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

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

Resolves #869

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

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

Fixes #854

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

Fixes #866

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

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

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

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

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

Fixes issue #846

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

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

Fixes #845

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

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

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

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

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

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

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

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

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

This ensures backward compatibility while maintaining the sequential tool calling fix

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

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

Fixes #841

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

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

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

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

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

Resolves #839

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

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

Fixes #835

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

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

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

Addresses review feedback on PR #832

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

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

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

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

Fixes #831

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

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

Fixes #824

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

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

Fixes #827

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

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

Closes #823

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #815

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

Resolves #813

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

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

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

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

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

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

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

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

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

This resolves the SyntaxError preventing module import and test execution.

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

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

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

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

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 23:01:57 +00:00
Mervin Praison 4c62731e81 Merge branch 'main' into claude/issue-795-20250710_222918 2025-07-10 23:56:44 +01:00
claude[bot]andMervin Praison 7ddbf98794 fix: add user message to chat_history before LLM call to fix handoff issue
This fix ensures that handoff tools can access the current user message
during execution. Previously, chat_history was updated after the LLM call,
causing handoffs to fail with "no specific task was provided" message.

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

This maintains backward compatibility while fixing the handoff functionality.

Fixes #795

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

Fixes #792

Co-authored-by: Mervin Praison <[email protected]>
2025-07-10 22:21:30 +00:00
943 changed files with 144753 additions and 6753 deletions

No files matched your search

+38 -22
View File
@@ -86,13 +86,29 @@ runs:
- name: Extract GitHub Context and Create Prompt
shell: bash
id: prepare_context
env:
# Pass user-controlled inputs via environment variables to prevent script injection (GHSL-2025-093)
EVENT_COMMENT_BODY: ${{ github.event.comment.body }}
EVENT_ISSUE_TITLE: ${{ github.event.issue.title }}
EVENT_ISSUE_BODY: ${{ github.event.issue.body }}
EVENT_ISSUE_NUMBER: ${{ github.event.issue.number }}
EVENT_PR_TITLE: ${{ github.event.pull_request.title }}
EVENT_PR_NUMBER: ${{ github.event.pull_request.number }}
EVENT_REVIEW_BODY: ${{ github.event.review.body }}
EVENT_ASSIGNEE_LOGIN: ${{ github.event.assignee.login }}
INPUT_TRIGGER_PHRASE: ${{ inputs.trigger_phrase }}
INPUT_ASSIGNEE_TRIGGER: ${{ inputs.assignee_trigger }}
INPUT_DIRECT_PROMPT: ${{ inputs.direct_prompt }}
EVENT_ACTION: ${{ github.event.action }}
EVENT_NAME: ${{ github.event_name }}
REPO_NAME: ${{ github.repository }}
run: |
echo "🔍 Extracting GitHub context from event: ${{ github.event_name }}"
echo "🔍 Extracting GitHub context from event: $EVENT_NAME"
# Function to check for trigger phrase
check_trigger() {
local text="$1"
local trigger="${{ inputs.trigger_phrase }}"
local trigger="$INPUT_TRIGGER_PHRASE"
if [[ "$text" == *"$trigger"* ]]; then
return 0
fi
@@ -104,11 +120,11 @@ runs:
USER_REQUEST=""
CONTEXT_INFO=""
case "${{ github.event_name }}" in
case "$EVENT_NAME" in
"issue_comment")
COMMENT_BODY="${{ github.event.comment.body }}"
ISSUE_TITLE="${{ github.event.issue.title }}"
ISSUE_NUMBER="${{ github.event.issue.number }}"
COMMENT_BODY="$EVENT_COMMENT_BODY"
ISSUE_TITLE="$EVENT_ISSUE_TITLE"
ISSUE_NUMBER="$EVENT_ISSUE_NUMBER"
if check_trigger "$COMMENT_BODY"; then
TRIGGER_FOUND="true"
@@ -118,9 +134,9 @@ runs:
;;
"pull_request_review_comment")
COMMENT_BODY="${{ github.event.comment.body }}"
PR_TITLE="${{ github.event.pull_request.title }}"
PR_NUMBER="${{ github.event.pull_request.number }}"
COMMENT_BODY="$EVENT_COMMENT_BODY"
PR_TITLE="$EVENT_PR_TITLE"
PR_NUMBER="$EVENT_PR_NUMBER"
if check_trigger "$COMMENT_BODY"; then
TRIGGER_FOUND="true"
@@ -130,9 +146,9 @@ runs:
;;
"pull_request_review")
REVIEW_BODY="${{ github.event.review.body }}"
PR_TITLE="${{ github.event.pull_request.title }}"
PR_NUMBER="${{ github.event.pull_request.number }}"
REVIEW_BODY="$EVENT_REVIEW_BODY"
PR_TITLE="$EVENT_PR_TITLE"
PR_NUMBER="$EVENT_PR_NUMBER"
if check_trigger "$REVIEW_BODY"; then
TRIGGER_FOUND="true"
@@ -142,17 +158,17 @@ runs:
;;
"issues")
ISSUE_BODY="${{ github.event.issue.body }}"
ISSUE_TITLE="${{ github.event.issue.title }}"
ISSUE_NUMBER="${{ github.event.issue.number }}"
ISSUE_BODY="$EVENT_ISSUE_BODY"
ISSUE_TITLE="$EVENT_ISSUE_TITLE"
ISSUE_NUMBER="$EVENT_ISSUE_NUMBER"
if check_trigger "$ISSUE_TITLE" || check_trigger "$ISSUE_BODY"; then
TRIGGER_FOUND="true"
USER_REQUEST="$ISSUE_BODY"
CONTEXT_INFO="Issue #$ISSUE_NUMBER: $ISSUE_TITLE"
elif [[ "${{ github.event.action }}" == "assigned" && -n "${{ inputs.assignee_trigger }}" ]]; then
ASSIGNEE="${{ github.event.assignee.login }}"
if [[ "$ASSIGNEE" == "${{ inputs.assignee_trigger }}" ]]; then
elif [[ "$EVENT_ACTION" == "assigned" && -n "$INPUT_ASSIGNEE_TRIGGER" ]]; then
ASSIGNEE="$EVENT_ASSIGNEE_LOGIN"
if [[ "$ASSIGNEE" == "$INPUT_ASSIGNEE_TRIGGER" ]]; then
TRIGGER_FOUND="true"
USER_REQUEST="$ISSUE_BODY"
CONTEXT_INFO="Issue #$ISSUE_NUMBER assigned to $ASSIGNEE: $ISSUE_TITLE"
@@ -162,9 +178,9 @@ runs:
esac
# Check for direct prompt override
if [[ -n "${{ inputs.direct_prompt }}" ]]; then
if [[ -n "$INPUT_DIRECT_PROMPT" ]]; then
TRIGGER_FOUND="true"
USER_REQUEST="${{ inputs.direct_prompt }}"
USER_REQUEST="$INPUT_DIRECT_PROMPT"
CONTEXT_INFO="Automated GitHub workflow"
fi
@@ -181,9 +197,9 @@ runs:
cat > /tmp/claude-action/github-context-prompt.txt << EOF
You are Claude Code, an AI assistant helping with GitHub workflows and code.
Repository: ${{ github.repository }}
Repository: $REPO_NAME
Context: $CONTEXT_INFO
Event: ${{ github.event_name }}
Event: $EVENT_NAME
User Request:
$USER_REQUEST
+81
View File
@@ -0,0 +1,81 @@
name: 'Gemini CLI Action'
description: 'Uses the Gemini CLI to automate software development tasks.'
author: 'Gemini'
inputs:
prompt:
description: 'A specific prompt to guide Gemini.'
required: false
default: 'You are a helpful assistant.'
GEMINI_API_KEY:
description: 'Your Gemini API key.'
required: true
OTLP_GCP_WIF_PROVIDER:
description: 'The workload identity provider for GCP authentication.'
required: false
OTLP_GOOGLE_CLOUD_PROJECT:
description: 'The Google Cloud project for telemetry.'
required: false
settings_json:
description: |
A JSON string to configure the Gemini CLI. This will be written to .gemini/settings.json.
To enable observability with Google Cloud, include:
{"telemetry": {"enabled": true, "target": "gcp"}, "sandbox": false}
required: false
version:
description: |
The version of @google/gemini-cli to execute.
Can be a specific version from npm (e.g., '0.1.0', 'latest'), a branch name (e.g., 'main'), or a commit hash.
required: false
default: 'latest'
runs:
using: "composite"
steps:
- name: Configure Gemini CLI
if: inputs.settings_json != ''
run: |
mkdir -p .gemini
echo "$SETTINGS_JSON" > .gemini/settings.json
shell: bash
env:
SETTINGS_JSON: ${{ inputs.settings_json }}
- name: Authenticate to Google Cloud for Telemetry
if: inputs.OTLP_GCP_WIF_PROVIDER != ''
id: auth
uses: 'google-github-actions/auth@v2'
with:
project_id: ${{ inputs.OTLP_GOOGLE_CLOUD_PROJECT }}
workload_identity_provider: ${{ inputs.OTLP_GCP_WIF_PROVIDER }}
- name: Install Gemini CLI
id: install
run: |
if [[ "${{ inputs.version }}" == "latest" || "${{ inputs.version }}" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9\.-]+)?(\+[a-zA-Z0-9\.-]+)?$ ]]; then
echo "Installing Gemini CLI from npm: @google/gemini-cli@${{ inputs.version }}"
npm install -g @google/gemini-cli@${{ inputs.version }}
else
echo "Installing Gemini CLI from GitHub: github:google-gemini/gemini-cli#${{ inputs.version }}"
npm install -g github:google-gemini/gemini-cli#${{ inputs.version }}
fi
echo "Verifying installation:"
if command -v gemini >/dev/null 2>&1; then
gemini --version || echo "Gemini CLI installed successfully (version command not available)"
else
echo "Error: Gemini CLI not found in PATH"
exit 1
fi
shell: bash
- name: Run Gemini CLI
run: |
gemini --yolo --prompt "$PROMPT"
shell: bash
env:
GEMINI_API_KEY: ${{ inputs.GEMINI_API_KEY }}
PROMPT: ${{ inputs.prompt }}
branding:
icon: 'terminal'
color: 'blue'
+7 -3
View File
@@ -1,4 +1,4 @@
name: Auto Issue Comment
name: Auto Issue Comment with PR Creation
on:
issues:
@@ -9,14 +9,18 @@ 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
with:
github-token: ${{ secrets.GH_TOKEN }}
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '@claude review this issue with multiple parallel running agents 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 use multi agents to review the applied 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. MAINLY IT SHOULD NOT IMPACT ON THE CURRENT SPEED OF EXECUTION of existing features, not increasing the overhead. **Please create a PR using gh tool with your changes**.'
})
+2 -1
View File
@@ -13,10 +13,11 @@ jobs:
- name: Add automated comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GH_TOKEN }}
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '@claude review this pull request with multiple parallel running agents 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 use multi agents to review the applied changes'
body: '@claude review this pull request and do a detailed analysis and fix this if the existing code doesn\'t have the solution implemented. Making sure it has backward compatibility, no existing features removed. After making those changes, again review the applied changes. Use @web to search if you dont know any information or to find the latest documentation or to find the latest version. Run the code if you think you need to run it to test it. Minimal code change to start with if required any changes. MAINLY IT SHOULD NOT IMPACT ON THE CURRENT SPEED OF EXECUTION of existing features, not increasing the overhead.'
})
+1
View File
@@ -11,6 +11,7 @@ on:
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
packages: write
+141 -20
View File
@@ -1,4 +1,4 @@
name: Claude Code
name: Claude Assistant
on:
issue_comment:
@@ -6,34 +6,155 @@ on:
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
types: [opened, assigned, labeled]
pull_request_review:
types: [submitted]
jobs:
claude:
claude-response:
# Prevent certain bots from triggering this action (but allow github-actions[bot] for auto-comments)
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
github.actor != 'dependabot[bot]' &&
github.actor != 'cursor[bot]' &&
github.actor != 'renovate[bot]' &&
!(contains(github.actor, '[bot]') && github.actor != 'github-actions[bot]')
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
contents: write
pull-requests: write
issues: write
actions: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude Code (OAuth)
id: claude
uses: grll/claude-code-action@beta
fetch-depth: 0
- uses: anthropics/claude-code-action@beta
with:
use_oauth: true
claude_access_token: ${{ secrets.CLAUDE_ACCESS_TOKEN }}
claude_refresh_token: ${{ secrets.CLAUDE_REFRESH_TOKEN }}
claude_expires_at: ${{ secrets.CLAUDE_EXPIRES_AT }}
claude_code_oauth_token: ${{ secrets.CLAUDE_ACCESS_TOKEN }}
github_token: ${{ secrets.GITHUB_TOKEN }}
trigger_phrase: "@claude"
allowed_tools: |
Bash(git:*)
Bash(python:*)
Bash(pip:*)
Bash(conda:*)
Bash(pytest:*)
Bash(gh:*)
Bash(python -m pytest:*)
Bash(python -m pip:*)
Bash(poetry:*)
View
GlobTool
GrepTool
BatchTool
Edit
Replace
mcp__github__get_issue
mcp__github__get_issue_comments
mcp__github__update_issue
timeout_minutes: 30
post-review-comment:
needs: claude-response
if: success() && needs.claude-response.result == 'success'
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
issues: write
steps:
- name: Check for existing review comment
id: check-comment
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GH_TOKEN }}
script: |
const reviewText = '@claude review if the changes made in the above branch are as per the requirements and make changes to the above branch if issues still exist.';
let comments = [];
let issueNumber;
try {
// Determine issue/PR number based on event type
if (context.eventName === 'pull_request_review_comment' || context.eventName === 'pull_request_review') {
issueNumber = context.payload.pull_request?.number || context.issue.number;
} else if (context.eventName === 'issue_comment' && context.payload.issue.pull_request) {
// This is a comment on a PR (not an issue)
issueNumber = context.payload.issue.number;
} else {
// This is a regular issue
issueNumber = context.issue.number;
}
comments = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber
});
// Look for Claude's completed review comments
const claudeReviewComments = comments.data.filter(comment =>
(comment.user.login === 'claude[bot]' || comment.body.includes('✅') || comment.body.includes('## Summary')) &&
!comment.body.includes('⏳') &&
!comment.body.includes('🔄') &&
!comment.body.includes('Loading...')
);
// Check if our review request comment already exists
const existingReviewRequest = comments.data.find(comment =>
comment.body.includes(reviewText)
);
// Post if Claude has completed a review AND we haven't posted the review request yet
const shouldPost = claudeReviewComments.length > 0 && !existingReviewRequest;
core.setOutput('should-post', shouldPost);
console.log(`Claude review completed: ${claudeReviewComments.length > 0}`);
console.log(`Review request exists: ${!!existingReviewRequest}`);
console.log(`Should post comment: ${shouldPost}`);
} catch (error) {
console.log('Error checking comments:', error);
core.setOutput('should-post', false); // If we can't check, don't post
}
- name: Wait 30 seconds before posting comment
if: steps.check-comment.outputs.should-post == 'true'
run: sleep 30
- name: Post review comment
if: steps.check-comment.outputs.should-post == 'true'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GH_TOKEN }}
script: |
let issueNumber;
let isPR = false;
// Determine issue/PR number and type based on event type
if (context.eventName === 'pull_request_review_comment' || context.eventName === 'pull_request_review') {
issueNumber = context.payload.pull_request?.number || context.issue.number;
isPR = true;
} else if (context.eventName === 'issue_comment' && context.payload.issue.pull_request) {
// This is a comment on a PR (not an issue)
issueNumber = context.payload.issue.number;
isPR = true;
} else {
// This is a regular issue - don't post review comment
issueNumber = context.issue.number;
isPR = false;
}
// Only post review comment on PRs, not regular issues
if (isPR) {
console.log(`Posting review comment on PR #${issueNumber}`);
await github.rest.issues.createComment({
issue_number: issueNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: '@claude review if the changes made in the above branch are as per the requirements and make changes to the above branch if issues still exist. MAINLY IT SHOULD NOT IMPACT ON THE CURRENT SPEED OF EXECUTION of existing features, not increasing the overhead.'
});
} else {
console.log(`Skipping review comment for regular issue #${issueNumber}`);
}
+2 -1
View File
@@ -10,6 +10,7 @@ jobs:
test:
name: Run tests and collect coverage
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout
@@ -40,7 +41,7 @@ jobs:
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-5-nano' }}" >> $GITHUB_ENV
echo "LOGLEVEL=DEBUG" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
+38 -28
View File
@@ -1,44 +1,54 @@
name: Daily Publish Docker
name: Publish Docker
on:
push:
branches:
- main
schedule:
- cron: '0 0 * * *'
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: 'Docker image tag (default: latest)'
required: false
default: 'latest'
jobs:
check-and-build:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Check last commit time
id: check_commit
run: |
last_commit_time=$(git log -1 --format=%ct)
current_time=$(date +%s)
time_diff=$((current_time - last_commit_time))
if [ $time_diff -ge 120 ] && [ $time_diff -lt 240 ]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
fi
uses: actions/checkout@v4
- name: Set up Docker Buildx
if: steps.check_commit.outputs.should_run == 'true'
uses: docker/setup-buildx-action@v1
uses: docker/setup-buildx-action@v3
- name: Log in to the GitHub Container Registry
if: steps.check_commit.outputs.should_run == 'true'
run: echo ${{ secrets.GH_TOKEN }} | docker login ghcr.io -u USERNAME --password-stdin
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/mervinpraison/praisonai
tags: |
type=raw,value=latest,enable=${{ github.event_name == 'release' }}
type=semver,pattern={{version}},enable=${{ github.event_name == 'release' }}
type=semver,pattern={{major}}.{{minor}},enable=${{ github.event_name == 'release' }}
type=raw,value=${{ github.event.inputs.tag || 'latest' }},enable=${{ github.event_name == 'workflow_dispatch' }}
- name: Build and push Docker image
if: steps.check_commit.outputs.should_run == 'true'
uses: docker/build-push-action@v2
uses: docker/build-push-action@v5
with:
context: .
file: ./docker/Dockerfile
push: true
tags: ghcr.io/mervinpraison/praisonai:latest
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -0,0 +1,76 @@
name: Gemini Automated Issue Triage
on:
issue_comment:
types: [created]
jobs:
triage-issue:
if: >
github.event_name == 'issue_comment' &&
!github.event.issue.pull_request &&
contains(github.event.comment.body, '@gemini triage') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR')
timeout-minutes: 5
permissions:
issues: write
contents: read
id-token: write
concurrency:
group: ${{ github.workflow }}-${{ github.event.issue.number }}
cancel-in-progress: true
runs-on: ubuntu-latest
steps:
- name: Generate GitHub App Token
id: generate_token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ steps.generate_token.outputs.token }}
- name: Run Gemini Issue Triage
uses: google-gemini/gemini-cli-action@main
env:
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
ISSUE_TITLE: ${{ github.event.issue.title }}
ISSUE_BODY: ${{ github.event.issue.body }}
ISSUE_NUMBER: ${{ github.event.issue.number }}
REPOSITORY: ${{ github.repository }}
with:
version: 0.1.8-rc.0
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
OTLP_GCP_WIF_PROVIDER: ${{ secrets.OTLP_GCP_WIF_PROVIDER }}
OTLP_GOOGLE_CLOUD_PROJECT: ${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}
settings_json: |
{
"coreTools": [
"run_shell_command(gh label list)",
"run_shell_command(gh issue edit)"
],
"telemetry": {
"enabled": true,
"target": "gcp"
},
"sandbox": false
}
prompt: |
You are an issue triage assistant. Analyze the current GitHub issue and apply the most appropriate existing labels.
Steps:
1. Run: `gh label list --limit 100` to get all available labels.
2. Review the issue title and body provided in the environment variables.
3. Select the most relevant labels from the existing labels, focusing on kind/*, area/*, and priority/*.
4. Apply the selected labels to this issue using: `gh issue edit ISSUE_NUMBER --add-label "label1,label2"`
Guidelines:
- Only use labels that already exist in the repository.
- Do not add comments or modify the issue content.
- Triage only the current issue.
- Assign all applicable kind/*, area/*, and priority/* labels based on the issue content.
+202
View File
@@ -0,0 +1,202 @@
name: Gemini Issue Review
on:
workflow_dispatch:
issue_comment:
types: [created]
permissions:
contents: write
issues: write
pull-requests: read
jobs:
review-issue:
if: >
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'issue_comment' &&
!github.event.issue.pull_request &&
contains(github.event.comment.body, '@gemini') &&
!contains(github.event.comment.body, '@gemini triage') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR'))
runs-on: ubuntu-latest
env:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
steps:
- name: Generate token
id: generate_token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ steps.generate_token.outputs.token }}
- name: Set up Git
run: |
git config --local user.email "[email protected]"
git config --local user.name "Gemini Bot"
- name: Get issue data
id: issue_data
env:
GH_TOKEN: ${{ steps.generate_token.outputs.token }}
# Pass user-controlled inputs via environment variables to prevent script injection (GHSL-2025-093)
EVENT_NAME: ${{ github.event_name }}
EVENT_ISSUE_NUMBER: ${{ github.event.issue.number }}
EVENT_COMMENT_BODY: ${{ github.event.comment.body }}
run: |
# Get issue number from event or context
if [ "$EVENT_NAME" = "issue_comment" ]; then
ISSUE_NUMBER="$EVENT_ISSUE_NUMBER"
elif [ "$EVENT_NAME" = "issues" ]; then
ISSUE_NUMBER="$EVENT_ISSUE_NUMBER"
else
echo "Unable to determine issue number"
exit 1
fi
# Get issue details
gh issue view $ISSUE_NUMBER --json title,body,labels,assignees > issue_details.json
# Extract additional instructions from comment if triggered by comment
ADDITIONAL_INSTRUCTIONS=""
if [ "$EVENT_NAME" = "issue_comment" ]; then
COMMENT_BODY="$EVENT_COMMENT_BODY"
ADDITIONAL_INSTRUCTIONS=$(echo "$COMMENT_BODY" | sed -n 's/.*@gemini[[:space:]]*\(.*\)/\1/p' | head -1)
fi
echo "ISSUE_NUMBER=$ISSUE_NUMBER" >> $GITHUB_OUTPUT
echo "ADDITIONAL_INSTRUCTIONS=$ADDITIONAL_INSTRUCTIONS" >> $GITHUB_OUTPUT
- name: Run Gemini CLI
uses: ./.github/actions/gemini
env:
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
ISSUE_NUMBER: ${{ steps.issue_data.outputs.ISSUE_NUMBER }}
ADDITIONAL_INSTRUCTIONS: ${{ steps.issue_data.outputs.ADDITIONAL_INSTRUCTIONS }}
REPOSITORY: ${{ github.repository }}
with:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
OTLP_GCP_WIF_PROVIDER: ${{ secrets.OTLP_GCP_WIF_PROVIDER }}
OTLP_GOOGLE_CLOUD_PROJECT: ${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}
prompt: |
You are a helpful GitHub issue assistant. Your task is to analyze and help with GitHub issues.
**Issue Details:**
- Issue Number: #${ISSUE_NUMBER}
- Repository: ${REPOSITORY}
- Issue URL: ${{ github.event.issue.html_url }}
**Additional Instructions:** ${ADDITIONAL_INSTRUCTIONS}
**CRITICAL: When making code modifications, follow this EXACT workflow:**
**STEP 1: Analyze the Issue**
- Use: `gh issue view ${ISSUE_NUMBER} --json title,body,labels,assignees`
- Analyze issue content thoroughly
- Search codebase for related files using `glob`, `search_file_content`, `list_directory`
**STEP 2: If Code Changes Are Needed**
Create a new branch with 'gemini/' prefix:
- Use: `git checkout -b gemini/issue-${ISSUE_NUMBER}-description`
- Example: `git checkout -b gemini/issue-123-fix-sequential-tools`
**STEP 3: Make Code Modifications**
- Use `read_file` to examine existing code
- Use `write_file` or `replace` to make changes
- Use `search_file_content` to find related code
- Make focused, targeted changes to fix the issue
**STEP 4: Test Changes (if applicable)**
- Run relevant tests if test files exist
- Use `run_shell_command` to execute test commands
**STEP 5: Commit and Push Changes**
- Use: `git add .` (or specific files)
- Use: `git commit -m "Gemini: [Issue #${ISSUE_NUMBER}] Brief description of fix"`
- Use: `git push -u origin gemini/issue-${ISSUE_NUMBER}-description`
**STEP 6: Create Pull Request**
- Use: `gh pr create --title "Fix #${ISSUE_NUMBER}: Issue description" --body "Fixes #${ISSUE_NUMBER}\n\nSummary of changes:\n- Change 1\n- Change 2" --head gemini/issue-${ISSUE_NUMBER}-description --base main`
- This will return a PR URL like: https://github.com/repo/pull/123
**STEP 7: Comment on Issue with Results**
Use: `gh issue comment ${ISSUE_NUMBER} -b "MESSAGE"`
**Your final comment MUST include:**
- Summary of what was analyzed
- What changes were made (if any)
- Link to the created PR (if applicable)
- Brief explanation of the solution
**Example final comment:**
```
Hi! I've analyzed and fixed this issue.
**Problem:** Sequential tool calling was getting stuck after first tool call.
**Solution:** Added proper prompt handling after each tool call in the Ollama model integration.
**Changes Made:**
- Modified `src/praisonai-agents/ollama-sequential.py`
- Added continuation prompts for multi-step tool execution
**Pull Request:** https://github.com/MervinPraison/PraisonAI/pull/856
The fix is ready for review. Please test and let me know if you encounter any issues!
```
**IMPORTANT NOTES:**
- Always create branches with 'gemini/' prefix
- Always include issue number in branch name and commit message
- Always create PR that references the issue
- Always provide PR link in your final response
- Use the GITHUB_TOKEN environment variable for authentication
Please proceed with helping resolve this issue following this exact workflow.
settings_json: |
{
"coreTools": [
"run_shell_command(echo)",
"run_shell_command(gh issue view)",
"run_shell_command(gh issue comment)",
"run_shell_command(gh issue list)",
"run_shell_command(gh issue edit)",
"run_shell_command(gh pr create)",
"run_shell_command(gh pr view)",
"run_shell_command(gh pr list)",
"run_shell_command(cat)",
"run_shell_command(head)",
"run_shell_command(tail)",
"run_shell_command(grep)",
"run_shell_command(find)",
"run_shell_command(git checkout)",
"run_shell_command(git add)",
"run_shell_command(git commit)",
"run_shell_command(git push)",
"run_shell_command(git status)",
"run_shell_command(git branch)",
"list_directory",
"read_file",
"read_many_files",
"write_file",
"replace",
"glob",
"search_file_content",
"web_fetch",
"google_web_search",
"save_memory"
],
"telemetry": {
"enabled": false,
"otlpGcpWifProvider": "${{ secrets.OTLP_GCP_WIF_PROVIDER }}",
"googleCloudProject": "${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}"
}
}
+248
View File
@@ -0,0 +1,248 @@
name: Gemini PR Review
on:
issue_comment:
types: [created]
workflow_dispatch:
inputs:
pr_number:
description: 'PR number to review'
required: true
type: number
jobs:
review-pr:
if: >
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
contains(github.event.comment.body, '@gemini') &&
(github.event.comment.author_association == 'OWNER' ||
github.event.comment.author_association == 'MEMBER' ||
github.event.comment.author_association == 'COLLABORATOR'))
timeout-minutes: 15
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
pull-requests: write
issues: write
steps:
- name: Generate GitHub App Token
id: generate_token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.PRIVATE_KEY }}
- name: Determine checkout ref
id: checkout_ref
run: |
if [ "${{ github.event_name }}" = "issue_comment" ]; then
echo "ref=refs/pull/${{ github.event.issue.number }}/head" >> "$GITHUB_OUTPUT"
else
echo "ref=${{ github.event.pull_request.head.sha }}" >> "$GITHUB_OUTPUT"
fi
- name: Checkout PR code
uses: actions/checkout@v4
with:
token: ${{ steps.generate_token.outputs.token }}
ref: ${{ steps.checkout_ref.outputs.ref }}
fetch-depth: 0
- name: Get PR details
id: get_pr
env:
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
# Pass user-controlled inputs via environment variables to prevent script injection (GHSL-2025-093)
EVENT_NAME: ${{ github.event_name }}
EVENT_INPUTS_PR_NUMBER: ${{ github.event.inputs.pr_number }}
EVENT_ISSUE_NUMBER: ${{ github.event.issue.number }}
EVENT_PR_NUMBER: ${{ github.event.pull_request.number }}
EVENT_COMMENT_BODY: ${{ github.event.comment.body }}
run: |
if [ "$EVENT_NAME" = "workflow_dispatch" ]; then
PR_NUMBER=$EVENT_INPUTS_PR_NUMBER
elif [ "$EVENT_NAME" = "issue_comment" ]; then
PR_NUMBER=$EVENT_ISSUE_NUMBER
else
PR_NUMBER=$EVENT_PR_NUMBER
fi
echo "pr_number=$PR_NUMBER" >> "$GITHUB_OUTPUT"
# Extract additional instructions from comment (if triggered by comment)
ADDITIONAL_INSTRUCTIONS=""
if [ "$EVENT_NAME" = "issue_comment" ]; then
COMMENT_BODY="$EVENT_COMMENT_BODY"
ADDITIONAL_INSTRUCTIONS=$(echo "$COMMENT_BODY" | sed 's/.*@gemini//' | xargs)
fi
echo "additional_instructions=$ADDITIONAL_INSTRUCTIONS" >> "$GITHUB_OUTPUT"
# Get PR details
PR_DATA=$(gh pr view $PR_NUMBER --json title,body,additions,deletions,changedFiles,baseRefName,headRefName)
echo "pr_data=$PR_DATA" >> "$GITHUB_OUTPUT"
# Get file changes
CHANGED_FILES=$(gh pr diff $PR_NUMBER --name-only)
echo "changed_files<<EOF" >> "$GITHUB_OUTPUT"
echo "$CHANGED_FILES" >> "$GITHUB_OUTPUT"
echo "EOF" >> "$GITHUB_OUTPUT"
- name: Run Gemini PR Review
uses: ./.github/actions/gemini
env:
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
PR_NUMBER: ${{ steps.get_pr.outputs.pr_number }}
PR_DATA: ${{ steps.get_pr.outputs.pr_data }}
CHANGED_FILES: ${{ steps.get_pr.outputs.changed_files }}
ADDITIONAL_INSTRUCTIONS: ${{ steps.get_pr.outputs.additional_instructions }}
REPOSITORY: ${{ github.repository }}
with:
version: 0.1.8-rc.0
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
OTLP_GCP_WIF_PROVIDER: ${{ secrets.OTLP_GCP_WIF_PROVIDER }}
OTLP_GOOGLE_CLOUD_PROJECT: ${{ secrets.OTLP_GOOGLE_CLOUD_PROJECT }}
settings_json: |
{
"coreTools": [
"run_shell_command(echo)",
"run_shell_command(gh pr view)",
"run_shell_command(gh pr diff)",
"run_shell_command(gh pr comment)",
"run_shell_command(gh pr list)",
"run_shell_command(cat)",
"run_shell_command(head)",
"run_shell_command(tail)",
"run_shell_command(grep)",
"run_shell_command(find)",
"run_shell_command(git checkout)",
"run_shell_command(git add)",
"run_shell_command(git commit)",
"run_shell_command(git push)",
"run_shell_command(git status)",
"run_shell_command(git branch)",
"run_shell_command(git fetch)",
"list_directory",
"read_file",
"read_many_files",
"write_file",
"replace",
"glob",
"search_file_content",
"web_fetch",
"google_web_search",
"save_memory"
],
"telemetry": {
"enabled": false,
"target": "gcp"
},
"sandbox": false
}
prompt: |
You are an expert code reviewer and AI assistant for Pull Requests. You can review code AND make modifications to improve the PR.
**PR Details:**
- PR Number: #$PR_NUMBER
- Repository: $REPOSITORY
- Additional Instructions: $ADDITIONAL_INSTRUCTIONS
**CRITICAL: When making code modifications, follow this EXACT workflow:**
**STEP 1: Analyze the PR**
- Use: `echo "$PR_DATA"` to get PR details (JSON format)
- Use: `echo "$CHANGED_FILES"` to get changed files list
- Use: `gh pr diff ${PR_NUMBER}` to see the full diff
- Use: `gh pr view ${PR_NUMBER} --json title,body,headRefName` to get PR info
- Analyze the code changes thoroughly
**STEP 2: If Code Improvements Are Needed**
**IMPORTANT:** DO NOT create a new branch! Work on the EXISTING PR branch.
- Use: `git fetch origin` to get latest changes
- Get PR branch name: `gh pr view ${PR_NUMBER} --json headRefName`
- Switch to PR branch: `git checkout BRANCH_NAME` (use actual branch name from PR)
- Use: `git pull origin BRANCH_NAME` to get latest PR changes
**STEP 3: Make Code Modifications**
- Use `read_file` to examine existing code
- Use `write_file` or `replace` to make improvements
- Use `search_file_content` to find related code
- Make focused, targeted improvements to the PR
**STEP 4: Test Changes (if applicable)**
- Run relevant tests if test files exist
- Use `run_shell_command` to execute test commands
**STEP 5: Commit and Push Changes to EXISTING PR Branch**
- Use: `git add .` (or specific files)
- Use: `git commit -m "Gemini: [PR #${PR_NUMBER}] Brief description of improvements"`
- Use: `git push origin BRANCH_NAME` (push to EXISTING PR branch)
**STEP 6: Review and Comment on PR**
Write comprehensive review and post comment with your analysis and any improvements made.
Use: `gh pr comment ${PR_NUMBER} -b "MESSAGE"`
Review Guidelines:
- Focus on code quality, security, performance, and maintainability
- Check for common issues: potential bugs, security vulnerabilities, performance bottlenecks
- Verify error handling and edge cases
- Look for code style and best practices
- Comment on architecture and design decisions if significant
- Be constructive and specific in feedback
- Highlight both issues and positive aspects
- Suggest improvements with examples when possible
Review Areas:
- **Security**: Authentication, authorization, input validation, data sanitization
- **Performance**: Algorithms, database queries, caching, resource usage
- **Reliability**: Error handling, logging, testing coverage, edge cases
- **Maintainability**: Code structure, documentation, naming conventions
- **Functionality**: Logic correctness, requirements fulfillment
Output Format:
Structure your review using this exact format with markdown:
## 📋 Review Summary
Provide a brief 2-3 sentence overview of the PR and overall assessment.
## 🔍 General Feedback
- List general observations about code quality
- Mention overall patterns or architectural decisions
- Highlight positive aspects of the implementation
- Note any recurring themes across files
## 🎯 Specific Feedback
Only include sections below that have actual issues. If there are no issues in a priority category, omit that entire section.
### 🔴 Critical
(Only include this section if there are critical issues)
Issues that must be addressed before merging (security vulnerabilities, breaking changes, major bugs):
- **File: `filename:line`** - Description of critical issue with specific recommendation
### 🟡 High
(Only include this section if there are high priority issues)
Important issues that should be addressed (performance problems, design flaws, significant bugs):
- **File: `filename:line`** - Description of high priority issue with suggested fix
### 🟢 Medium
(Only include this section if there are medium priority issues)
Improvements that would enhance code quality (style issues, minor optimizations, better practices):
- **File: `filename:line`** - Description of medium priority improvement
### 🔵 Low
(Only include this section if there are suggestions)
Nice-to-have improvements and suggestions (documentation, naming, minor refactoring):
- **File: `filename:line`** - Description of suggestion or enhancement
**Note**: If no specific issues are found in any category, simply state "No specific issues identified in this review."
## ✅ Highlights
(Only include this section if there are positive aspects to highlight)
- Mention specific good practices or implementations
- Acknowledge well-written code sections
- Note improvements from previous versions
---
*Review completed by Gemini CLI*
+1 -1
View File
@@ -29,7 +29,7 @@ jobs:
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-5-nano' }}" >> $GITHUB_ENV
echo "LOGLEVEL=DEBUG" >> $GITHUB_ENV
- name: Install dependencies
+10 -4
View File
@@ -26,6 +26,10 @@ on:
jobs:
comprehensive-test:
runs-on: ubuntu-latest
timeout-minutes: 15
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
OPENAI_MODEL_NAME: gpt-4o-mini
strategy:
matrix:
python-version: ["3.11"]
@@ -54,11 +58,13 @@ jobs:
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
- name: Set environment variables
- name: Verify environment variables
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
if [ -n "$OPENAI_API_KEY" ]; then
echo "✅ OPENAI_API_KEY is set (length: ${#OPENAI_API_KEY})"
else
echo "⚠️ OPENAI_API_KEY is NOT set"
fi
- name: Run Comprehensive Test Suite
run: |
+10 -9
View File
@@ -9,6 +9,7 @@ on:
jobs:
test-core:
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
matrix:
python-version: [3.11]
@@ -33,7 +34,7 @@ jobs:
cd src/praisonai
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system duckduckgo_search
uv pip install --system pytest pytest-asyncio pytest-cov
uv pip install --system pytest pytest-asyncio pytest-cov pytest-timeout
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
@@ -41,13 +42,13 @@ jobs:
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-5-nano' }}" >> $GITHUB_ENV
echo "LOGLEVEL=DEBUG" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
# Also export to current shell session for immediate availability
export OPENAI_API_KEY="${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}"
export OPENAI_API_BASE="${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}"
export OPENAI_MODEL_NAME="${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}"
export OPENAI_MODEL_NAME="${{ secrets.OPENAI_MODEL_NAME || 'gpt-5-nano' }}"
export LOGLEVEL=DEBUG
# Verify immediate availability
echo "🔧 Immediate verification in same step:"
@@ -125,7 +126,7 @@ jobs:
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}
OPENAI_API_BASE: ${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}
OPENAI_MODEL_NAME: ${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}
OPENAI_MODEL_NAME: ${{ secrets.OPENAI_MODEL_NAME || 'gpt-5-nano' }}
LOGLEVEL: DEBUG
run: |
echo "🔍 Testing PraisonAI API key usage directly..."
@@ -151,7 +152,7 @@ jobs:
return 'INVALID_TYPE'
print('🔧 Direct PraisonAI API Key Check:')
env_api_key = os.environ.get(\\"OPENAI_API_KEY\\", \\"NOT_SET\\")
env_api_key = os.environ.get(\"OPENAI_API_KEY\", \"NOT_SET\")
print(f'Environment OPENAI_API_KEY: {get_key_display_value(env_api_key)}...')
from praisonai import PraisonAI
@@ -163,9 +164,9 @@ jobs:
from praisonai.inc.models import PraisonAIModel
print('\\\\n🧪 Testing PraisonAIModel with explicit API key (CrewAI method):')
print('\\n🧪 Testing PraisonAIModel with explicit API key (CrewAI method):')
model_with_explicit_key = PraisonAIModel(
model='openai/gpt-4o-mini',
model='openai/gpt-5-nano',
base_url=praisonai.config_list[0].get('base_url'),
api_key=api_key_from_config # This will be a string from praisonai.config_list
)
@@ -250,7 +251,7 @@ jobs:
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}
OPENAI_API_BASE: ${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}
OPENAI_MODEL_NAME: ${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}
OPENAI_MODEL_NAME: ${{ secrets.OPENAI_MODEL_NAME || 'gpt-5-nano' }}
LOGLEVEL: DEBUG
run: |
echo "🧪 Running legacy tests with real API key..."
@@ -261,7 +262,7 @@ jobs:
export OPENAI_API_KEY="$OPENAI_API_KEY"
export OPENAI_API_BASE="$OPENAI_API_BASE"
export OPENAI_MODEL_NAME="$OPENAI_MODEL_NAME"
cd src/praisonai && python -m pytest tests/test.py -v --tb=short --disable-warnings
cd src/praisonai && python -m pytest tests/test.py -v --tb=short --disable-warnings -m "not real" --timeout=60
- name: Upload coverage reports to Codecov
if: matrix.python-version == '3.11'
+13 -2
View File
@@ -13,6 +13,7 @@ on:
jobs:
test-examples:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout code
@@ -41,8 +42,11 @@ jobs:
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-5-nano' }}" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
echo "PRAISONAI_TELEMETRY_DISABLED=true" >> $GITHUB_ENV
echo "PRAISONAI_DISABLE_TELEMETRY=true" >> $GITHUB_ENV
echo "DO_NOT_TRACK=true" >> $GITHUB_ENV
- name: Test Key Example Scripts
run: |
@@ -73,6 +77,7 @@ jobs:
performance-test:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout code
@@ -97,6 +102,12 @@ jobs:
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
- name: Set environment variables
run: |
echo "PRAISONAI_TELEMETRY_DISABLED=true" >> $GITHUB_ENV
echo "PRAISONAI_DISABLE_TELEMETRY=true" >> $GITHUB_ENV
echo "DO_NOT_TRACK=true" >> $GITHUB_ENV
- name: Run Performance Benchmarks
run: |
echo "🏃 Running performance benchmarks..."
@@ -161,4 +172,4 @@ jobs:
with:
name: performance-report
path: performance_report.md
retention-days: 30
retention-days: 5
+2 -1
View File
@@ -24,6 +24,7 @@ on:
jobs:
framework-tests:
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
matrix:
python-version: [3.11]
@@ -55,7 +56,7 @@ jobs:
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-5-nano' }}" >> $GITHUB_ENV
- name: Test ${{ matrix.framework }} Framework
run: |
+1
View File
@@ -26,6 +26,7 @@ jobs:
real-tests:
runs-on: ubuntu-latest
if: ${{ github.event.inputs.confirm_costs == 'true' && github.event.inputs.framework != 'none' }}
timeout-minutes: 15
strategy:
matrix:
+6 -5
View File
@@ -5,6 +5,7 @@ on: [push, pull_request]
jobs:
quick-test:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout code
@@ -26,7 +27,7 @@ jobs:
cd src/praisonai
uv pip install --system ."[ui,gradio,api,agentops,google,openai,anthropic,cohere,chat,code,realtime,call,crewai,autogen]"
uv pip install --system duckduckgo_search
uv pip install --system pytest pytest-asyncio pytest-cov
uv pip install --system pytest pytest-asyncio pytest-cov pytest-timeout
# Install knowledge dependencies from praisonai-agents
uv pip install --system "praisonaiagents[knowledge]"
@@ -34,7 +35,7 @@ jobs:
run: |
echo "OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY || 'sk-test-key-for-github-actions-testing-only-not-real' }}" >> $GITHUB_ENV
echo "OPENAI_API_BASE=${{ secrets.OPENAI_API_BASE || 'https://api.openai.com/v1' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-4o-mini' }}" >> $GITHUB_ENV
echo "OPENAI_MODEL_NAME=${{ secrets.OPENAI_MODEL_NAME || 'gpt-5-nano' }}" >> $GITHUB_ENV
echo "LOGLEVEL=DEBUG" >> $GITHUB_ENV
echo "PYTHONPATH=${{ github.workspace }}/src/praisonai-agents:$PYTHONPATH" >> $GITHUB_ENV
@@ -315,8 +316,8 @@ jobs:
try:
from praisonai.inc.models import PraisonAIModel
# Test PraisonAIModel with openai/gpt-4o-mini (from YAML)
model = PraisonAIModel(model='openai/gpt-4o-mini')
# Test PraisonAIModel with openai/gpt-5-nano (from YAML)
model = PraisonAIModel(model='openai/gpt-5-nano')
print('🤖 PraisonAIModel Configuration:')
print(f' model: {model.model}')
@@ -488,7 +489,7 @@ jobs:
- name: Run Legacy Example Tests
run: |
cd src/praisonai && python -m pytest tests/test.py -v --tb=short --disable-warnings
cd src/praisonai && python -m pytest tests/test.py -v --tb=short --disable-warnings -m "not real" --timeout=60
continue-on-error: true
- name: Upload coverage reports to Codecov
+6 -1
View File
@@ -75,4 +75,9 @@ agents/praisonaiagents/praisonaiagents.egg-info
# Local Netlify folder
.netlify
.qodo
CopilotKit*
CopilotKit*
.gemini
issue_details.json
# MCP Registry tokens
.mcpregistry_*
+1957 -82
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -14,9 +14,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
# Note: praisonai is installed from PyPI - remove version pin to use latest available
RUN pip install --no-cache-dir \
flask \
"praisonai>=2.2.48" \
praisonai \
"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.48" \
"praisonai>=2.3.46" \
"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.48" \
"praisonai>=2.3.46" \
"praisonai[ui]" \
"praisonai[chat]" \
"praisonai[realtime]" \
+25
View File
@@ -0,0 +1,25 @@
# Dockerfile for PraisonAI Serve API
# Deploy to Railway, Render, Fly.io, or any container platform
#
# Build: docker build -f Dockerfile.serve -t praisonai-serve .
# Run: docker run -p 8005:8005 -e OPENAI_API_KEY=sk-xxx praisonai-serve
FROM python:3.11-slim
WORKDIR /app
# Install dependencies
RUN pip install --no-cache-dir praisonai praisonaiagents
# Copy agents configuration
COPY agents.yaml .
# Expose the API port
EXPOSE 8005
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8005/health || exit 1
# Start the API server
CMD ["praisonai", "serve", "agents.yaml", "--host", "0.0.0.0", "--port", "8005"]
+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.48" \
"praisonai>=2.3.46" \
"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.48`
- PraisonAI: `>=2.2.95`
- 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.48" "praisonaiagents==0.0.92"
RUN pip install "praisonai==2.2.95" "praisonaiagents==0.0.92"
```
## 🌐 Production Deployment
+4 -15
View File
@@ -137,22 +137,11 @@ services:
POSTGRES_USER: praisonai
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-praisonai_dev_pass}
volumes:
database:
image: postgres:15-alpine
environment:
POSTGRES_DB: praisonai_dev
POSTGRES_USER: praisonai
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-praisonai_dev_pass}
volumes:
- postgres_data:/var/lib/postgresql/data
read_only: true
tmpfs:
- /tmp
- /var/tmp
ports:
- "5432:5432"
networks:
- postgres_data:/var/lib/postgresql/data
read_only: true
tmpfs:
- /tmp
- /var/tmp
ports:
- "5432:5432"
networks:
+49
View File
@@ -0,0 +1,49 @@
# PraisonAI Examples
This folder contains examples for PraisonAI. For detailed documentation, visit [docs.praison.ai](https://docs.praison.ai).
## Structure
```
examples/
├── python/ # Python examples
│ ├── agents/ # Agent examples (single, multi, router, etc.)
│ ├── workflows/ # Workflow patterns (routing, parallel, loop)
│ ├── tools/ # Custom tools examples
│ ├── mcp/ # MCP protocol examples
│ ├── memory/ # Memory and sessions
│ ├── code/ # Code editing and external CLI tools
│ └── ...
├── yaml/ # YAML workflow examples
└── cookbooks/ # Complete use-case examples
```
## Quick Links
| Category | Examples | Docs |
|----------|----------|------|
| **Agents** | [python/agents/](python/agents/) | [📖](https://docs.praison.ai/concepts/agents) |
| **Workflows** | [python/workflows/](python/workflows/) | [📖](https://docs.praison.ai/features/workflows) |
| **Model Router** | [python/agents/router-agent-cost-optimization.py](python/agents/router-agent-cost-optimization.py) | [📖](https://docs.praison.ai/features/model-router) |
| **MCP** | [python/mcp/](python/mcp/) | [📖](https://docs.praison.ai/mcp) |
| **Memory** | [python/memory/](python/memory/) | [📖](https://docs.praison.ai/concepts/memory) |
| **Tools** | [python/tools/](python/tools/) | [📖](https://docs.praison.ai/tools) |
| **Code** | [python/code/](python/code/) | [📖](https://docs.praison.ai/code) |
| **YAML** | [yaml/](yaml/) | [📖](https://docs.praison.ai/features/yaml-workflows) |
## Running Examples
```bash
# Install PraisonAI
pip install praisonai
# Set API key
export OPENAI_API_KEY=your_key_here
# Run an example
python examples/python/agents/single-agent.py
```
## CLI Commands
See the main [README.md](../README.md#-cli--no-code-interface) for all CLI commands.
@@ -0,0 +1,89 @@
"""
Fast Context with Agent - Basic Example
This is the simplest way to use Fast Context with an Agent.
Just set fast_context=True and the agent will automatically
have access to rapid code search capabilities.
Fast Context provides:
- 10-20x faster code search than traditional methods
- Parallel execution (8 concurrent searches)
- Automatic caching for repeated queries
- Seamless integration with Agent workflows
"""
from praisonaiagents import Agent
def main():
print("=" * 60)
print("Agent with Fast Context - Basic Example")
print("=" * 60)
# Create an agent with Fast Context enabled
# This is the simplest configuration
agent = Agent(
name="CodeAssistant",
instructions="You are a helpful code assistant.",
fast_context=True, # Enable Fast Context
fast_context_path=".", # Search in current directory
verbose=False
)
print("\n✓ Agent created with Fast Context enabled")
print(f" - fast_context_enabled: {agent.fast_context_enabled}")
print(f" - fast_context_path: {agent.fast_context_path}")
print(f" - fast_context_model: {agent.fast_context_model}")
# Use delegate_to_fast_context to search code
print("\n" + "-" * 60)
print("Searching for 'class Agent' in the codebase...")
print("-" * 60)
context = agent.delegate_to_fast_context("class Agent")
if context:
print(f"\n✓ Found relevant code!")
print(f" Context length: {len(context)} characters")
print("\nPreview of found context:")
print("-" * 40)
# Show first 500 characters
preview = context[:500]
print(preview)
if len(context) > 500:
print("...")
else:
print("\n✗ No relevant code found")
# Another search example
print("\n" + "-" * 60)
print("Searching for 'def chat' in the codebase...")
print("-" * 60)
context = agent.delegate_to_fast_context("def chat")
if context:
print(f"\n✓ Found relevant code!")
print(f" Context length: {len(context)} characters")
else:
print("\n✗ No relevant code found")
# Access FastContext directly for more control
print("\n" + "-" * 60)
print("Direct FastContext access for advanced usage...")
print("-" * 60)
fc = agent.fast_context
if fc:
result = fc.search("import")
print(f"\n✓ Direct search for 'import':")
print(f" Files found: {result.total_files}")
print(f" Search time: {result.search_time_ms}ms")
print(f" From cache: {result.from_cache}")
print("\n" + "=" * 60)
print("Fast Context makes code search instant for your agents!")
print("=" * 60)
if __name__ == "__main__":
main()
+84
View File
@@ -0,0 +1,84 @@
"""
Example 1: Basic Fast Context Usage
This example demonstrates the basic usage of Fast Context for rapid code search.
Fast Context is 10-20x faster than traditional sequential search because it:
- Executes up to 8 tool calls in parallel
- Limits search to 4 turns maximum
- Uses a lightweight model optimized for search
"""
from praisonaiagents.context.fast import FastContext
import time
def main():
print("=" * 70)
print("Fast Context - Basic Usage Example")
print("=" * 70)
# Create FastContext instance pointing to the praisonai-agents codebase
fc = FastContext(
workspace_path="/Users/praison/praisonai-package/src/praisonai-agents"
)
# Example 1: Simple pattern search
print("\n1. Simple Pattern Search")
print("-" * 40)
start = time.perf_counter()
result = fc.search("def chat")
elapsed = (time.perf_counter() - start) * 1000
print(f" Query: 'def chat'")
print(f" Files found: {result.total_files}")
print(f" Search time: {result.search_time_ms}ms (total: {elapsed:.0f}ms)")
print(f" Turns used: {result.turns_used}")
print(f" Tool calls: {result.total_tool_calls}")
if result.files:
print("\n Top matches:")
for f in result.files[:3]:
print(f" - {f.path}")
for lr in f.line_ranges[:2]:
print(f" Lines {lr.start}-{lr.end}")
# Example 2: Search for class definitions
print("\n2. Search for Class Definitions")
print("-" * 40)
result = fc.search("class Agent")
print(f" Query: 'class Agent'")
print(f" Files found: {result.total_files}")
print(f" Search time: {result.search_time_ms}ms")
if result.files:
print("\n Files containing 'class Agent':")
for f in result.files[:5]:
print(f" - {f.path} (relevance: {f.relevance_score:.2f})")
# Example 3: Search for imports
print("\n3. Search for Specific Imports")
print("-" * 40)
result = fc.search("from typing import")
print(f" Query: 'from typing import'")
print(f" Files found: {result.total_files}")
print(f" Search time: {result.search_time_ms}ms")
# Example 4: Get formatted context string
print("\n4. Get Formatted Context for Agent")
print("-" * 40)
context = fc.get_context_for_agent("authentication", max_files=3)
print(f" Context length: {len(context)} characters")
print(f" Preview:")
preview = context[:300].replace('\n', '\n ')
print(f" {preview}...")
print("\n" + "=" * 70)
print("Fast Context provides rapid, parallel code search!")
print("=" * 70)
if __name__ == "__main__":
main()
@@ -0,0 +1,113 @@
"""
Example 2: Parallel vs Sequential Search Comparison
This example demonstrates the speed advantage of Fast Context's parallel
execution compared to traditional sequential search.
Key insight: Fast Context executes up to 8 searches simultaneously,
making it 5-10x faster for complex queries.
"""
import time
import os
from praisonaiagents.context.fast import FastContext
from praisonaiagents.context.fast.search_tools import grep_search, glob_search
WORKSPACE = "/Users/praison/praisonai-package/src/praisonai-agents"
def sequential_search(queries: list) -> dict:
"""Traditional sequential search - one query at a time."""
results = {}
for query in queries:
results[query] = grep_search(
search_path=WORKSPACE,
pattern=query,
max_results=20
)
return results
def parallel_search_with_fast_context(queries: list) -> dict:
"""Fast Context parallel search - multiple queries at once."""
fc = FastContext(workspace_path=WORKSPACE)
results = {}
for query in queries:
result = fc.search(query)
results[query] = result
return results
def main():
print("=" * 70)
print("Parallel vs Sequential Search Comparison")
print("=" * 70)
# Define multiple search queries
queries = [
"def __init__",
"class Agent",
"async def",
"import logging",
"from typing",
]
print(f"\nSearching for {len(queries)} patterns in the codebase...")
print(f"Workspace: {WORKSPACE}")
# Sequential search
print("\n1. Sequential Search (Traditional)")
print("-" * 40)
start = time.perf_counter()
seq_results = sequential_search(queries)
seq_time = (time.perf_counter() - start) * 1000
total_seq_matches = sum(len(r) for r in seq_results.values())
print(f" Total matches: {total_seq_matches}")
print(f" Time: {seq_time:.0f}ms")
# Fast Context search (with caching disabled for fair comparison)
print("\n2. Fast Context Search (Parallel)")
print("-" * 40)
fc = FastContext(workspace_path=WORKSPACE, cache_enabled=False)
start = time.perf_counter()
fc_results = {}
for query in queries:
fc_results[query] = fc.search(query)
fc_time = (time.perf_counter() - start) * 1000
total_fc_matches = sum(r.total_files for r in fc_results.values())
print(f" Total files found: {total_fc_matches}")
print(f" Time: {fc_time:.0f}ms")
# Comparison
print("\n3. Comparison")
print("-" * 40)
speedup = seq_time / fc_time if fc_time > 0 else float('inf')
print(f" Sequential: {seq_time:.0f}ms")
print(f" Fast Context: {fc_time:.0f}ms")
print(f" Speedup: {speedup:.1f}x faster")
# Detailed results
print("\n4. Results by Query")
print("-" * 40)
for query in queries:
seq_count = len(seq_results[query])
fc_count = fc_results[query].total_files
fc_ms = fc_results[query].search_time_ms
print(f" '{query}':")
print(f" Sequential: {seq_count} matches")
print(f" Fast Context: {fc_count} files in {fc_ms}ms")
print("\n" + "=" * 70)
print(f"Fast Context is {speedup:.1f}x faster due to parallel execution!")
print("=" * 70)
if __name__ == "__main__":
main()
+132
View File
@@ -0,0 +1,132 @@
"""
Example 3: Caching Performance Demonstration
This example shows how Fast Context's caching dramatically improves
performance for repeated queries.
Key benefits:
- First query: Full search execution
- Subsequent queries: Instant cache hit (0ms search time)
- Configurable TTL (time-to-live)
"""
import time
from praisonaiagents.context.fast import FastContext
WORKSPACE = "/Users/praison/praisonai-package/src/praisonai-agents"
def main():
print("=" * 70)
print("Fast Context Caching Performance")
print("=" * 70)
# Create FastContext with caching enabled
fc = FastContext(
workspace_path=WORKSPACE,
cache_enabled=True,
cache_ttl=300 # 5 minutes
)
query = "def execute"
print(f"\nQuery: '{query}'")
print(f"Cache TTL: 300 seconds")
# First search - cache miss
print("\n1. First Search (Cache Miss)")
print("-" * 40)
start = time.perf_counter()
result1 = fc.search(query)
elapsed1 = (time.perf_counter() - start) * 1000
print(f" Files found: {result1.total_files}")
print(f" From cache: {result1.from_cache}")
print(f" Search time: {result1.search_time_ms}ms")
print(f" Total time: {elapsed1:.1f}ms")
# Second search - cache hit
print("\n2. Second Search (Cache Hit)")
print("-" * 40)
start = time.perf_counter()
result2 = fc.search(query)
elapsed2 = (time.perf_counter() - start) * 1000
print(f" Files found: {result2.total_files}")
print(f" From cache: {result2.from_cache}")
print(f" Search time: {result2.search_time_ms}ms")
print(f" Total time: {elapsed2:.1f}ms")
# Third search - still cached
print("\n3. Third Search (Still Cached)")
print("-" * 40)
start = time.perf_counter()
result3 = fc.search(query)
elapsed3 = (time.perf_counter() - start) * 1000
print(f" Files found: {result3.total_files}")
print(f" From cache: {result3.from_cache}")
print(f" Total time: {elapsed3:.1f}ms")
# Clear cache and search again
print("\n4. After Cache Clear")
print("-" * 40)
fc.clear_cache()
print(" Cache cleared!")
start = time.perf_counter()
result4 = fc.search(query)
elapsed4 = (time.perf_counter() - start) * 1000
print(f" Files found: {result4.total_files}")
print(f" From cache: {result4.from_cache}")
print(f" Search time: {result4.search_time_ms}ms")
print(f" Total time: {elapsed4:.1f}ms")
# Performance comparison
print("\n5. Performance Summary")
print("-" * 40)
cache_speedup = elapsed1 / elapsed2 if elapsed2 > 0 else float('inf')
print(f" First search (no cache): {elapsed1:.1f}ms")
print(f" Cached searches: ~{elapsed2:.1f}ms")
print(f" Cache speedup: {cache_speedup:.0f}x faster")
# Multiple different queries
print("\n6. Multiple Query Caching")
print("-" * 40)
queries = ["class Agent", "async def", "import os", "def __init__"]
# First pass - populate cache
print(" First pass (populating cache):")
start = time.perf_counter()
for q in queries:
fc.search(q)
first_pass = (time.perf_counter() - start) * 1000
print(f" Time: {first_pass:.0f}ms")
# Second pass - all cached
print(" Second pass (all cached):")
start = time.perf_counter()
for q in queries:
r = fc.search(q)
assert r.from_cache, f"Expected cache hit for '{q}'"
second_pass = (time.perf_counter() - start) * 1000
print(f" Time: {second_pass:.1f}ms")
multi_speedup = first_pass / second_pass if second_pass > 0 else float('inf')
print(f" Speedup: {multi_speedup:.0f}x faster")
print("\n" + "=" * 70)
print("Caching provides instant results for repeated queries!")
print("=" * 70)
if __name__ == "__main__":
main()
+112
View File
@@ -0,0 +1,112 @@
"""
Example 4: Agent Integration with Fast Context
This example shows how to use Fast Context integrated with the Agent class
for automatic code search delegation.
Benefits:
- Seamless integration with existing Agent workflows
- Automatic context injection for code-related queries
- Configurable via Agent parameters or environment variables
"""
from praisonaiagents import Agent
WORKSPACE = "/Users/praison/praisonai-package/src/praisonai-agents"
def main():
print("=" * 70)
print("Agent Integration with Fast Context")
print("=" * 70)
# Create an agent with Fast Context enabled
print("\n1. Creating Agent with Fast Context")
print("-" * 40)
agent = Agent(
name="CodeAssistant",
instructions="You are a helpful code assistant that can search and analyze code.",
fast_context=True,
fast_context_path=WORKSPACE,
fast_context_model="gpt-4o-mini",
fast_context_max_turns=4,
fast_context_parallelism=8,
fast_context_timeout=30.0,
verbose=False
)
print(f" Agent name: {agent.name}")
print(f" Fast Context enabled: {agent.fast_context_enabled}")
print(f" Fast Context path: {agent.fast_context_path}")
print(f" Fast Context model: {agent.fast_context_model}")
print(f" Max turns: {agent.fast_context_max_turns}")
print(f" Parallelism: {agent.fast_context_parallelism}")
# Use delegate_to_fast_context for code search
print("\n2. Delegating Code Search to Fast Context")
print("-" * 40)
queries = [
"find the Agent class definition",
"search for authentication handlers",
"locate memory management code",
]
for query in queries:
print(f"\n Query: '{query}'")
context = agent.delegate_to_fast_context(query)
if context:
# Show preview of context
lines = context.split('\n')
preview_lines = lines[:5]
print(f" Found context ({len(context)} chars):")
for line in preview_lines:
print(f" {line[:60]}{'...' if len(line) > 60 else ''}")
if len(lines) > 5:
print(f" ... and {len(lines) - 5} more lines")
else:
print(" No relevant code found")
# Access the FastContext instance directly
print("\n3. Direct FastContext Access")
print("-" * 40)
fc = agent.fast_context
if fc:
result = fc.search("def chat")
print(f" Direct search for 'def chat':")
print(f" Files found: {result.total_files}")
print(f" Search time: {result.search_time_ms}ms")
for f in result.files[:3]:
print(f" - {f.path}")
# Show configuration options
print("\n4. Configuration Options")
print("-" * 40)
print(" Agent parameters:")
print(" - fast_context=True # Enable Fast Context")
print(" - fast_context_path='.' # Workspace path")
print(" - fast_context_model='gpt-4o-mini' # Search model")
print(" - fast_context_max_turns=4 # Max search turns")
print(" - fast_context_parallelism=8 # Parallel calls")
print(" - fast_context_timeout=30.0 # Timeout (seconds)")
print("\n Environment variables:")
print(" - FAST_CONTEXT_MODEL")
print(" - FAST_CONTEXT_MAX_TURNS")
print(" - FAST_CONTEXT_PARALLELISM")
print(" - FAST_CONTEXT_TIMEOUT")
print(" - FAST_CONTEXT_CACHE")
print(" - FAST_CONTEXT_CACHE_TTL")
print("\n" + "=" * 70)
print("Fast Context integrates seamlessly with Agent for code search!")
print("=" * 70)
if __name__ == "__main__":
main()
@@ -0,0 +1,121 @@
"""
Example 5: File and Symbol Indexing
This example demonstrates the file and symbol indexing capabilities
that power Fast Context's rapid search.
Features:
- FileIndexer: Index file metadata for fast lookups
- SymbolIndexer: Extract code symbols (functions, classes, imports)
- Support for Python, JavaScript, TypeScript, Go, Rust, Java
"""
import time
from praisonaiagents.context.fast.indexer import (
FileIndexer,
SymbolIndexer,
SymbolType
)
WORKSPACE = "/Users/praison/praisonai-package/src/praisonai-agents"
def main():
print("=" * 70)
print("File and Symbol Indexing")
print("=" * 70)
# File Indexer
print("\n1. File Indexer")
print("-" * 40)
start = time.perf_counter()
file_indexer = FileIndexer(workspace_path=WORKSPACE)
file_count = file_indexer.index()
file_time = (time.perf_counter() - start) * 1000
print(f" Indexed {file_count} files in {file_time:.0f}ms")
stats = file_indexer.get_stats()
print(f" Total size: {stats['total_size_mb']} MB")
print(f" Extensions: {list(stats['extensions'].keys())[:5]}")
# Find files by pattern
print("\n Finding files by pattern:")
py_files = file_indexer.find_by_pattern("**/*.py")
print(f" - Python files (*.py): {len(py_files)}")
agent_files = file_indexer.find_by_pattern("**/agent*.py")
print(f" - Agent files (agent*.py): {len(agent_files)}")
# Find files by name
print("\n Finding files by name:")
init_files = file_indexer.find_by_name("__init__.py", exact=True)
print(f" - __init__.py files: {len(init_files)}")
agent_matches = file_indexer.find_by_name("agent")
print(f" - Files containing 'agent': {len(agent_matches)}")
# Symbol Indexer
print("\n2. Symbol Indexer")
print("-" * 40)
start = time.perf_counter()
symbol_indexer = SymbolIndexer(workspace_path=WORKSPACE)
symbol_count = symbol_indexer.index()
symbol_time = (time.perf_counter() - start) * 1000
print(f" Indexed {symbol_count} symbols in {symbol_time:.0f}ms")
stats = symbol_indexer.get_stats()
print(f" Files indexed: {stats['total_files']}")
print(f" Symbols by type:")
for sym_type, count in stats['by_type'].items():
print(f" - {sym_type}: {count}")
# Find symbols by name
print("\n Finding symbols by name:")
agent_symbols = symbol_indexer.find_by_name("Agent", exact=True)
print(f" - 'Agent' (exact): {len(agent_symbols)} symbols")
for sym in agent_symbols[:3]:
print(f" {sym.symbol_type.value}: {sym.name} in {sym.file_path}:{sym.line_number}")
chat_symbols = symbol_indexer.find_by_name("chat")
print(f" - 'chat' (partial): {len(chat_symbols)} symbols")
for sym in chat_symbols[:3]:
print(f" {sym.symbol_type.value}: {sym.name} in {sym.file_path}:{sym.line_number}")
# Find symbols by type
print("\n Finding symbols by type:")
classes = symbol_indexer.find_by_type(SymbolType.CLASS)
print(f" - Classes: {len(classes)}")
for cls in classes[:5]:
print(f" class {cls.name} in {cls.file_path}:{cls.line_number}")
functions = symbol_indexer.find_by_type(SymbolType.FUNCTION)
print(f" - Functions: {len(functions)}")
methods = symbol_indexer.find_by_type(SymbolType.METHOD)
print(f" - Methods: {len(methods)}")
imports = symbol_indexer.find_by_type(SymbolType.IMPORT)
print(f" - Imports: {len(imports)}")
# Performance comparison
print("\n3. Performance Summary")
print("-" * 40)
print(f" File indexing: {file_time:.0f}ms for {file_count} files")
print(f" Symbol indexing: {symbol_time:.0f}ms for {symbol_count} symbols")
print(f" Files per second: {file_count / (file_time / 1000):.0f}")
print(f" Symbols per second: {symbol_count / (symbol_time / 1000):.0f}")
print("\n" + "=" * 70)
print("Indexing enables instant lookups for files and symbols!")
print("=" * 70)
if __name__ == "__main__":
main()
+163
View File
@@ -0,0 +1,163 @@
"""
Example 6: Context Injection for Agents
This example demonstrates how Fast Context results can be formatted
and injected into agent prompts for better code understanding.
Features:
- Multiple format styles (markdown, xml, plain)
- Token budget management
- Precision over recall (avoid context pollution)
"""
from praisonaiagents.context.fast import FastContext
from praisonaiagents.context.fast.context_injector import (
ContextInjector,
InjectionConfig,
inject_fast_context
)
WORKSPACE = "/Users/praison/praisonai-package/src/praisonai-agents"
def main():
print("=" * 70)
print("Context Injection for Agents")
print("=" * 70)
# Search for code
fc = FastContext(workspace_path=WORKSPACE)
result = fc.search("class Agent")
print(f"\nSearch results: {result.total_files} files found")
# Markdown format (default)
print("\n1. Markdown Format")
print("-" * 40)
config_md = InjectionConfig(
max_tokens=2000,
max_files=3,
max_lines_per_file=20,
format_style="markdown",
include_line_numbers=True,
include_file_content=True,
prioritize_precision=True
)
injector_md = ContextInjector(config_md)
md_context = injector_md.format_context(result)
print(f" Format: Markdown")
print(f" Length: {len(md_context)} chars (~{len(md_context)//4} tokens)")
print(f" Preview:")
for line in md_context.split('\n')[:10]:
print(f" {line[:70]}")
print(" ...")
# XML format
print("\n2. XML Format")
print("-" * 40)
config_xml = InjectionConfig(
max_tokens=2000,
max_files=3,
format_style="xml",
prioritize_precision=True
)
injector_xml = ContextInjector(config_xml)
xml_context = injector_xml.format_context(result)
print(f" Format: XML")
print(f" Length: {len(xml_context)} chars")
print(f" Preview:")
for line in xml_context.split('\n')[:10]:
print(f" {line[:70]}")
print(" ...")
# Plain text format
print("\n3. Plain Text Format")
print("-" * 40)
config_plain = InjectionConfig(
max_tokens=2000,
max_files=3,
format_style="plain"
)
injector_plain = ContextInjector(config_plain)
plain_context = injector_plain.format_context(result)
print(f" Format: Plain")
print(f" Length: {len(plain_context)} chars")
print(f" Preview:")
for line in plain_context.split('\n')[:8]:
print(f" {line[:70]}")
print(" ...")
# Inject into prompts
print("\n4. Injecting into Prompts")
print("-" * 40)
system_prompt = "You are a helpful code assistant."
user_message = "Explain how the Agent class works."
injected = inject_fast_context(
result=result,
system_prompt=system_prompt,
user_message=user_message,
max_tokens=1500,
format_style="markdown"
)
print(f" Original system prompt: {len(system_prompt)} chars")
print(f" Injected system prompt: {len(injected['system_prompt'])} chars")
print(f" User message unchanged: {injected['user_message'] == user_message}")
# Token budget management
print("\n5. Token Budget Management")
print("-" * 40)
budgets = [500, 1000, 2000, 4000]
for budget in budgets:
config = InjectionConfig(max_tokens=budget, max_files=10)
injector = ContextInjector(config)
context = injector.format_context(result)
estimated_tokens = len(context) // 4
print(f" Budget: {budget} tokens -> {len(context)} chars (~{estimated_tokens} tokens)")
# Precision mode
print("\n6. Precision vs Recall")
print("-" * 40)
# High precision (fewer, more relevant results)
config_precision = InjectionConfig(
max_tokens=2000,
max_files=5,
prioritize_precision=True
)
injector_precision = ContextInjector(config_precision)
precision_context = injector_precision.format_context(result)
# Lower precision (more results)
config_recall = InjectionConfig(
max_tokens=2000,
max_files=10,
prioritize_precision=False
)
injector_recall = ContextInjector(config_recall)
recall_context = injector_recall.format_context(result)
print(f" High precision mode: {len(precision_context)} chars")
print(f" High recall mode: {len(recall_context)} chars")
print(f" Precision mode is more focused for better agent understanding")
print("\n" + "=" * 70)
print("Context injection formats search results for optimal agent use!")
print("=" * 70)
if __name__ == "__main__":
main()
+213
View File
@@ -0,0 +1,213 @@
"""
Example 7: Search Tools Deep Dive
This example demonstrates the individual search tools that power Fast Context:
- grep_search: Pattern-based search with regex support
- glob_search: File pattern matching
- read_file: Read file contents with line ranges
- list_directory: Directory listing with filtering
"""
import time
from praisonaiagents.context.fast.search_tools import (
grep_search,
glob_search,
read_file,
list_directory
)
WORKSPACE = "/Users/praison/praisonai-package/src/praisonai-agents"
def main():
print("=" * 70)
print("Search Tools Deep Dive")
print("=" * 70)
# grep_search
print("\n1. grep_search - Pattern Search")
print("-" * 40)
# Simple pattern
start = time.perf_counter()
results = grep_search(
search_path=WORKSPACE,
pattern="def __init__",
max_results=10
)
elapsed = (time.perf_counter() - start) * 1000
print(f" Pattern: 'def __init__'")
print(f" Matches: {len(results)}")
print(f" Time: {elapsed:.0f}ms")
if results:
print(f" First match: {results[0]['path']}:{results[0]['line_number']}")
# Regex pattern
results = grep_search(
search_path=WORKSPACE,
pattern=r"class \w+Agent",
is_regex=True,
max_results=10
)
print(f"\n Regex: 'class \\w+Agent'")
print(f" Matches: {len(results)}")
for r in results[:3]:
print(f" - {r['path']}:{r['line_number']}: {r['content'][:50]}...")
# Case sensitive
results_sensitive = grep_search(
search_path=WORKSPACE,
pattern="Agent",
case_sensitive=True,
max_results=50
)
results_insensitive = grep_search(
search_path=WORKSPACE,
pattern="agent",
case_sensitive=False,
max_results=50
)
print(f"\n Case sensitive 'Agent': {len(results_sensitive)} matches")
print(f" Case insensitive 'agent': {len(results_insensitive)} matches")
# With context lines
results = grep_search(
search_path=WORKSPACE,
pattern="class Agent:",
context_lines=2,
max_results=3
)
print(f"\n With 2 context lines:")
if results:
print(f" {results[0]['path']}:")
if results[0].get('context'):
for line in results[0]['context'].split('\n')[:5]:
print(f" {line[:60]}")
# glob_search
print("\n2. glob_search - File Pattern Matching")
print("-" * 40)
# Find Python files
start = time.perf_counter()
results = glob_search(
search_path=WORKSPACE,
pattern="**/*.py",
max_results=100
)
elapsed = (time.perf_counter() - start) * 1000
print(f" Pattern: '**/*.py'")
print(f" Files found: {len(results)}")
print(f" Time: {elapsed:.0f}ms")
# Find specific files
results = glob_search(
search_path=WORKSPACE,
pattern="**/agent*.py",
max_results=20
)
print(f"\n Pattern: '**/agent*.py'")
print(f" Files found: {len(results)}")
for r in results[:5]:
print(f" - {r['path']} ({r['size']} bytes)")
# Find test files
results = glob_search(
search_path=WORKSPACE,
pattern="**/test_*.py",
max_results=50
)
print(f"\n Pattern: '**/test_*.py'")
print(f" Test files: {len(results)}")
# read_file
print("\n3. read_file - Read File Contents")
print("-" * 40)
# Read entire file
result = read_file(
filepath=f"{WORKSPACE}/praisonaiagents/__init__.py",
max_lines=20
)
print(f" File: praisonaiagents/__init__.py")
print(f" Success: {result['success']}")
print(f" Lines: {result.get('total_lines', 'N/A')}")
if result['success']:
lines = result['content'].split('\n')[:5]
print(f" Preview:")
for line in lines:
print(f" {line[:60]}")
# Read specific line range
result = read_file(
filepath=f"{WORKSPACE}/praisonaiagents/agent/agent.py",
start_line=1,
end_line=20
)
print(f"\n File: agent/agent.py (lines 1-20)")
print(f" Success: {result['success']}")
if result['success']:
lines = result['content'].split('\n')[:5]
print(f" Preview:")
for line in lines:
print(f" {line[:60]}")
# Read with context
result = read_file(
filepath=f"{WORKSPACE}/praisonaiagents/agent/agent.py",
start_line=100,
end_line=105,
context_lines=3
)
print(f"\n File: agent/agent.py (lines 100-105 with 3 context lines)")
print(f" Success: {result['success']}")
# list_directory
print("\n4. list_directory - Directory Listing")
print("-" * 40)
# List root
result = list_directory(
dir_path=WORKSPACE,
recursive=False,
max_entries=20
)
print(f" Directory: {WORKSPACE}")
print(f" Success: {result['success']}")
print(f" Entries: {len(result.get('entries', []))}")
dirs = [e for e in result.get('entries', []) if e.get('is_dir')]
files = [e for e in result.get('entries', []) if not e.get('is_dir')]
print(f" Directories: {len(dirs)}")
print(f" Files: {len(files)}")
# List recursive with depth limit
result = list_directory(
dir_path=f"{WORKSPACE}/praisonaiagents",
recursive=True,
max_depth=2,
max_entries=50
)
print(f"\n Directory: praisonaiagents (recursive, depth=2)")
print(f" Entries: {len(result.get('entries', []))}")
# Show directory structure
print(f" Structure:")
for entry in result.get('entries', [])[:10]:
prefix = "📁" if entry.get('is_dir') else "📄"
print(f" {prefix} {entry['name']}")
print("\n" + "=" * 70)
print("These search tools power Fast Context's rapid code search!")
print("=" * 70)
if __name__ == "__main__":
main()
@@ -0,0 +1,227 @@
"""
Example 8: Comprehensive Benchmark
This example provides a comprehensive benchmark comparing Fast Context
performance against traditional search approaches.
Metrics measured:
- Search latency
- Throughput (queries per second)
- Cache effectiveness
- Parallel execution speedup
"""
import time
import statistics
from praisonaiagents.context.fast import FastContext
from praisonaiagents.context.fast.search_tools import grep_search
from praisonaiagents.context.fast.indexer import FileIndexer, SymbolIndexer
WORKSPACE = "/Users/praison/praisonai-package/src/praisonai-agents"
def benchmark_search_latency():
"""Benchmark search latency."""
print("\n1. Search Latency Benchmark")
print("-" * 50)
fc = FastContext(workspace_path=WORKSPACE, cache_enabled=False)
queries = [
"def __init__",
"class Agent",
"import logging",
"async def",
"from typing import",
]
# Warm up
fc.search("warmup")
# Benchmark each query
latencies = []
for query in queries:
times = []
for _ in range(3): # 3 runs per query
start = time.perf_counter()
fc.search(query)
elapsed = (time.perf_counter() - start) * 1000
times.append(elapsed)
avg = statistics.mean(times)
latencies.append(avg)
print(f" '{query}': {avg:.1f}ms (min: {min(times):.1f}, max: {max(times):.1f})")
print(f"\n Average latency: {statistics.mean(latencies):.1f}ms")
print(f" Median latency: {statistics.median(latencies):.1f}ms")
print(f" P95 latency: {sorted(latencies)[int(len(latencies)*0.95)]:.1f}ms")
def benchmark_throughput():
"""Benchmark queries per second."""
print("\n2. Throughput Benchmark")
print("-" * 50)
fc = FastContext(workspace_path=WORKSPACE, cache_enabled=True)
queries = ["def", "class", "import", "return", "if", "for", "while", "try"]
# Cold run (no cache)
fc.clear_cache()
start = time.perf_counter()
for query in queries:
fc.search(query)
cold_time = time.perf_counter() - start
cold_qps = len(queries) / cold_time
print(f" Cold (no cache):")
print(f" Queries: {len(queries)}")
print(f" Time: {cold_time*1000:.0f}ms")
print(f" Throughput: {cold_qps:.1f} queries/second")
# Warm run (cached)
start = time.perf_counter()
for _ in range(10): # 10 iterations
for query in queries:
fc.search(query)
warm_time = time.perf_counter() - start
warm_qps = (len(queries) * 10) / warm_time
print(f"\n Warm (cached):")
print(f" Queries: {len(queries) * 10}")
print(f" Time: {warm_time*1000:.0f}ms")
print(f" Throughput: {warm_qps:.0f} queries/second")
print(f"\n Cache speedup: {warm_qps/cold_qps:.0f}x")
def benchmark_cache_effectiveness():
"""Benchmark cache hit rate and speedup."""
print("\n3. Cache Effectiveness Benchmark")
print("-" * 50)
fc = FastContext(workspace_path=WORKSPACE, cache_enabled=True)
fc.clear_cache()
queries = ["Agent", "chat", "memory", "tool", "execute"]
# First pass - cache misses
miss_times = []
for query in queries:
start = time.perf_counter()
result = fc.search(query)
elapsed = (time.perf_counter() - start) * 1000
miss_times.append(elapsed)
assert not result.from_cache
# Second pass - cache hits
hit_times = []
for query in queries:
start = time.perf_counter()
result = fc.search(query)
elapsed = (time.perf_counter() - start) * 1000
hit_times.append(elapsed)
assert result.from_cache
avg_miss = statistics.mean(miss_times)
avg_hit = statistics.mean(hit_times)
print(f" Cache miss (first query): {avg_miss:.1f}ms avg")
print(f" Cache hit (repeat query): {avg_hit:.2f}ms avg")
print(f" Cache speedup: {avg_miss/avg_hit:.0f}x faster")
print(f" Time saved per cached query: {avg_miss - avg_hit:.1f}ms")
def benchmark_parallel_execution():
"""Benchmark parallel vs sequential execution."""
print("\n4. Parallel Execution Benchmark")
print("-" * 50)
queries = ["def", "class", "import", "return", "async"]
# Sequential (one at a time)
start = time.perf_counter()
for query in queries:
grep_search(WORKSPACE, query, max_results=20)
seq_time = (time.perf_counter() - start) * 1000
# Parallel (Fast Context)
fc = FastContext(workspace_path=WORKSPACE, cache_enabled=False)
start = time.perf_counter()
for query in queries:
fc.search(query)
par_time = (time.perf_counter() - start) * 1000
print(f" Sequential: {seq_time:.0f}ms")
print(f" Parallel (Fast Context): {par_time:.0f}ms")
print(f" Speedup: {seq_time/par_time:.1f}x")
def benchmark_indexing():
"""Benchmark indexing performance."""
print("\n5. Indexing Performance Benchmark")
print("-" * 50)
# File indexing
start = time.perf_counter()
file_indexer = FileIndexer(workspace_path=WORKSPACE)
file_count = file_indexer.index()
file_time = (time.perf_counter() - start) * 1000
print(f" File Indexer:")
print(f" Files: {file_count}")
print(f" Time: {file_time:.0f}ms")
print(f" Rate: {file_count/(file_time/1000):.0f} files/second")
# Symbol indexing
start = time.perf_counter()
symbol_indexer = SymbolIndexer(workspace_path=WORKSPACE)
symbol_count = symbol_indexer.index()
symbol_time = (time.perf_counter() - start) * 1000
print(f"\n Symbol Indexer:")
print(f" Symbols: {symbol_count}")
print(f" Time: {symbol_time:.0f}ms")
print(f" Rate: {symbol_count/(symbol_time/1000):.0f} symbols/second")
# Lookup performance
start = time.perf_counter()
for _ in range(100):
file_indexer.find_by_pattern("**/*.py")
lookup_time = (time.perf_counter() - start) * 1000
print(f"\n Lookup Performance:")
print(f" 100 pattern lookups: {lookup_time:.1f}ms")
print(f" Per lookup: {lookup_time/100:.2f}ms")
def main():
print("=" * 70)
print("Fast Context Comprehensive Benchmark")
print("=" * 70)
print(f"\nWorkspace: {WORKSPACE}")
benchmark_search_latency()
benchmark_throughput()
benchmark_cache_effectiveness()
benchmark_parallel_execution()
benchmark_indexing()
print("\n" + "=" * 70)
print("Summary")
print("=" * 70)
print("""
Fast Context provides:
✓ Sub-100ms search latency for most queries
✓ 100+ queries/second with caching
✓ 100x+ speedup for cached queries
✓ 2-5x speedup from parallel execution
✓ 1000+ files/second indexing rate
These benchmarks demonstrate why Fast Context is ideal for
rapid code search in AI agent workflows.
""")
if __name__ == "__main__":
main()
@@ -26,14 +26,14 @@
"\n",
"### ✨ Key Benefits:\n",
"- 🚀 **Scalable & Customizable** – Industry-agnostic design \n",
"- 💰 **Cost-Effective** – Runs on GPT-4o-mini \n",
"- 💰 **Cost-Effective** – Runs on gpt-5-nano \n",
"- 🛠️ **Production-Ready** – Realistic automation framework \n",
"- 🔄 **Complete Pipeline** – End-to-end flow\n",
"\n",
"---\n",
"\n",
"### 🔧 Technologies:\n",
"**PraisonAI** • **OpenAI GPT-4o-mini** • **Python** • **SQLite** \n",
"**PraisonAI** • **OpenAI gpt-5-nano** • **Python** • **SQLite** \n",
"**Multi-Agent Architecture**\n",
"\n",
"---\n",
@@ -100,7 +100,7 @@
"text": [
"📦 Dependencies installed!\n",
"🔄 Using PraisonAI Multi-Agent Framework\n",
"🤖 Powered by OpenAI GPT-4o-mini\n"
"🤖 Powered by OpenAI gpt-5-nano\n"
]
}
],
@@ -116,7 +116,7 @@
"\n",
"print(\"📦 Dependencies installed!\")\n",
"print(\"🔄 Using PraisonAI Multi-Agent Framework\")\n",
"print(\"🤖 Powered by OpenAI GPT-4o-mini\")"
"print(\"🤖 Powered by OpenAI gpt-5-nano\")"
]
},
{
@@ -5102,7 +5102,7 @@
"\n",
"🎊 BLENDER PRODUCTION STUDIO COMPLETE!\n",
"🎬 17-Agent AI System Successfully Executed\n",
"🤖 Powered by PraisonAI + OpenAI GPT-4o-mini\n"
"🤖 Powered by PraisonAI + OpenAI gpt-5-nano\n"
]
}
],
@@ -5149,7 +5149,7 @@
"\n",
"print(\"\\n🎊 BLENDER PRODUCTION STUDIO COMPLETE!\")\n",
"print(\"🎬 17-Agent AI System Successfully Executed\")\n",
"print(\"🤖 Powered by PraisonAI + OpenAI GPT-4o-mini\")"
"print(\"🤖 Powered by PraisonAI + OpenAI gpt-5-nano\")"
]
}
],
@@ -182,7 +182,7 @@
" ]\n",
" for turn in range(max_turns):\n",
" response = client.chat.completions.create(\n",
" model=\"gpt-4o-mini\",\n",
" model=\"gpt-5-nano\",\n",
" messages=history,\n",
" max_tokens=500\n",
" )\n",
@@ -2642,7 +2642,7 @@
"\n",
"\ud83c\udf8a SEMANTIC NETWORK ANALYSIS COMPLETE!\n",
"\ud83c\udf10 Cross-platform profile discovery and analysis\n",
"\ud83e\udd16 Powered by PraisonAI + OpenAI GPT-4o-mini\n"
"\ud83e\udd16 Powered by PraisonAI + OpenAI gpt-5-nano\n"
]
}
],
@@ -2687,7 +2687,7 @@
"\n",
"print(\"\\n\ud83c\udf8a SEMANTIC NETWORK ANALYSIS COMPLETE!\")\n",
"print(\"\ud83c\udf10 Cross-platform profile discovery and analysis\")\n",
"print(\"\ud83e\udd16 Powered by PraisonAI + OpenAI GPT-4o-mini\")"
"print(\"\ud83e\udd16 Powered by PraisonAI + OpenAI gpt-5-nano\")"
]
},
{
@@ -1262,7 +1262,7 @@
"\n",
"🎊 AI SHOPPING ASSISTANT ACTIVE!\n",
"🛒 Ready to help customers with natural language shopping\n",
"🤖 Powered by PraisonAI + OpenAI GPT-4o-mini\n"
"🤖 Powered by PraisonAI + OpenAI gpt-5-nano\n"
]
}
],
@@ -1305,7 +1305,7 @@
"\n",
"print(\"\\n🎊 AI SHOPPING ASSISTANT ACTIVE!\")\n",
"print(\"🛒 Ready to help customers with natural language shopping\")\n",
"print(\"🤖 Powered by PraisonAI + OpenAI GPT-4o-mini\")"
"print(\"🤖 Powered by PraisonAI + OpenAI gpt-5-nano\")"
]
},
{
@@ -29,7 +29,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
@@ -71,7 +71,6 @@
"import pandas as pd\n",
"\n",
"print(\"📦 Dependencies installed!\")\n",
"print(\"🔄 Converting from AGNO → PraisonAI\")\n",
"print(\"🎯 Building Job Hunting Agent System\")"
]
},
@@ -156,7 +156,7 @@
" - Property comparison\n",
" - Cost of living and taxes\n",
" - First-time homebuyer guidance\n",
"llm: gpt-4o\n",
"llm: gpt-5-nano\n",
"verbosity: true\n",
"format: markdown\n",
"\"\"\"\n"
@@ -188,7 +188,7 @@
"Help users evaluate neighborhoods, estimate mortgage payments, compare homes, and understand homeownership costs.\n",
"Explain clearly, format in markdown, and be friendly but professional.\n",
"\"\"\",\n",
" llm=\"gpt-4o\",\n",
" llm=\"gpt-5-nano\",\n",
" verbose=True,\n",
" markdown=True\n",
")\n"
@@ -311,7 +311,7 @@
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭───────────────────────────────────────────────────── Task ──────────────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> You are an expert health advisor using the GPT-4o Mini model. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> You are an expert health advisor using the gpt-5-nano Mini model. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"background-color: #272822\"> </span><span style=\"color: #f8f8f2; text-decoration-color: #f8f8f2; background-color: #272822\">Based on the following air quality conditions in Mumbai, Maharashtra, India:</span><span style=\"background-color: #272822\"> </span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
@@ -340,7 +340,7 @@
],
"text/plain": [
"\u001b[36m╭─\u001b[0m\u001b[36m────────────────────────────────────────────────────\u001b[0m\u001b[36m Task \u001b[0m\u001b[36m─────────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
"\u001b[36m│\u001b[0m You are an expert health advisor using the GPT-4o Mini model. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m You are an expert health advisor using the gpt-5-nano Mini model. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[48;2;39;40;34m \u001b[0m\u001b[38;2;248;248;242;48;2;39;40;34mBased on the following air quality conditions in Mumbai, Maharashtra, India:\u001b[0m\u001b[48;2;39;40;34m \u001b[0m\u001b[48;2;39;40;34m \u001b[0m \u001b[36m│\u001b[0m\n",
@@ -519,7 +519,7 @@
" aqi_data = aqi_data.data # Convert to dict\n",
"\n",
" prompt = f\"\"\"\n",
" You are an expert health advisor using the GPT-4o Mini model.\n",
" You are an expert health advisor using the gpt-5-nano Mini model.\n",
"\n",
" Based on the following air quality conditions in {user_city}, {user_state}, {user_country}:\n",
" - Overall AQI: {aqi_data.get('aqi', 'N/A')}\n",
@@ -193,7 +193,7 @@
" goal=\"Evaluate hackathon projects through video demonstrations\",\n",
" backstory=\"\"\"You are an expert hackathon judge. You give fair scores and detailed feedback\n",
" on technical complexity, innovation, presentation, and UX.\"\"\",\n",
" llm=\"gpt-4o-mini\",\n",
" llm=\"gpt-5-nano\",\n",
" self_reflect=False\n",
")"
],
@@ -65,7 +65,7 @@
"source": [
"from llama_index.llms.openai import OpenAI\n",
"\n",
"llm = OpenAI(model=\"gpt-4o-mini\", api_key=\"Enter your api key here\") # Replace with your OpenAI API key\n"
"llm = OpenAI(model=\"gpt-5-nano\", api_key=\"Enter your api key here\") # Replace with your OpenAI API key\n"
]
},
{
@@ -0,0 +1,293 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "ZOWgx2fYqW8T"
},
"source": [
"# GitHub Repository Insights with PraisonAIAgents"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XgJdLRiIqZ2L"
},
"source": [
"This notebook demonstrates how to explore and analyze GitHub repositories using PraisonAIAgents in Google Colab. You can query repository issues, pull requests, and activity patterns with natural language, leveraging the power of agentic tools—all without leaving your notebook."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Y_koMT6qzxne"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Programming_Code_Analysis_Agents/GitHub_Repository_Insights.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2ey7zWAJrIPx"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"id": "_xFH-iLTxzd8"
},
"outputs": [],
"source": [
"!pip install praisonaiagents openai requests --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Kzty0zxzsbZ_"
},
"source": [
"# Set Up Key"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"id": "HCVP5fmvx2hH"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Set your GitHub token here\n",
"GITHUB_TOKEN = \"your-github-token\" # <-- Replace with your actual token\n",
"\n",
"# Set your OpenAI API key here (required by PraisonAIAgents, even if not used for LLM)\n",
"OPENAI_API_KEY = \"your-openai-api-key\" # <-- Replace with your actual OpenAI API key\n",
"\n",
"# Set environment variable for OpenAI\n",
"os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "10BTLbF4s_f-"
},
"source": [
"# Import Libraries"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"id": "_sLahvfXyEb0"
},
"outputs": [],
"source": [
"from praisonaiagents import Agent\n",
"import requests\n",
"from IPython.display import display, Markdown"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "GRftdghxtUDs"
},
"source": [
"# Custom Tool"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"id": "nT11EFNNyIHl"
},
"outputs": [],
"source": [
"def github_query_tool(query: str, repo: str, github_token: str) -> str:\n",
" \"\"\"\n",
" Custom tool to query GitHub repository data using the GitHub API.\n",
" Supports basic queries for issues, pull requests, and repository info.\n",
" \"\"\"\n",
" headers = {\n",
" \"Authorization\": f\"token {github_token}\",\n",
" \"Accept\": \"application/vnd.github.v3+json\"\n",
" }\n",
" base_url = f\"https://api.github.com/repos/{repo}\"\n",
" result = \"\"\n",
"\n",
" if \"issue\" in query.lower():\n",
" url = f\"{base_url}/issues\"\n",
" response = requests.get(url, headers=headers)\n",
" if response.ok:\n",
" issues = response.json()\n",
" result = f\"Found {len(issues)} issues in {repo}.\\n\"\n",
" for issue in issues[:5]:\n",
" result += f\"- #{issue['number']}: {issue['title']} (State: {issue['state']})\\n\"\n",
" else:\n",
" result = f\"Failed to fetch issues: {response.text}\"\n",
"\n",
" elif \"pull request\" in query.lower() or \"pr\" in query.lower():\n",
" url = f\"{base_url}/pulls\"\n",
" response = requests.get(url, headers=headers)\n",
" if response.ok:\n",
" pulls = response.json()\n",
" result = f\"Found {len(pulls)} pull requests in {repo}.\\n\"\n",
" for pr in pulls[:5]:\n",
" result += f\"- #{pr['number']}: {pr['title']} (State: {pr['state']})\\n\"\n",
" else:\n",
" result = f\"Failed to fetch pull requests: {response.text}\"\n",
"\n",
" elif \"activity\" in query.lower() or \"stats\" in query.lower():\n",
" url = f\"{base_url}/stats/contributors\"\n",
" response = requests.get(url, headers=headers)\n",
" if response.ok:\n",
" stats = response.json()\n",
" result = f\"Repository activity for {repo}:\\n\"\n",
" for contributor in stats[:5]:\n",
" result += f\"- {contributor['author']['login']}: {contributor['total']} commits\\n\"\n",
" else:\n",
" result = f\"Failed to fetch activity stats: {response.text}\"\n",
"\n",
" else:\n",
" # Default: basic repo info\n",
" response = requests.get(base_url, headers=headers)\n",
" if response.ok:\n",
" info = response.json()\n",
" result = (\n",
" f\"Repository: {info['full_name']}\\n\"\n",
" f\"Description: {info.get('description', 'No description')}\\n\"\n",
" f\"Stars: {info['stargazers_count']}\\n\"\n",
" f\"Forks: {info['forks_count']}\\n\"\n",
" f\"Open Issues: {info['open_issues_count']}\\n\"\n",
" )\n",
" else:\n",
" result = f\"Failed to fetch repository info: {response.text}\"\n",
"\n",
" return result"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "mAFg5SW-tacD"
},
"source": [
"# Register Tool and Create Agent"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"id": "x_MmUc_AyMaB"
},
"outputs": [],
"source": [
"def github_tool_wrapper(inputs):\n",
" query = inputs.get(\"query\", \"\")\n",
" repo = inputs.get(\"repo\", \"\")\n",
" github_token = inputs.get(\"github_token\", \"\")\n",
" return github_query_tool(query, repo, github_token)\n",
"\n",
"agent = Agent(\n",
" instructions=\"\"\"\n",
" You are a GitHub assistant. Help users explore repositories and their activity.\n",
" - Provide organized, concise insights about the repository.\n",
" - Focus on facts and data from the GitHub API.\n",
" - Use markdown formatting for better readability.\n",
" - Present numerical data in tables when appropriate.\n",
" - Include links to relevant GitHub pages when helpful.\n",
" \"\"\",\n",
" tools={\n",
" \"github_query_tool\": github_tool_wrapper\n",
" }\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lPstz7bbtr0k"
},
"source": [
"# User Input and Run Agent"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 118
},
"id": "MymtRmlnyQqd",
"outputId": "33a23810-4a67-4615-f9e9-146b3030fcbf"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter the GitHub repository (owner/repo): Dhivya-Bharathy/PraisonAI\n",
"Enter your question (e.g., Show me open issues): Show me open issues\n"
]
},
{
"data": {
"text/markdown": [
"### Results\n",
"Found 0 issues in Dhivya-Bharathy/PraisonAI.\n"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# User input\n",
"repo = input(\"Enter the GitHub repository (owner/repo): \")\n",
"query = input(\"Enter your question (e.g., Show me open issues): \")\n",
"\n",
"# Call the tool directly (since agent.chat expects an LLM, but we want tool output)\n",
"response = agent.execute_tool(\"github_query_tool\", {\n",
" \"query\": query,\n",
" \"repo\": repo,\n",
" \"github_token\": GITHUB_TOKEN\n",
"})\n",
"\n",
"# Display the result\n",
"display(Markdown(f\"### Results\\n{response}\"))"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,309 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "vmQmHoy-5cAh"
},
"source": [
"# Notion Workspace Assistant with PraisonAIAgents"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WOow52NM5dmh"
},
"source": [
"This notebook demonstrates how to interact with your Notion workspace using PraisonAIAgents in Google Colab. You can read, search, and update Notion pages with natural language queries, leveraging agentic tools for seamless document management—all within a notebook environment."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TlnFAv9P_lGL"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Programming_Code_Analysis_Agents/Notion_Workspace_Assistant.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zMn7hUGZ5hn5"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "U6X3lKAu6iU3"
},
"outputs": [],
"source": [
"!pip install praisonaiagents openai requests --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4_96-D7z6lrC"
},
"source": [
"# Set Up Key"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"id": "kltUFVIW6rEO"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"# Set your Notion and OpenAI API keys here\n",
"NOTION_API_KEY = \"ntn_..\" # <-- Replace with your actual Notion integration token\n",
"OPENAI_API_KEY = \"sk-proj-_..\" # <-- Replace with your actual OpenAI API key\n",
"\n",
"# Set environment variables for downstream libraries\n",
"os.environ[\"NOTION_API_KEY\"] = NOTION_API_KEY\n",
"os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FOLTBEXu635I"
},
"source": [
"# Tools"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "fLWxSASM5jlU"
},
"outputs": [],
"source": [
"from praisonaiagents import Agent\n",
"import requests\n",
"from IPython.display import display, Markdown"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KN_Sxha37EQ0"
},
"source": [
"# Custom Tool"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"id": "WWxcfO9L7Fsu"
},
"outputs": [],
"source": [
"def notion_read_page_tool(page_id: str, notion_token: str) -> str:\n",
" \"\"\"\n",
" Custom tool to read the content of a Notion page using the Notion API.\n",
" \"\"\"\n",
" url = f\"https://api.notion.com/v1/blocks/{page_id}/children\"\n",
" headers = {\n",
" \"Authorization\": f\"Bearer {notion_token}\",\n",
" \"Notion-Version\": \"2022-06-28\"\n",
" }\n",
" response = requests.get(url, headers=headers)\n",
" if response.ok:\n",
" data = response.json()\n",
" blocks = data.get(\"results\", [])\n",
" content = []\n",
" for block in blocks:\n",
" block_type = block.get(\"type\", \"\")\n",
" text = \"\"\n",
" if block_type == \"paragraph\":\n",
" text = block.get(\"paragraph\", {}).get(\"text\", [])\n",
" if text:\n",
" text = text[0].get(\"plain_text\", \"\")\n",
" elif block_type == \"heading_1\":\n",
" text = block.get(\"heading_1\", {}).get(\"text\", [])\n",
" if text:\n",
" text = \"# \" + text[0].get(\"plain_text\", \"\")\n",
" elif block_type == \"heading_2\":\n",
" text = block.get(\"heading_2\", {}).get(\"text\", [])\n",
" if text:\n",
" text = \"## \" + text[0].get(\"plain_text\", \"\")\n",
" elif block_type == \"heading_3\":\n",
" text = block.get(\"heading_3\", {}).get(\"text\", [])\n",
" if text:\n",
" text = \"### \" + text[0].get(\"plain_text\", \"\")\n",
" if text:\n",
" content.append(text)\n",
" return \"\\n\".join(content) if content else \"No readable content found on this page.\"\n",
" else:\n",
" return f\"Failed to fetch page content: {response.text}\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ebuhw9z27Nae"
},
"source": [
"# YAML Prompt"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "eMjDDjzO7Pf3",
"outputId": "b935f96d-f147-44de-80ea-7f75d23f9e7b"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"agent_instructions: |\n",
" You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
" - Provide clear, organized summaries of page content.\n",
" - Use the Notion API to fetch and display information.\n",
" - If a page cannot be read, explain the issue clearly.\n",
"\n",
"tools:\n",
" - name: notion_read_page_tool\n",
" description: >\n",
" Reads the content of a Notion page using its page ID and the user's Notion integration token.\n",
" parameters:\n",
" - name: page_id\n",
" type: string\n",
" description: The Notion page ID to read.\n",
" - name: notion_token\n",
" type: string\n",
" description: The user's Notion integration token.\n",
"\n"
]
}
],
"source": [
"yaml_prompt = \"\"\"\n",
"agent_instructions: |\n",
" You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
" - Provide clear, organized summaries of page content.\n",
" - Use the Notion API to fetch and display information.\n",
" - If a page cannot be read, explain the issue clearly.\n",
"\n",
"tools:\n",
" - name: notion_read_page_tool\n",
" description: >\n",
" Reads the content of a Notion page using its page ID and the user's Notion integration token.\n",
" parameters:\n",
" - name: page_id\n",
" type: string\n",
" description: The Notion page ID to read.\n",
" - name: notion_token\n",
" type: string\n",
" description: The user's Notion integration token.\n",
"\"\"\"\n",
"print(yaml_prompt)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1ozm6Z467WQK"
},
"source": [
"# Main"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 83
},
"id": "eNg-jwpx7X5s",
"outputId": "4440b52a-46b3-4683-9183-13cd21596e25"
},
"outputs": [
{
"data": {
"text/markdown": [
"### Notion Page Content\n",
"*No content found or page is not accessible. Please check your page ID and sharing settings.*"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Define a wrapper to match the agent's expected tool signature\n",
"def notion_tool_wrapper(inputs):\n",
" page_id = inputs.get(\"page_id\", \"\")\n",
" notion_token = inputs.get(\"notion_token\", \"\")\n",
" return notion_read_page_tool(page_id, notion_token)\n",
"\n",
"# Create the agent and register the tool\n",
"agent = Agent(\n",
" instructions=\"\"\"\n",
" You are a Notion workspace assistant. Help users read and manage their Notion pages.\n",
" - Provide clear, organized summaries of page content.\n",
" - Use the Notion API to fetch and display information.\n",
" - If a page cannot be read, explain the issue clearly.\n",
" \"\"\",\n",
" tools={\n",
" \"notion_read_page_tool\": notion_tool_wrapper\n",
" }\n",
")\n",
"\n",
"# Call the tool directly (since agent.chat expects an LLM, but we want tool output)\n",
"response = agent.execute_tool(\"notion_read_page_tool\", {\n",
" \"page_id\": page_id,\n",
" \"notion_token\": NOTION_API_KEY\n",
"})\n",
"\n",
"# Check for error pattern and display a friendly message\n",
"if response.startswith(\"Failed to fetch page content:\"):\n",
" display(Markdown(\"### Notion Page Content\\n*No content found or page is not accessible. Please check your page ID and sharing settings.*\"))\n",
"else:\n",
" display(Markdown(f\"### Notion Page Content\\n{response}\"))"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -1,355 +1,355 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "_T4g3t5sLoag"
},
"source": [
"# ZeroScript: AI-Powered Browser Test Automation using PraisonAI Agent & OpenAI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "O4PKfpalLsmn"
},
"source": [
"# Description"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CEG1pfumLysm"
},
"source": [
"AI-powered browser testing using PraisonAI Agent and OpenAI. Executes YAML-defined test cases, captures screenshots, logs interactions, and generates JSON reports. Ideal for intelligent, automated UI testing.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lbgxOG4gL1Wf"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/ZeroScript_AI_TestExecutor.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WCJqMUzXIndh"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"id": "9AQhJ59cJPmR"
},
"outputs": [],
"source": [
"!pip install --quiet praisonaiagents browser-use python-dotenv pyyaml openai\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QD-dF-6_It1z"
},
"source": [
"# Environment Setup"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "QkRQDli4JhCV",
"outputId": "4b8957ed-a37a-4b11-8585-3537a0437d40"
},
"outputs": [
"cells": [
{
"data": {
"text/plain": [
"True"
"cell_type": "markdown",
"metadata": {
"id": "_T4g3t5sLoag"
},
"source": [
"# ZeroScript: AI-Powered Browser Test Automation using PraisonAI Agent & OpenAI"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"Enter your key\" # replace with actual key\n",
"load_dotenv()\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ELuogWnrIw3o"
},
"source": [
"# Create my_secrets.py"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"id": "sG6tO_v0Jm5N"
},
"outputs": [],
"source": [
"with open(\"my_secrets.py\", \"w\") as f:\n",
" f.write('''sensitive_data = {\n",
" \"username\": \"standard_user\",\n",
" \"password\": \"secret_sauce\"\n",
"}''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rDB_viedIzRR"
},
"source": [
"# Create views.py"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"id": "CtwcybdbJoV8"
},
"outputs": [],
"source": [
"with open(\"views.py\", \"w\") as f:\n",
" f.write('''\n",
"from pydantic import BaseModel\n",
"\n",
"class TestResult(BaseModel):\n",
" status: str\n",
" message: str = \"\"\n",
"''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YTRmBpTiI1kd"
},
"source": [
"# Create agent.py"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"id": "zdJJGt6TJpvr"
},
"outputs": [],
"source": [
"with open(\"agent.py\", \"w\") as f:\n",
" f.write('''\n",
"import os\n",
"from praisonaiagents import Agent\n",
"from browser_use import Browser, BrowserConfig, Controller\n",
"from browser_use.browser.context import BrowserContext, BrowserContextConfig\n",
"from openai import OpenAI\n",
"from views import TestResult\n",
"from my_secrets import sensitive_data\n",
"\n",
"# Browser setup\n",
"browser = Browser(config=BrowserConfig(headless=True))\n",
"context_cfg = BrowserContextConfig(save_recording_path=\"data/recordings\")\n",
"controller = Controller(output_model=TestResult)\n",
"\n",
"async def browser_use(task: str):\n",
" context = BrowserContext(browser=browser, config=context_cfg)\n",
" agent = Agent(\n",
" task=task,\n",
" llm=OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"), model=\"gpt-4\"),\n",
" browser_context=context,\n",
" sensitive_data=sensitive_data,\n",
" controller=controller,\n",
" save_conversation_path=\"data/conversations/convo\",\n",
" extend_system_message=(\n",
" \"You are a professional software tester. Execute browser test steps precisely.\"\n",
" )\n",
" )\n",
" response = await agent.run()\n",
" await context.close()\n",
" return response\n",
"''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-LZtQIE3I4-_"
},
"source": [
"# Create Sample Test YAML"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "l1OdXYI-JreK",
"outputId": "62323fcd-c74f-498f-defc-2c170fa8983e"
},
"outputs": [
{
"data": {
"text/plain": [
"350"
"cell_type": "markdown",
"metadata": {
"id": "O4PKfpalLsmn"
},
"source": [
"# Description"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CEG1pfumLysm"
},
"source": [
"AI-powered browser testing using PraisonAI Agent and OpenAI. Executes YAML-defined test cases, captures screenshots, logs interactions, and generates JSON reports. Ideal for intelligent, automated UI testing.\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lbgxOG4gL1Wf"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/DhivyaBharathy-web/PraisonAI/blob/main/examples/cookbooks/ZeroScript_AI_TestExecutor.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WCJqMUzXIndh"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"id": "9AQhJ59cJPmR"
},
"outputs": [],
"source": [
"!pip install --quiet praisonaiagents browser-use python-dotenv pyyaml openai\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QD-dF-6_It1z"
},
"source": [
"# Environment Setup"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "QkRQDli4JhCV",
"outputId": "4b8957ed-a37a-4b11-8585-3537a0437d40"
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"Enter your key\" # replace with actual key\n",
"load_dotenv()\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ELuogWnrIw3o"
},
"source": [
"# Create my_secrets.py"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"id": "sG6tO_v0Jm5N"
},
"outputs": [],
"source": [
"with open(\"my_secrets.py\", \"w\") as f:\n",
" f.write('''sensitive_data = {\n",
" \"username\": \"standard_user\",\n",
" \"password\": \"secret_sauce\"\n",
"}''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rDB_viedIzRR"
},
"source": [
"# Create views.py"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"id": "CtwcybdbJoV8"
},
"outputs": [],
"source": [
"with open(\"views.py\", \"w\") as f:\n",
" f.write('''\n",
"from pydantic import BaseModel\n",
"\n",
"class TestResult(BaseModel):\n",
" status: str\n",
" message: str = \"\"\n",
"''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YTRmBpTiI1kd"
},
"source": [
"# Create agent.py"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"id": "zdJJGt6TJpvr"
},
"outputs": [],
"source": [
"with open(\"agent.py\", \"w\") as f:\n",
" f.write('''\n",
"import os\n",
"from praisonaiagents import Agent\n",
"from browser_use import Browser, BrowserConfig, Controller\n",
"from browser_use.browser.context import BrowserContext, BrowserContextConfig\n",
"from openai import OpenAI\n",
"from views import TestResult\n",
"from my_secrets import sensitive_data\n",
"\n",
"# Browser setup\n",
"browser = Browser(config=BrowserConfig(headless=True))\n",
"context_cfg = BrowserContextConfig(save_recording_path=\"data/recordings\")\n",
"controller = Controller(output_model=TestResult)\n",
"\n",
"async def browser_use(task: str):\n",
" context = BrowserContext(browser=browser, config=context_cfg)\n",
" agent = Agent(\n",
" task=task,\n",
" llm=OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\"), model=\"gpt-4\"),\n",
" browser_context=context,\n",
" sensitive_data=sensitive_data,\n",
" controller=controller,\n",
" save_conversation_path=\"data/conversations/convo\",\n",
" extend_system_message=(\n",
" \"You are a professional software tester. Execute browser test steps precisely.\"\n",
" )\n",
" )\n",
" response = await agent.run()\n",
" await context.close()\n",
" return response\n",
"''')\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-LZtQIE3I4-_"
},
"source": [
"# Create Sample Test YAML"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "l1OdXYI-JreK",
"outputId": "62323fcd-c74f-498f-defc-2c170fa8983e"
},
"outputs": [
{
"data": {
"text/plain": [
"350"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from pathlib import Path\n",
"tests_dir = Path(\"tests\")\n",
"tests_dir.mkdir(exist_ok=True)\n",
"yaml_content = \"\"\"\n",
"hooks:\n",
" beforeEach: |\n",
" Navigate to https://www.saucedemo.com\n",
" afterEach: |\n",
" Take screenshot\n",
"\n",
"tests:\n",
" - id: \"login_test_001\"\n",
" name: \"Valid Login Test\"\n",
" instructions: |\n",
" 1. Enter standard_user in username field\n",
" 2. Enter secret_sauce in password field\n",
" 3. Click login button\n",
" 4. Verify page contains text \"Products\"\n",
"\"\"\"\n",
"(Path(\"tests/login_test.yml\")).write_text(yaml_content)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sUjy-7OdI7p_"
},
"source": [
"# Run Tests"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Agkiwh7xJtY3",
"outputId": "759aa77c-fd65-49b8-b239-550588059478"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Exception ignored in: <function BrowserSession.__del__ at 0x7e2f540fb100>\n",
"Traceback (most recent call last):\n",
" File \"/usr/local/lib/python3.11/dist-packages/browser_use/browser/session.py\", line 497, in __del__\n",
" status = f'\ud83e\ude93 killing pid={self.browser_pid}...' if (self.browser_pid and owns_browser) else '\u2620\ufe0f'\n",
" ^^^^^^^^^^^^^^^^\n",
" File \"/usr/local/lib/python3.11/dist-packages/pydantic/main.py\", line 991, in __getattr__\n",
" raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')\n",
"AttributeError: 'BrowserSession' object has no attribute 'browser_pid'\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u2705 Report saved to data/reports/report_20250630_092319.json\n"
]
}
],
"source": [
"import asyncio, yaml, json, base64, shutil\n",
"from agent import browser_use, browser\n",
"from pathlib import Path\n",
"from datetime import datetime\n",
"\n",
"# Clean or create data dirs\n",
"for sub in [\"recordings\", \"conversations\", \"screenshots\", \"reports\"]:\n",
" d = Path(\"data\") / sub\n",
" if d.exists(): shutil.rmtree(d)\n",
" d.mkdir(parents=True, exist_ok=True)\n",
"\n",
"async def execute_test_file(path):\n",
" cfg = yaml.safe_load(Path(path).read_text())\n",
" hooks, results = cfg.get(\"hooks\", {}), []\n",
" for t in cfg[\"tests\"]:\n",
" task = f\"{hooks.get('beforeEach','')}\\n{t['instructions']}\\n{hooks.get('afterEach','')}\"\n",
" res = {\"id\": t[\"id\"], \"name\": t[\"name\"]}\n",
" try:\n",
" r = await browser_use(task)\n",
" imgs = r.screenshots()\n",
" if imgs:\n",
" out = Path(\"data/screenshots\") / f\"{t['id']}.png\"\n",
" out.write_bytes(base64.b64decode(imgs[-1]))\n",
" result_obj = r.final_result() if hasattr(r, \"final_result\") else str(r)\n",
" res[\"result\"] = result_obj.model_dump() if hasattr(result_obj, \"model_dump\") else str(result_obj)\n",
" except Exception as e:\n",
" res[\"error\"] = str(e)\n",
" results.append(res)\n",
" return results\n",
"\n",
"async def main():\n",
" all_results = []\n",
" for file in Path(\"tests\").glob(\"*.yml\"):\n",
" all_results.extend(await execute_test_file(str(file)))\n",
" report = Path(\"data/reports\") / f\"report_{datetime.now():%Y%m%d_%H%M%S}.json\"\n",
" report.write_text(json.dumps(all_results, indent=2))\n",
" await browser.close()\n",
" print(f\"\u2705 Report saved to {report}\")\n",
"\n",
"await main()\n"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from pathlib import Path\n",
"tests_dir = Path(\"tests\")\n",
"tests_dir.mkdir(exist_ok=True)\n",
"yaml_content = \"\"\"\n",
"hooks:\n",
" beforeEach: |\n",
" Navigate to https://www.saucedemo.com\n",
" afterEach: |\n",
" Take screenshot\n",
"\n",
"tests:\n",
" - id: \"login_test_001\"\n",
" name: \"Valid Login Test\"\n",
" instructions: |\n",
" 1. Enter standard_user in username field\n",
" 2. Enter secret_sauce in password field\n",
" 3. Click login button\n",
" 4. Verify page contains text \"Products\"\n",
"\"\"\"\n",
"(Path(\"tests/login_test.yml\")).write_text(yaml_content)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sUjy-7OdI7p_"
},
"source": [
"# Run Tests"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
"provenance": []
},
"id": "Agkiwh7xJtY3",
"outputId": "759aa77c-fd65-49b8-b239-550588059478"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Exception ignored in: <function BrowserSession.__del__ at 0x7e2f540fb100>\n",
"Traceback (most recent call last):\n",
" File \"/usr/local/lib/python3.11/dist-packages/browser_use/browser/session.py\", line 497, in __del__\n",
" status = f'🪓 killing pid={self.browser_pid}...' if (self.browser_pid and owns_browser) else '☠️'\n",
" ^^^^^^^^^^^^^^^^\n",
" File \"/usr/local/lib/python3.11/dist-packages/pydantic/main.py\", line 991, in __getattr__\n",
" raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}')\n",
"AttributeError: 'BrowserSession' object has no attribute 'browser_pid'\n"
]
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Report saved to data/reports/report_20250630_092319.json\n"
]
"language_info": {
"name": "python"
}
],
"source": [
"import asyncio, yaml, json, base64, shutil\n",
"from agent import browser_use, browser\n",
"from pathlib import Path\n",
"from datetime import datetime\n",
"\n",
"# Clean or create data dirs\n",
"for sub in [\"recordings\", \"conversations\", \"screenshots\", \"reports\"]:\n",
" d = Path(\"data\") / sub\n",
" if d.exists(): shutil.rmtree(d)\n",
" d.mkdir(parents=True, exist_ok=True)\n",
"\n",
"async def execute_test_file(path):\n",
" cfg = yaml.safe_load(Path(path).read_text())\n",
" hooks, results = cfg.get(\"hooks\", {}), []\n",
" for t in cfg[\"tests\"]:\n",
" task = f\"{hooks.get('beforeEach','')}\\n{t['instructions']}\\n{hooks.get('afterEach','')}\"\n",
" res = {\"id\": t[\"id\"], \"name\": t[\"name\"]}\n",
" try:\n",
" r = await browser_use(task)\n",
" imgs = r.screenshots()\n",
" if imgs:\n",
" out = Path(\"data/screenshots\") / f\"{t['id']}.png\"\n",
" out.write_bytes(base64.b64decode(imgs[-1]))\n",
" result_obj = r.final_result() if hasattr(r, \"final_result\") else str(r)\n",
" res[\"result\"] = result_obj.dict() if hasattr(result_obj, \"dict\") else str(result_obj)\n",
" except Exception as e:\n",
" res[\"error\"] = str(e)\n",
" results.append(res)\n",
" return results\n",
"\n",
"async def main():\n",
" all_results = []\n",
" for file in Path(\"tests\").glob(\"*.yml\"):\n",
" all_results.extend(await execute_test_file(str(file)))\n",
" report = Path(\"data/reports\") / f\"report_{datetime.now():%Y%m%d_%H%M%S}.json\"\n",
" report.write_text(json.dumps(all_results, indent=2))\n",
" await browser.close()\n",
" print(f\"✅ Report saved to {report}\")\n",
"\n",
"await main()\n"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
"nbformat": 4,
"nbformat_minor": 0
}
@@ -129,7 +129,7 @@
"judge = Agent(\n",
" name=\"Judge\",\n",
" role=\"Preside over court proceedings\",\n",
" llm=\"gpt-4o-mini\",\n",
" llm=\"gpt-5-nano\",\n",
" instructions=[\n",
" \"You are an impartial judge\",\n",
" \"Make fair decisions based on evidence\",\n",
@@ -142,7 +142,7 @@
"prosecutor = Agent(\n",
" name=\"Prosecutor\",\n",
" role=\"Present case against defendant\",\n",
" llm=\"gpt-4o-mini\",\n",
" llm=\"gpt-5-nano\",\n",
" instructions=[\n",
" \"You are a prosecutor seeking conviction\",\n",
" \"Present evidence methodically\",\n",
@@ -155,7 +155,7 @@
"defense = Agent(\n",
" name=\"Defense\",\n",
" role=\"Defend the accused\",\n",
" llm=\"gpt-4o-mini\",\n",
" llm=\"gpt-5-nano\",\n",
" instructions=[\n",
" \"You are a defense attorney\",\n",
" \"Create reasonable doubt\",\n",
@@ -168,7 +168,7 @@
"witness = Agent(\n",
" name=\"Witness\",\n",
" role=\"Provide testimony\",\n",
" llm=\"gpt-4o-mini\",\n",
" llm=\"gpt-5-nano\",\n",
" instructions=[\n",
" \"You are a witness testifying\",\n",
" \"Provide factual testimony\",\n",
@@ -76,7 +76,7 @@
"output_type": "stream",
"text": [
"✅ API key configured!\n",
"✅ Using model: gpt-4o-mini\n"
"✅ Using model: gpt-5-nano\n"
]
}
],
@@ -85,7 +85,7 @@
"openai_key = \"sk-..\"\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = openai_key\n",
"model_choice = \"gpt-4o-mini\"\n",
"model_choice = \"gpt-5-nano\"\n",
"\n",
"print(\"✅ API key configured!\")\n",
"print(f\"✅ Using model: {model_choice}\")"
@@ -336,7 +336,7 @@
"\n",
"temperature: 0.3\n",
"max_tokens: 4000\n",
"model: \"gpt-4o-mini\"\n",
"model: \"gpt-5-nano\"\n",
"\"\"\"\n",
"\n",
"print(\"✅ YAML Prompt configured!\")"
@@ -8,7 +8,7 @@
"source": [
"# 🤖 Add AI Documentation Processor: Multi-Agent Content Analysis & Code Generation System\n",
"\n",
"This PR adds a comprehensive AI-powered documentation processing system using PraisonAI and OpenAI GPT-4o-mini. Features 3 specialized agents for content analysis, code generation, and example creation, perfect for automated documentation processing and code generation workflows.\n",
"This PR adds a comprehensive AI-powered documentation processing system using PraisonAI and OpenAI gpt-5-nano. Features 3 specialized agents for content analysis, code generation, and example creation, perfect for automated documentation processing and code generation workflows.\n",
"\n",
"**Key Features:** Multi-agent document analysis, automated code generation, usage example creation, content validation, and scalable processing workflows for various document formats."
]
@@ -152,7 +152,7 @@
" - Evaluate risk factors\n",
" - Identify scams or red flags\n",
" - Summarize project fundamentals\n",
"llm: gpt-4o\n",
"llm: gpt-5-nano\n",
"verbosity: true\n",
"format: markdown\n",
"\"\"\"\n"
@@ -184,7 +184,7 @@
"and market trends. Provide critical insight into legitimacy, potential growth, and associated risks.\n",
"Use markdown formatting and structure your research clearly.\n",
"\"\"\",\n",
" llm=\"gpt-4o\",\n",
" llm=\"gpt-5-nano\",\n",
" verbose=True,\n",
" markdown=True\n",
")\n"
@@ -491,7 +491,7 @@
"\n",
"temperature: 0.7\n",
"max_tokens: 3000\n",
"model: \"gpt-4o-mini\"\n",
"model: \"gpt-5-nano\"\n",
"\"\"\"\n",
"\n",
"print(\"✅ YAML Prompt configured!\")"
@@ -627,7 +627,7 @@
" )\n",
" else: # OpenAI\n",
" llm = ChatOpenAI(\n",
" model=\"gpt-4o\",\n",
" model=\"gpt-5-nano\",\n",
" api_key=api_key,\n",
" temperature=0.0\n",
" )\n",
@@ -120,7 +120,7 @@
"\n",
" def run(self, message: str):\n",
" response = client.chat.completions.create(\n",
" model=\"gpt-4o-mini\",\n",
" model=\"gpt-5-nano\",\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": self.prompt},\n",
" {\"role\": \"user\", \"content\": message}\n",
@@ -153,7 +153,7 @@
" - Spot content patterns and trends\n",
" - Recommend growth strategies\n",
" - Detect potential monetization methods\n",
"llm: gpt-4o\n",
"llm: gpt-5-nano\n",
"verbosity: true\n",
"format: markdown\n",
"\"\"\"\n"
@@ -184,7 +184,7 @@
"You are a YouTube intelligence analyst. Your job is to research a specific channel, niche, or influencer topic.\n",
"Provide growth recommendations, engagement analysis, trending strategies, and monetization tips. Format in markdown.\n",
"\"\"\",\n",
" llm=\"gpt-4o\",\n",
" llm=\"gpt-5-nano\",\n",
" verbose=True,\n",
" markdown=True\n",
")\n"
@@ -136,7 +136,7 @@
"name": "stdout",
"output_type": "stream",
"text": [
"{'name': 'Travel Research Agent', 'description': 'A world-class travel researcher that searches for destinations, activities, and accommodations', 'instructions': ['Given a travel destination and number of days, generate 3 relevant search terms', 'Search the web for each term using web_search tool', 'Analyze results and return 10 most relevant findings', 'Focus on activities, accommodations, attractions, and local insights', 'Ensure high-quality, accurate information', 'Use travel_budget_calculator to estimate costs'], 'tools': ['web_search', 'travel_budget_calculator'], 'model': 'gpt-4o', 'temperature': 0.7}\n"
"{'name': 'Travel Research Agent', 'description': 'A world-class travel researcher that searches for destinations, activities, and accommodations', 'instructions': ['Given a travel destination and number of days, generate 3 relevant search terms', 'Search the web for each term using web_search tool', 'Analyze results and return 10 most relevant findings', 'Focus on activities, accommodations, attractions, and local insights', 'Ensure high-quality, accurate information', 'Use travel_budget_calculator to estimate costs'], 'tools': ['web_search', 'travel_budget_calculator'], 'model': 'gpt-5-nano', 'temperature': 0.7}\n"
]
}
],
@@ -156,7 +156,7 @@
"tools:\n",
" - web_search\n",
" - travel_budget_calculator\n",
"model: gpt-4o\n",
"model: gpt-5-nano\n",
"temperature: 0.7\n",
"\"\"\"\n",
"\n",
@@ -17,7 +17,7 @@
"id": "Y9FkDzt1lF47"
},
"source": [
"This notebook implements a conversational restaurant booking assistant using the Praison AI Agent framework. It handles natural interruptions such as modifying guest count or changing time mid-conversation. Built for Google Colab Free Tier, it uses OpenAI's GPT-4o model and follows a YAML-based agent design for clarity and modularity."
"This notebook implements a conversational restaurant booking assistant using the Praison AI Agent framework. It handles natural interruptions such as modifying guest count or changing time mid-conversation. Built for Google Colab Free Tier, it uses OpenAI's gpt-5-nano model and follows a YAML-based agent design for clarity and modularity."
]
},
{
@@ -135,7 +135,7 @@
" - Context management\n",
" - Handling mid-conversation changes\n",
" - Summarizing confirmed reservations\n",
"llm: gpt-4o\n",
"llm: gpt-5-nano\n",
"verbosity: true\n",
"format: markdown\n",
"\"\"\"\n"
@@ -167,7 +167,7 @@
"manage corrections like “change to 3 guests” or “move to 8 PM,”\n",
"confirm the details once the user is satisfied. Respond in markdown.\n",
"\"\"\",\n",
" llm=\"gpt-4o\",\n",
" llm=\"gpt-5-nano\",\n",
" verbose=True,\n",
" markdown=True\n",
")\n"
@@ -0,0 +1,481 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "LJRJRQtFTagH"
},
"source": [
"# AI RAG Agent with Web Access using PraisonAI"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ph4RVTBCTcmB"
},
"source": [
"This notebook demonstrates how to build a Retrieval-Augmented Generation (RAG) agent with web access using GPT-4o and PraisonAI. The agent specializes in Thai recipes and can search the web for additional information."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tMxfwPPATy_o"
},
"source": [
"This RAG agent:\n",
"* Creates an AI assistant specialized in Thai recipes and cooking\n",
"* Has access to a PDF knowledge base about Thai recipes\n",
"* Can search the web using DuckDuckGo for additional information\n",
"* Provides comprehensive answers about Thai cuisine\n",
"* Uses PraisonAI framework for agent management"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "h68oMaCITmqt"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/rag_examples/agentic_rag/PraisonAI_RecipeAgent.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cAdzoWXJUMfF"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9D-2TlOrUNcu"
},
"outputs": [],
"source": [
"!pip install praisonaiagents openai requests"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yY-4-kEIUW40"
},
"source": [
"# Set Up API Key"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "f5bhQ05yUX6J",
"outputId": "dcf9d0d9-332e-4136-9289-4c39d898005c"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter your OpenAI API key: ··········\n",
"✅ API key set successfully!\n"
]
}
],
"source": [
"import os\n",
"\n",
"# Set your OpenAI API key here\n",
"os.environ['OPENAI_API_KEY'] = 'Enter your api key here'\n",
"\n",
"# Or use this method to input it securely\n",
"from getpass import getpass\n",
"api_key = getpass('Enter your OpenAI API key: ')\n",
"os.environ['OPENAI_API_KEY'] = api_key\n",
"\n",
"print(\"✅ API key set successfully!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Eh0j-SegUi13"
},
"source": [
"# Tools"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Z1A9oifIUkQN",
"outputId": "9be78226-36fa-43c4-865d-2f7e6e2ba9de"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Tools imported successfully!\n"
]
}
],
"source": [
"from praisonaiagents import Agent\n",
"import requests\n",
"import tempfile\n",
"from pathlib import Path\n",
"\n",
"print(\"✅ Tools imported successfully!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "efnnREHXUnYA"
},
"source": [
"# YAML Prompt"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "kcM14-yQUqG-",
"outputId": "c5b6288d-a789-4a93-e20c-1d285370b667"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"✅ Agent instructions configured!\n"
]
}
],
"source": [
"# Agent configuration and instructions\n",
"AGENT_INSTRUCTIONS = \"\"\"\n",
"You are a helpful AI assistant specialized in Thai recipes and cooking.\n",
"\n",
"You have access to a PDF knowledge base about Thai recipes from: https://phi-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf\n",
"\n",
"You can also search the web for additional information about Thai cooking, ingredients, and techniques.\n",
"\n",
"When answering questions:\n",
"1. Use your knowledge about Thai cuisine to provide helpful information\n",
"2. If needed, search the web for additional details, current information, or clarification\n",
"3. Provide comprehensive, helpful answers about Thai cuisine\n",
"4. Always be informative and helpful about Thai cooking!\n",
"\n",
"You can use the internet_search function to search the web when needed.\n",
"\n",
"Focus on providing practical cooking advice, ingredient information, and authentic Thai recipe guidance.\n",
"\"\"\"\n",
"\n",
"print(\"✅ Agent instructions configured!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MCBRcXFJUulY"
},
"source": [
"# Main"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "YaRLbgMmUvXv",
"outputId": "8ed8d9f8-85a7-48de-ccc6-f617cd672a85"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🤖 Thai Recipe RAG Agent created successfully!\n",
"The agent is ready to answer questions about Thai cooking.\n"
]
}
],
"source": [
"# Create the RAG agent\n",
"rag_agent = Agent(\n",
" instructions=AGENT_INSTRUCTIONS,\n",
" llm=\"gpt-4o\",\n",
" markdown=True,\n",
" verbose=True\n",
")\n",
"\n",
"print(\"🤖 Thai Recipe RAG Agent created successfully!\")\n",
"print(\"The agent is ready to answer questions about Thai cooking.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QvZM94pGU0IX"
},
"source": [
"# Test the Agent"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000,
"referenced_widgets": [
"47739975c9f04ee5b4e69e8f445cbeda",
"08888d583cba4c01b3fdf8f30b06ca4f"
]
},
"id": "QPdrleKxU1VN",
"outputId": "a71a86cd-eff8-4309-9b50-173a30066c90"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"🤔 Question: What are the essential ingredients for Thai cooking?\n"
]
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╭─ </span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8; font-weight: bold\">Agent Info</span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\"> ────────────────────────────────────────────────────────────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #ff9b9b; text-decoration-color: #ff9b9b; font-weight: bold\">👤 Agent:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Agent</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #b4b4b3; text-decoration-color: #b4b4b3; font-weight: bold\">Role:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Assistant</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[38;2;210;227;200m╭─\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[1;38;2;210;227;200mAgent Info\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[38;2;210;227;200m───────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\u001b[38;2;210;227;200m─╮\u001b[0m\n",
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;255;155;155m👤 Agent:\u001b[0m \u001b[38;2;255;229;229mAgent\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;180;180;179mRole:\u001b[0m \u001b[38;2;255;229;229mAssistant\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
"\u001b[38;2;210;227;200m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "47739975c9f04ee5b4e69e8f445cbeda",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
],
"text/plain": []
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
"</pre>\n"
],
"text/plain": [
"\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #7f7f7f; text-decoration-color: #7f7f7f\">Response generated in 8.4s</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[2mResponse generated in 8.4s\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭───────────────────────────────────────────────────── Task ──────────────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> What are the essential ingredients for Thai cooking? <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[36m╭─\u001b[0m\u001b[36m────────────────────────────────────────────────────\u001b[0m\u001b[36m Task \u001b[0m\u001b[36m─────────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
"\u001b[36m│\u001b[0m What are the essential ingredients for Thai cooking? \u001b[36m│\u001b[0m\n",
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭─────────────────────────────────────────────────── Response ────────────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Thai cooking is known for its balance of five fundamental taste senses in each dish or the overall meal: sour, <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> sweet, salty, bitter, and spicy. Essential ingredients that help achieve this balance include: <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 1 </span><span style=\"font-weight: bold\">Fish Sauce (Nam Pla)</span>: A salty, savory sauce made from fermented fish. It's a cornerstone of Thai cooking, <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>used to add depth of flavor. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 2 </span><span style=\"font-weight: bold\">Lime Juice</span>: Used to add a fresh, tangy citrus flavor to dishes, especially in salads and some curries. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 3 </span><span style=\"font-weight: bold\">Chilies</span>: Thai cuisine often features fresh Thai bird's eye chilies for heat, as well as dried chilies for <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>certain recipes. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 4 </span><span style=\"font-weight: bold\">Lemongrass</span>: A citrusy, fragrant herb that is often used in soups, curries, and teas. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 5 </span><span style=\"font-weight: bold\">Galangal</span>: Similar to ginger, galangal has a sharp, peppery flavor and is used in soups and curries. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 6 </span><span style=\"font-weight: bold\">Kaffir Lime Leaves</span>: They add a distinct, zesty citrus aroma and flavor to Thai dishes. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 7 </span><span style=\"font-weight: bold\">Coconut Milk</span>: Adds richness and creaminess, commonly used in curries and desserts. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 8 </span><span style=\"font-weight: bold\">Palm Sugar</span>: Used as a sweetener, palm sugar has a nuanced flavor, unlike regular sugar. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 9 </span><span style=\"font-weight: bold\">Tamarind Paste</span>: Provides a sour element to many dishes, particularly pad Thai and some sauces. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 10 </span><span style=\"font-weight: bold\">Thai Basil</span>: Adds a spicy, peppery flavor, different from the sweet basil used in Western cooking. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 11 </span><span style=\"font-weight: bold\">Coriander (Cilantro)</span>: Used as a garnish and for its fresh, citrusy leaves and roots, which add depth to <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>sauces and stocks. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> 12 </span><span style=\"font-weight: bold\">Shrimp Paste</span>: A very pungent paste made from fermented shrimp, used sparingly to enrich the flavor of <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>dishes. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> These ingredients are commonly used in combination to create the complex and rich flavors characteristic of <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Thai cuisine. Fresh and high-quality versions of these ingredients contribute significantly to the authenticity <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> of Thai dishes. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[36m╭─\u001b[0m\u001b[36m──────────────────────────────────────────────────\u001b[0m\u001b[36m Response \u001b[0m\u001b[36m───────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
"\u001b[36m│\u001b[0m Thai cooking is known for its balance of five fundamental taste senses in each dish or the overall meal: sour, \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m sweet, salty, bitter, and spicy. Essential ingredients that help achieve this balance include: \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 1 \u001b[0m\u001b[1mFish Sauce (Nam Pla)\u001b[0m: A salty, savory sauce made from fermented fish. It's a cornerstone of Thai cooking, \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mused to add depth of flavor. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 2 \u001b[0m\u001b[1mLime Juice\u001b[0m: Used to add a fresh, tangy citrus flavor to dishes, especially in salads and some curries. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 3 \u001b[0m\u001b[1mChilies\u001b[0m: Thai cuisine often features fresh Thai bird's eye chilies for heat, as well as dried chilies for \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mcertain recipes. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 4 \u001b[0m\u001b[1mLemongrass\u001b[0m: A citrusy, fragrant herb that is often used in soups, curries, and teas. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 5 \u001b[0m\u001b[1mGalangal\u001b[0m: Similar to ginger, galangal has a sharp, peppery flavor and is used in soups and curries. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 6 \u001b[0m\u001b[1mKaffir Lime Leaves\u001b[0m: They add a distinct, zesty citrus aroma and flavor to Thai dishes. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 7 \u001b[0m\u001b[1mCoconut Milk\u001b[0m: Adds richness and creaminess, commonly used in curries and desserts. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 8 \u001b[0m\u001b[1mPalm Sugar\u001b[0m: Used as a sweetener, palm sugar has a nuanced flavor, unlike regular sugar. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 9 \u001b[0m\u001b[1mTamarind Paste\u001b[0m: Provides a sour element to many dishes, particularly pad Thai and some sauces. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 10 \u001b[0m\u001b[1mThai Basil\u001b[0m: Adds a spicy, peppery flavor, different from the sweet basil used in Western cooking. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 11 \u001b[0m\u001b[1mCoriander (Cilantro)\u001b[0m: Used as a garnish and for its fresh, citrusy leaves and roots, which add depth to \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0msauces and stocks. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m 12 \u001b[0m\u001b[1mShrimp Paste\u001b[0m: A very pungent paste made from fermented shrimp, used sparingly to enrich the flavor of \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mdishes. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m These ingredients are commonly used in combination to create the complex and rich flavors characteristic of \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m Thai cuisine. Fresh and high-quality versions of these ingredients contribute significantly to the authenticity \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m of Thai dishes. \u001b[36m│\u001b[0m\n",
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"�� Answer: Thai cooking is known for its balance of five fundamental taste senses in each dish or the overall meal: sour, sweet, salty, bitter, and spicy. Essential ingredients that help achieve this balance include:\n",
"\n",
"1. **Fish Sauce (Nam Pla)**: A salty, savory sauce made from fermented fish. It's a cornerstone of Thai cooking, used to add depth of flavor.\n",
"\n",
"2. **Lime Juice**: Used to add a fresh, tangy citrus flavor to dishes, especially in salads and some curries.\n",
"\n",
"3. **Chilies**: Thai cuisine often features fresh Thai bird's eye chilies for heat, as well as dried chilies for certain recipes.\n",
"\n",
"4. **Lemongrass**: A citrusy, fragrant herb that is often used in soups, curries, and teas.\n",
"\n",
"5. **Galangal**: Similar to ginger, galangal has a sharp, peppery flavor and is used in soups and curries.\n",
"\n",
"6. **Kaffir Lime Leaves**: They add a distinct, zesty citrus aroma and flavor to Thai dishes.\n",
"\n",
"7. **Coconut Milk**: Adds richness and creaminess, commonly used in curries and desserts.\n",
"\n",
"8. **Palm Sugar**: Used as a sweetener, palm sugar has a nuanced flavor, unlike regular sugar.\n",
"\n",
"9. **Tamarind Paste**: Provides a sour element to many dishes, particularly pad Thai and some sauces.\n",
"\n",
"10. **Thai Basil**: Adds a spicy, peppery flavor, different from the sweet basil used in Western cooking.\n",
"\n",
"11. **Coriander (Cilantro)**: Used as a garnish and for its fresh, citrusy leaves and roots, which add depth to sauces and stocks.\n",
"\n",
"12. **Shrimp Paste**: A very pungent paste made from fermented shrimp, used sparingly to enrich the flavor of dishes.\n",
"\n",
"These ingredients are commonly used in combination to create the complex and rich flavors characteristic of Thai cuisine. Fresh and high-quality versions of these ingredients contribute significantly to the authenticity of Thai dishes.\n"
]
}
],
"source": [
"# Test question 1: Basic Thai cooking\n",
"question1 = \"What are the essential ingredients for Thai cooking?\"\n",
"print(f\"🤔 Question: {question1}\")\n",
"\n",
"try:\n",
" response1 = rag_agent.start(question1)\n",
" print(f\"�� Answer: {response1}\")\n",
"except Exception as e:\n",
" print(f\"❌ Error: {e}\")"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -0,0 +1,556 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "EA8l4cSVl3Lx"
},
"source": [
"# Agentic RAG with GPT-5 - Colab Notebook"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "I-8nOxJ2l7nO"
},
"source": [
"This Colab notebook sets up a Streamlit app using PraisonAI Agents framework.\n",
"It allows you to interact with an AI agent powered by GPT-5 for Q&A.\n",
"Currently, the knowledge base functionality is disabled due to compatibility issues."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "g5I1tMkxmDQe"
},
"source": [
"- GPT-5 Integration (via OpenAI API)\n",
"- Streamlit Web App\n",
"- Agent Framework: PraisonAI Agents\n",
"- Markdown-formatted responses"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yeEno7U0q2U_"
},
"source": [
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Qwen2.5_InstructionAgent.ipynb)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WV2GnzZCmGBR"
},
"source": [
"# Dependencies"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "20wAadXemJ0k"
},
"outputs": [],
"source": [
"!pip install praisonaiagents python-dotenv streamlit"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "l71uCRarndvy"
},
"source": [
"# Set API Key"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"id": "brfc-ZZKnfre"
},
"outputs": [],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"\n",
"load_dotenv()\n",
"\n",
"OPENAI_API_KEY = \"Enter your api key here\"\n",
"\n",
"os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d1fGzyQCn1aQ"
},
"source": [
"# Tools and Imports"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"id": "GcNPLkZXntIS"
},
"outputs": [],
"source": [
"import streamlit as st\n",
"from praisonaiagents import Agent\n",
"\n",
"# YAML Prompt Configuration\n",
"agent_config = {\n",
" \"name\": \"Knowledge Agent\",\n",
" \"instructions\": [\n",
" \"You are a helpful AI assistant. Answer questions based on your general knowledge.\",\n",
" \"Provide clear, well-structured answers in markdown format.\",\n",
" \"Use proper markdown formatting with headers, lists, and emphasis where appropriate.\",\n",
" \"Structure your response with clear sections and bullet points when helpful.\",\n",
" ],\n",
" \"llm\": \"gpt-5-nano\",\n",
" \"markdown\": True,\n",
" \"verbose\": True\n",
"}\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jkmrh0gIn_4a"
},
"source": [
"# Initialize Agent"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"id": "qaJvf8RyoAsB"
},
"outputs": [],
"source": [
"def create_agent():\n",
" \"\"\"Create an agent with reasoning capabilities\"\"\"\n",
" return Agent(\n",
" name=agent_config[\"name\"],\n",
" instructions=agent_config[\"instructions\"],\n",
" llm=agent_config[\"llm\"],\n",
" markdown=agent_config[\"markdown\"],\n",
" verbose=agent_config[\"verbose\"]\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kvGJh3bbqTmh"
},
"source": [
"# Main Function"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000,
"referenced_widgets": [
"ad296d97510246de8eb0138ce8a8a166",
"f6e502b3dca442f0ae6c5739f5a6d159"
]
},
"id": "_QyxzqKKqUrW",
"outputId": "97be7e02-b034-4004-e9e3-56337e3f2887"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"�� Initializing Agentic RAG with GPT-5...\n",
"📚 Loading agent...\n",
"✅ Agent loaded successfully!\n",
"\n",
"🎯 Example queries you can try:\n",
"1. What is PraisonAI and how do Agents work?\n",
"2. What are Teams in PraisonAI and how do they work?\n",
"3. Give me a step-by-step guide to building a RAG system.\n",
"4. What are AI Agents?\n",
"\n",
"============================================================\n",
"\n",
"🤔 Enter your question (or 'quit' to exit):\n",
"> What is PraisonAI and how do Agents work?\n",
"🔍 Processing your question...\n"
]
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╭─ </span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8; font-weight: bold\">Agent Info</span><span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\"> ────────────────────────────────────────────────────────────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #ff9b9b; text-decoration-color: #ff9b9b; font-weight: bold\">👤 Agent:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Knowledge Agent</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #b4b4b3; text-decoration-color: #b4b4b3; font-weight: bold\">Role:</span> <span style=\"color: #ffe5e5; text-decoration-color: #ffe5e5\">Assistant</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span> <span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">│</span>\n",
"<span style=\"color: #d2e3c8; text-decoration-color: #d2e3c8\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[38;2;210;227;200m╭─\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[1;38;2;210;227;200mAgent Info\u001b[0m\u001b[38;2;210;227;200m \u001b[0m\u001b[38;2;210;227;200m───────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\u001b[38;2;210;227;200m─╮\u001b[0m\n",
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;255;155;155m👤 Agent:\u001b[0m \u001b[38;2;255;229;229mKnowledge Agent\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[1;38;2;180;180;179mRole:\u001b[0m \u001b[38;2;255;229;229mAssistant\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
"\u001b[38;2;210;227;200m│\u001b[0m \u001b[38;2;210;227;200m│\u001b[0m\n",
"\u001b[38;2;210;227;200m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ad296d97510246de8eb0138ce8a8a166",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
],
"text/plain": []
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
"</pre>\n"
],
"text/plain": [
"\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #7f7f7f; text-decoration-color: #7f7f7f\">Response generated in 9.4s</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[2mResponse generated in 9.4s\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭───────────────────────────────────────────────────── Task ──────────────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> What is PraisonAI and how do Agents work? <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[36m╭─\u001b[0m\u001b[36m────────────────────────────────────────────────────\u001b[0m\u001b[36m Task \u001b[0m\u001b[36m─────────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
"\u001b[36m│\u001b[0m What is PraisonAI and how do Agents work? \u001b[36m│\u001b[0m\n",
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #008080; text-decoration-color: #008080\">╭─────────────────────────────────────────────────── Response ────────────────────────────────────────────────────╮</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> ┃ <span style=\"font-weight: bold\">What is PraisonAI?</span> ┃ <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> PraisonAI is a platform designed to leverage artificial intelligence to enhance personal and business <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> productivity. It typically involves developing AI models that can assist in various tasks, automate processes, <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> and provide insights based on data analysis. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">Key Features of PraisonAI</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Task Automation</span>: Automates repetitive tasks, allowing users to focus on more strategic activities. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Data Insights</span>: Analyzes large sets of data to provide actionable insights. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Natural Language Processing</span>: Enables users to interact with the AI through natural language, making it <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>user-friendly. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Customizable Solutions</span>: Tailors AI applications to meet specific user needs across various industries. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> ┃ <span style=\"font-weight: bold\">How Do Agents Work in PraisonAI?</span> ┃ <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> Agents in PraisonAI refer to autonomous or semi-autonomous AI systems that perform designated tasks or <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> functions. Here’s how they typically operate: <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">1. Types of Agents</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Reactive Agents</span>: Respond to the current environment without internal memory. They act solely based on <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>current inputs. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Deliberative Agents</span>: Have a model of their environment, plan their actions, and retain memories of past <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>interactions. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Learning Agents</span>: Improve their performance over time through experience, adapting to new information. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">2. Functionality of Agents</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Task Execution</span>: Agents can carry out specific tasks as programmed, such as scheduling, data entry, or <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>customer support. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Interaction</span>: They often interact with users through chat interfaces or APIs, providing a seamless user <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>experience. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Integration</span>: Can be integrated with other systems or software to enhance functionality, such as CRM systems, <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>databases, or other AI tools. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Continuous Learning</span>: Agents may utilize machine learning algorithms to adapt and evolve based on user <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> </span>interactions and data received. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">3. Benefits of Using Agents</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Increased Efficiency</span>: Automate routine tasks to reduce workload. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">24/7 Availability</span>: Provide consistent support and functionality without downtime. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Scalability</span>: Easily scale operations by deploying more agents as needed. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #808000; text-decoration-color: #808000; font-weight: bold\"> • </span><span style=\"font-weight: bold\">Data-Driven Decisions</span>: Use data insights to inform strategy and operations. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"font-weight: bold; text-decoration: underline\">Conclusion</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> PraisonAI represents a robust platform for enhancing productivity through AI, with agents serving as the heart <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> of this solution, performing various tasks and supporting users in achieving their goals efficiently. Whether <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> they are simple reactive agents or complex learning entities, their design focuses on making operations <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">│</span> smoother and more effective. <span style=\"color: #008080; text-decoration-color: #008080\">│</span>\n",
"<span style=\"color: #008080; text-decoration-color: #008080\">╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[36m╭─\u001b[0m\u001b[36m──────────────────────────────────────────────────\u001b[0m\u001b[36m Response \u001b[0m\u001b[36m───────────────────────────────────────────────────\u001b[0m\u001b[36m─╮\u001b[0m\n",
"\u001b[36m│\u001b[0m ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m ┃ \u001b[1mWhat is PraisonAI?\u001b[0m ┃ \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m PraisonAI is a platform designed to leverage artificial intelligence to enhance personal and business \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m productivity. It typically involves developing AI models that can assist in various tasks, automate processes, \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m and provide insights based on data analysis. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;4mKey Features of PraisonAI\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mTask Automation\u001b[0m: Automates repetitive tasks, allowing users to focus on more strategic activities. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mData Insights\u001b[0m: Analyzes large sets of data to provide actionable insights. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mNatural Language Processing\u001b[0m: Enables users to interact with the AI through natural language, making it \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0muser-friendly. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mCustomizable Solutions\u001b[0m: Tailors AI applications to meet specific user needs across various industries. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m ┃ \u001b[1mHow Do Agents Work in PraisonAI?\u001b[0m ┃ \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m Agents in PraisonAI refer to autonomous or semi-autonomous AI systems that perform designated tasks or \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m functions. Here’s how they typically operate: \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;4m1. \u001b[0m\u001b[1;4mTypes of Agents\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mReactive Agents\u001b[0m: Respond to the current environment without internal memory. They act solely based on \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mcurrent inputs. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mDeliberative Agents\u001b[0m: Have a model of their environment, plan their actions, and retain memories of past \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0minteractions. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mLearning Agents\u001b[0m: Improve their performance over time through experience, adapting to new information. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;4m2. \u001b[0m\u001b[1;4mFunctionality of Agents\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mTask Execution\u001b[0m: Agents can carry out specific tasks as programmed, such as scheduling, data entry, or \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mcustomer support. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mInteraction\u001b[0m: They often interact with users through chat interfaces or APIs, providing a seamless user \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mexperience. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mIntegration\u001b[0m: Can be integrated with other systems or software to enhance functionality, such as CRM systems, \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0mdatabases, or other AI tools. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mContinuous Learning\u001b[0m: Agents may utilize machine learning algorithms to adapt and evolve based on user \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m \u001b[0minteractions and data received. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;4m3. \u001b[0m\u001b[1;4mBenefits of Using Agents\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mIncreased Efficiency\u001b[0m: Automate routine tasks to reduce workload. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1m24/7 Availability\u001b[0m: Provide consistent support and functionality without downtime. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mScalability\u001b[0m: Easily scale operations by deploying more agents as needed. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;33m • \u001b[0m\u001b[1mData-Driven Decisions\u001b[0m: Use data insights to inform strategy and operations. \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[1;4mConclusion\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m PraisonAI represents a robust platform for enhancing productivity through AI, with agents serving as the heart \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m of this solution, performing various tasks and supporting users in achieving their goals efficiently. Whether \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m they are simple reactive agents or complex learning entities, their design focuses on making operations \u001b[36m│\u001b[0m\n",
"\u001b[36m│\u001b[0m smoother and more effective. \u001b[36m│\u001b[0m\n",
"\u001b[36m╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"💡 Answer:\n",
"========================================\n",
"# What is PraisonAI?\n",
"\n",
"PraisonAI is a platform designed to leverage artificial intelligence to enhance personal and business productivity. It typically involves developing AI models that can assist in various tasks, automate processes, and provide insights based on data analysis.\n",
"\n",
"## Key Features of PraisonAI\n",
"\n",
"- **Task Automation**: Automates repetitive tasks, allowing users to focus on more strategic activities.\n",
"- **Data Insights**: Analyzes large sets of data to provide actionable insights.\n",
"- **Natural Language Processing**: Enables users to interact with the AI through natural language, making it user-friendly.\n",
"- **Customizable Solutions**: Tailors AI applications to meet specific user needs across various industries.\n",
"\n",
"# How Do Agents Work in PraisonAI?\n",
"\n",
"Agents in PraisonAI refer to autonomous or semi-autonomous AI systems that perform designated tasks or functions. Here’s how they typically operate:\n",
"\n",
"## 1. **Types of Agents**\n",
"\n",
"- **Reactive Agents**: Respond to the current environment without internal memory. They act solely based on current inputs.\n",
"- **Deliberative Agents**: Have a model of their environment, plan their actions, and retain memories of past interactions.\n",
"- **Learning Agents**: Improve their performance over time through experience, adapting to new information.\n",
"\n",
"## 2. **Functionality of Agents**\n",
"\n",
"- **Task Execution**: Agents can carry out specific tasks as programmed, such as scheduling, data entry, or customer support.\n",
"- **Interaction**: They often interact with users through chat interfaces or APIs, providing a seamless user experience.\n",
"- **Integration**: Can be integrated with other systems or software to enhance functionality, such as CRM systems, databases, or other AI tools.\n",
"- **Continuous Learning**: Agents may utilize machine learning algorithms to adapt and evolve based on user interactions and data received.\n",
"\n",
"## 3. **Benefits of Using Agents**\n",
"\n",
"- **Increased Efficiency**: Automate routine tasks to reduce workload.\n",
"- **24/7 Availability**: Provide consistent support and functionality without downtime.\n",
"- **Scalability**: Easily scale operations by deploying more agents as needed.\n",
"- **Data-Driven Decisions**: Use data insights to inform strategy and operations.\n",
"\n",
"## Conclusion\n",
"\n",
"PraisonAI represents a robust platform for enhancing productivity through AI, with agents serving as the heart of this solution, performing various tasks and supporting users in achieving their goals efficiently. Whether they are simple reactive agents or complex learning entities, their design focuses on making operations smoother and more effective.\n",
"========================================\n",
"\n",
"🤔 Enter your question (or 'quit' to exit):\n",
"> quit\n",
"👋 Goodbye!\n"
]
}
],
"source": [
"def main():\n",
" print(\"�� Initializing Agentic RAG with GPT-5...\")\n",
"\n",
" # Check if API key is set\n",
" if not OPENAI_API_KEY or OPENAI_API_KEY == \"your_openai_api_key_here\":\n",
" print(\"❌ Please set your OpenAI API key first!\")\n",
" print(\"�� Get your key from: https://platform.openai.com/\")\n",
" return\n",
"\n",
" try:\n",
" # Create agent\n",
" print(\"📚 Loading agent...\")\n",
" agent = create_agent()\n",
" print(\"✅ Agent loaded successfully!\")\n",
"\n",
" # Example queries\n",
" example_queries = [\n",
" \"What is PraisonAI and how do Agents work?\",\n",
" \"What are Teams in PraisonAI and how do they work?\",\n",
" \"Give me a step-by-step guide to building a RAG system.\",\n",
" \"What are AI Agents?\"\n",
" ]\n",
"\n",
" print(\"\\n🎯 Example queries you can try:\")\n",
" for i, query in enumerate(example_queries, 1):\n",
" print(f\"{i}. {query}\")\n",
"\n",
" print(\"\\n\" + \"=\"*60)\n",
"\n",
" # Interactive query loop\n",
" while True:\n",
" print(\"\\n🤔 Enter your question (or 'quit' to exit):\")\n",
" user_query = input(\"> \")\n",
"\n",
" if user_query.lower() in ['quit', 'exit', 'q']:\n",
" print(\"👋 Goodbye!\")\n",
" break\n",
"\n",
" if user_query.strip():\n",
" print(\"🔍 Processing your question...\")\n",
" try:\n",
" response = agent.start(user_query)\n",
" print(\"\\n💡 Answer:\")\n",
" print(\"=\"*40)\n",
" print(response)\n",
" print(\"=\"*40)\n",
" except Exception as e:\n",
" print(f\"❌ Error: {str(e)}\")\n",
" print(f\"🔍 Error type: {type(e).__name__}\")\n",
" print(\"💡 This might be due to API issues or model access problems.\")\n",
" else:\n",
" print(\"❌ Please enter a valid question.\")\n",
"\n",
" except Exception as e:\n",
" print(f\"❌ Failed to initialize agent: {str(e)}\")\n",
" print(\"�� Make sure your API key is correct and you have sufficient credits.\")\n",
"\n",
"# Run the main function\n",
"if __name__ == \"__main__\":\n",
" main()"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
@@ -585,7 +585,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -1090,7 +1090,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -1,10 +1,10 @@
framework: crewai
topic: "Technology Research and Content Creation using AWS Bedrock"
roles:
agents: # Canonical: use 'agents' instead of 'roles'
research_specialist:
role: "Research Specialist"
backstory: |
instructions: # Canonical |
You are an experienced technology researcher with deep expertise in analyzing
emerging technologies and market trends. You excel at gathering comprehensive
information from various sources and synthesizing it into actionable insights.
@@ -35,7 +35,7 @@ roles:
content_creator:
role: "Technical Content Creator"
backstory: |
instructions: # Canonical |
You are a skilled technical writer and content creator who specializes in
translating complex technology concepts into engaging, accessible content
for various audiences including developers, business leaders, and end users.
@@ -64,7 +64,7 @@ roles:
quality_reviewer:
role: "Content Quality Reviewer"
backstory: |
instructions: # Canonical |
You are a meticulous editor and quality assurance specialist with extensive
experience in technical content review. You ensure accuracy, clarity, and
consistency while maintaining the intended tone and message.
@@ -2077,7 +2077,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -151,7 +151,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -533,7 +533,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -235,7 +235,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -1250,7 +1250,7 @@
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"TAVILY_API_KEY\"] = userdata.get('TAVILY_API_KEY') or \"ENTER TAVILY_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -1559,7 +1559,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -2159,7 +2159,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -698,7 +698,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -592,7 +592,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -572,7 +572,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -580,7 +580,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -252,7 +252,7 @@
"text": [
"\u001b[95m \n",
"\n",
"[{'title': 'CrewAI uses third-party models to automate business tasks', 'href': 'https://techcrunch.com/2024/10/22/crewai-uses-third-party-models-to-automate-business-tasks/', 'body': 'CrewAI, a startup developing a hub where companies can build automations using third-party AI models, has raised $18 million from investors including Andrew Ng. ... 4:00 AM PDT · October 22, 2024 ...'}, {'title': 'CrewAI Launches Multi-Agentic Platform to Deliver on the Promise of ...', 'href': 'https://markets.businessinsider.com/news/stocks/crewai-launches-multi-agentic-platform-to-deliver-on-the-promise-of-generative-ai-for-enterprise-1033870246?op=1', 'body': 'SAN FRANCISCO and SÃO PAULO, Oct. 22, 2024 (GLOBE NEWSWIRE) -- CrewAI, a leading multi-agent platform, today announced $18 million in total funding that included an inception round led by ...'}, {'title': 'Agentic AI startup CrewAI closes $18M funding round', 'href': 'https://siliconangle.com/2024/10/22/agentic-ai-startup-crewai-closes-18m-funding-round/', 'body': \"An e-commerce company, for example, could create an agent that uses GPT-4o to generate shopping advice based on customers' past purchases. CrewAI has created an open-source framework of the same ...\"}, {'title': 'CrewAI Company Profile 2024: Valuation, Funding & Investors - PitchBook', 'href': 'https://pitchbook.com/profiles/company/590845-78', 'body': \"Explore institutional-grade private market research from our team of analysts. ... Artificial Intelligence & Machine Learning; Artificial Intelligence & Machine Learning Report. September 19, 2024. CrewAI Executive Team (2) Update this profile Name ... CrewAI's primary industry is Business/Productivity Software. Is CrewAI a private or public ...\"}, {'title': 'CrewAI - Autonomous AI Agents in action for a market ... - LinkedIn', 'href': 'https://www.linkedin.com/pulse/crewai-autonomous-ai-agents-action-market-research-task-kithion-ovnrc', 'body': 'The will provide a detailed market trends report, the will generate a comprehensive analysis of top competitors, and the will develop a thorough marketing plan. Conclusion. CrewAI, combined with ...'}]\n",
"[{'title': 'CrewAI uses third-party models to automate business tasks', 'href': 'https://techcrunch.com/2024/10/22/crewai-uses-third-party-models-to-automate-business-tasks/', 'body': 'CrewAI, a startup developing a hub where companies can build automations using third-party AI models, has raised $18 million from investors including Andrew Ng. ... 4:00 AM PDT · October 22, 2024 ...'}, {'title': 'CrewAI Launches Multi-Agentic Platform to Deliver on the Promise of ...', 'href': 'https://markets.businessinsider.com/news/stocks/crewai-launches-multi-agentic-platform-to-deliver-on-the-promise-of-generative-ai-for-enterprise-1033870246?op=1', 'body': 'SAN FRANCISCO and SÃO PAULO, Oct. 22, 2024 (GLOBE NEWSWIRE) -- CrewAI, a leading multi-agent platform, today announced $18 million in total funding that included an inception round led by ...'}, {'title': 'Agentic AI startup CrewAI closes $18M funding round', 'href': 'https://siliconangle.com/2024/10/22/agentic-ai-startup-crewai-closes-18m-funding-round/', 'body': \"An e-commerce company, for example, could create an agent that uses gpt-5-nano to generate shopping advice based on customers' past purchases. CrewAI has created an open-source framework of the same ...\"}, {'title': 'CrewAI Company Profile 2024: Valuation, Funding & Investors - PitchBook', 'href': 'https://pitchbook.com/profiles/company/590845-78', 'body': \"Explore institutional-grade private market research from our team of analysts. ... Artificial Intelligence & Machine Learning; Artificial Intelligence & Machine Learning Report. September 19, 2024. CrewAI Executive Team (2) Update this profile Name ... CrewAI's primary industry is Business/Productivity Software. Is CrewAI a private or public ...\"}, {'title': 'CrewAI - Autonomous AI Agents in action for a market ... - LinkedIn', 'href': 'https://www.linkedin.com/pulse/crewai-autonomous-ai-agents-action-market-research-task-kithion-ovnrc', 'body': 'The will provide a detailed market trends report, the will generate a comprehensive analysis of top competitors, and the will develop a thorough marketing plan. Conclusion. CrewAI, combined with ...'}]\n",
"\u001b[00m\n",
"\u001b[32;1m\u001b[1;3mThought: I have found more information about CrewAI's target customers and market positioning. CrewAI is a startup that has developed a hub where companies can build automations using third-party AI models, and it has recently raised $18 million in funding. Their target customers are likely businesses looking to automate complex tasks and improve efficiency using AI. They are positioned as a platform for deploying and managing AI agents to automate a variety of tasks.\n",
"\n",
@@ -1075,7 +1075,7 @@
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"EXA_API_KEY\"] = userdata.get('EXA_API_KEY') or \"ENTER EXA_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -667,7 +667,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -1947,7 +1947,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -73,7 +73,7 @@
" url=url,\n",
" word_count_threshold=1,\n",
" extraction_strategy= LLMExtractionStrategy(\n",
" provider=\"openai/gpt-4o\",\n",
" provider=\"openai/gpt-5-nano\",\n",
" api_token=os.getenv('OPENAI_API_KEY'),\n",
" schema=ModelFee.schema(),\n",
" extraction_type=\"schema\",\n",
@@ -666,7 +666,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -475,7 +475,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -2130,7 +2130,7 @@
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"SERPER_API_KEY\"] = userdata.get('SERPER_API_KEY') or \"ENTER SERPER_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -635,7 +635,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -564,7 +564,7 @@
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"TAVILY_API_KEY\"] = userdata.get('TAVILY_API_KEY') or \"ENTER TAVILY_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -564,7 +564,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -614,7 +614,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -66,7 +66,7 @@
"\n",
"# Set up OpenAI API key (add to Google Colab secrets)\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\""
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\""
]
},
{
@@ -8,10 +8,10 @@ variables:
industry: "Electric Vehicles"
research_focus: "comprehensive market analysis"
roles:
agents: # Canonical: use 'agents' instead of 'roles'
market_overview_specialist:
role: "Market Overview Specialist"
backstory: |
instructions: # Canonical |
You are a seasoned market research analyst with 10+ years of experience
in analyzing market dynamics, trends, and growth patterns across various
industries. You excel at synthesizing complex market data into clear,
@@ -22,7 +22,7 @@ roles:
verbose: true
allow_delegation: false
llm:
model: "gpt-4o-mini"
model: "gpt-5-nano"
temperature: 0.3
tools:
- "InternetSearchTool"
@@ -64,7 +64,7 @@ roles:
competitive_intelligence_analyst:
role: "Competitive Intelligence Analyst"
backstory: |
instructions: # Canonical |
You are a competitive intelligence expert specializing in analyzing
competitive landscapes, market positioning, and strategic intelligence.
You have deep expertise in competitor analysis, market share assessment,
@@ -76,7 +76,7 @@ roles:
verbose: true
allow_delegation: false
llm:
model: "gpt-4o-mini"
model: "gpt-5-nano"
temperature: 0.3
tools:
- "InternetSearchTool"
@@ -119,7 +119,7 @@ roles:
financial_performance_analyst:
role: "Financial Performance Analyst"
backstory: |
instructions: # Canonical |
You are a financial analyst with expertise in corporate finance,
financial statement analysis, and industry benchmarking. You specialize
in analyzing financial performance metrics, trends, and comparative
@@ -130,7 +130,7 @@ roles:
verbose: true
allow_delegation: false
llm:
model: "gpt-4o-mini"
model: "gpt-5-nano"
temperature: 0.3
tools:
- "InternetSearchTool"
@@ -173,7 +173,7 @@ roles:
growth_opportunities_researcher:
role: "Growth Opportunities Researcher"
backstory: |
instructions: # Canonical |
You are a strategic business analyst specializing in identifying growth
opportunities, market expansion strategies, and emerging business models.
You excel at spotting trends, gaps, and untapped potential in markets
@@ -185,7 +185,7 @@ roles:
verbose: true
allow_delegation: false
llm:
model: "gpt-4o-mini"
model: "gpt-5-nano"
temperature: 0.4
tools:
- "InternetSearchTool"
@@ -228,7 +228,7 @@ roles:
risk_assessment_specialist:
role: "Risk Assessment Specialist"
backstory: |
instructions: # Canonical |
You are a risk management expert with extensive experience in identifying,
analyzing, and assessing business risks across various industries. You
specialize in market risks, competitive threats, regulatory challenges,
@@ -239,7 +239,7 @@ roles:
verbose: true
allow_delegation: false
llm:
model: "gpt-4o-mini"
model: "gpt-5-nano"
temperature: 0.3
tools:
- "InternetSearchTool"
@@ -287,7 +287,7 @@ roles:
research_report_synthesizer:
role: "Research Report Synthesizer"
backstory: |
instructions: # Canonical |
You are an expert business report writer and analyst with extensive
experience in synthesizing complex research findings into clear,
actionable business intelligence reports. You excel at creating
@@ -299,7 +299,7 @@ roles:
verbose: true
allow_delegation: false
llm:
model: "gpt-4o-mini"
model: "gpt-5-nano"
temperature: 0.3
tasks:
report_synthesis:
@@ -462,7 +462,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -380,7 +380,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -540,7 +540,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -2639,7 +2639,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -1835,7 +1835,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -623,7 +623,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -635,7 +635,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
@@ -582,7 +582,7 @@
"\n",
"# Add OPENAI_API_KEY Secrets to Google Colab on the Left Hand Side 🔑 or Enter Manually Below\n",
"os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY') or \"ENTER OPENAI_API_KEY HERE\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-4o-mini\"\n",
"os.environ[\"OPENAI_MODEL_NAME\"] = \"gpt-5-nano\"\n",
"\n",
"# Run PraisonAI\n",
"result = praisonai.run()\n",
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""
Fixed example demonstrating proper guardrail usage with PraisonAI Agents.
This addresses the issues reported in issue #875.
"""
from praisonaiagents import Agent, Task, GuardrailResult, PraisonAIAgents, TaskOutput
from typing import Tuple, Any
import trafilatura
# Example 1: Using GuardrailResult return type (now supported!)
def validate_length_guardrailresult(output: TaskOutput) -> GuardrailResult:
"""Ensure output is between 100-500 characters using GuardrailResult"""
# Extract the raw text from the TaskOutput object
text = output.raw if hasattr(output, 'raw') else str(output)
length = len(text)
if 100 <= length <= 500:
return GuardrailResult(
success=True,
result=output, # Pass through the original output
error=""
)
else:
return GuardrailResult(
success=False,
result=None,
error=f"Output must be 100-500 chars, got {length}"
)
# Example 2: Using Tuple[bool, Any] return type (original method)
def validate_length_tuple(output: TaskOutput) -> Tuple[bool, Any]:
"""Ensure output is between 100-500 characters using tuple"""
text = output.raw if hasattr(output, 'raw') else str(output)
length = len(text)
if 100 <= length <= 500:
return True, output
else:
return False, f"Output must be 100-500 chars, got {length}"
# Tool function
def get_url_context(url):
"""Fetch and extract content from a URL"""
downloaded = trafilatura.fetch_url(url)
if not downloaded:
return "Sorry, I couldn't fetch the content from that URL."
extracted = trafilatura.extract(
downloaded,
include_comments=False,
include_links=True,
output_format='json',
with_metadata=True,
url=url
)
if not extracted:
return "Sorry, I couldn't extract readable content from that page."
return extracted # returns JSON string
# Create agent with FIXED tools parameter (must be a list!)
agent = Agent(
name="Content Summarizer",
role="Content Analysis Expert",
goal="Summarize web content concisely",
instructions="You are a helpful assistant that summarizes web content",
llm="gemini/gemini-2.5-flash-lite-preview-06-17",
self_reflect=False,
verbose=True,
tools=[get_url_context] # FIX: tools must be a list, not a single function
)
# Create task with GuardrailResult guardrail
task_with_guardrailresult = Task(
name="summarise article with GuardrailResult",
description="get the context of this url: https://blog.google/technology/ai/dolphingemma/ and produce a summary below 500 characters",
agent=agent,
guardrail=validate_length_guardrailresult, # Using GuardrailResult
expected_output="summary of the article below 500 characters",
max_retries=3 # Will retry up to 3 times if guardrail fails
)
# Alternative: Create task with tuple guardrail
task_with_tuple = Task(
name="summarise article with tuple",
description="get the context of this url: https://blog.google/technology/ai/dolphingemma/ and produce a summary below 500 characters",
agent=agent,
guardrail=validate_length_tuple, # Using Tuple[bool, Any]
expected_output="summary of the article below 500 characters",
max_retries=3
)
# Example with string-based LLM guardrail
task_with_llm_guardrail = Task(
name="summarise with LLM guardrail",
description="get the context of this url: https://blog.google/technology/ai/dolphingemma/ and produce a summary",
agent=agent,
guardrail="Ensure the summary is professional, factual, and between 100-500 characters",
expected_output="professional summary of the article"
)
# Run with GuardrailResult example
print("=== Running with GuardrailResult guardrail ===")
agents_gr = PraisonAIAgents(
agents=[agent],
tasks=[task_with_guardrailresult]
)
# Uncomment to run:
# result_gr = agents_gr.start()
# Run with Tuple example
print("\n=== Running with Tuple[bool, Any] guardrail ===")
agents_tuple = PraisonAIAgents(
agents=[agent],
tasks=[task_with_tuple]
)
# Uncomment to run:
# result_tuple = agents_tuple.start()
# Run with LLM guardrail example
print("\n=== Running with LLM-based guardrail ===")
agents_llm = PraisonAIAgents(
agents=[agent],
tasks=[task_with_llm_guardrail]
)
# Uncomment to run:
# result_llm = agents_llm.start()
print("""
Key fixes applied:
1. GuardrailResult is now accepted as a valid return type annotation
2. tools parameter must be a list: tools=[get_url_context] not tools=get_url_context
3. Both GuardrailResult and Tuple[bool, Any] return types are supported
4. String-based LLM guardrails are also supported
The guardrail will automatically retry (up to max_retries times) if validation fails.
""")
+53
View File
@@ -0,0 +1,53 @@
"""
PraisonAI A2A Server Example
Expose a PraisonAI Agent as an A2A (Agent2Agent) Server.
This enables other AI agents to discover and communicate with your agent.
Run:
uvicorn a2a-server:app --reload
Endpoints:
GET /.well-known/agent.json - Agent Card for discovery
GET /status - Server status
"""
from praisonaiagents import Agent, A2A
from fastapi import FastAPI
# Create an agent with tools
def search_web(query: str) -> str:
"""Search the web for information."""
return f"Search results for: {query}"
def calculate(expression: str) -> str:
"""Calculate a mathematical expression."""
try:
return f"Result: {eval(expression)}"
except Exception:
return "Invalid expression"
agent = Agent(
name="Research Assistant",
role="Research Analyst",
goal="Help users research topics and answer questions",
tools=[search_web, calculate]
)
# Expose as A2A Server
a2a = A2A(
agent=agent,
url="http://localhost:8000/a2a",
version="1.0.0"
)
# Create FastAPI app
app = FastAPI(
title="PraisonAI A2A Server",
description="A2A-compatible agent server"
)
app.include_router(a2a.get_router())
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
@@ -0,0 +1,259 @@
# Multi-Provider/Multi-Model Support
PraisonAI now supports intelligent multi-provider and multi-model capabilities, allowing agents to automatically select the most appropriate AI model based on task requirements, cost considerations, and performance needs.
## 🚀 Key Features
### 1. **Automatic Model Selection**
- Analyzes task complexity and selects the best model
- Considers cost vs. performance trade-offs
- Supports fallback mechanisms for reliability
### 2. **Cost Optimization**
- Routes simple tasks to cheaper models (e.g., gpt-5-nano, Gemini Flash)
- Reserves expensive models for complex tasks
- Tracks usage and provides cost estimates
### 3. **Multi-Provider Support**
- Works with OpenAI, Anthropic, Google, Groq, and more
- Seamless switching between providers
- Provider preference settings
### 4. **Flexible Routing Strategies**
- `auto`: Automatic selection based on task analysis
- `cost-optimized`: Prioritize cheaper models
- `performance-optimized`: Prioritize capability
- `manual`: Use specified model
## 📦 Installation
The multi-provider support is included in the standard installation:
```bash
pip install praisonaiagents
```
## 🔧 Basic Usage
### Simple Multi-Model Agent
```python
from praisonaiagents import Task, PraisonAIAgents
from praisonaiagents.agent import RouterAgent
# Create a multi-model agent
agent = RouterAgent(
name="Smart Assistant",
role="Adaptive AI Assistant",
goal="Complete tasks using the most appropriate model",
models=["gpt-5-nano", "gpt-5-nano", "claude-3-5-sonnet-20241022"],
routing_strategy="auto" # Automatic model selection
)
# Create tasks
simple_task = Task(
name="calculate",
description="What is 15% of 250?",
agent=agent
)
complex_task = Task(
name="analyze",
description="Write a Python implementation of the A* pathfinding algorithm",
agent=agent
)
# Run tasks - agent will automatically select appropriate models
agents = PraisonAIAgents(
agents=[agent],
tasks=[simple_task, complex_task]
)
results = agents.start()
```
### Cost-Optimized Workflow
```python
from praisonaiagents.llm import ModelRouter
# Create custom router with cost constraints
router = ModelRouter(
cost_threshold=0.005, # Max $0.005 per 1k tokens
preferred_providers=["google", "openai"]
)
# Create cost-conscious agent
analyzer = RouterAgent(
name="Budget Analyzer",
role="Data Analyst",
goal="Analyze data efficiently",
models={
"gemini/gemini-1.5-flash": {},
"gpt-5-nano": {},
"claude-3-haiku-20240307": {}
},
model_router=router,
routing_strategy="cost-optimized"
)
```
## 🎯 Routing Strategies
### Auto Routing (Default)
Automatically selects models based on:
- Task complexity analysis
- Required capabilities (tools, vision, etc.)
- Context size requirements
- Cost/performance balance
### Cost-Optimized
Prioritizes cheaper models while meeting task requirements:
- Uses lightweight models for simple tasks
- Only escalates to expensive models when necessary
- Ideal for high-volume operations
### Performance-Optimized
Prioritizes model capability:
- Uses the best available model for the task
- Ideal for quality-critical applications
- Less concern for cost
### Manual
Uses the specified model without routing:
- Direct control over model selection
- Useful for testing or specific requirements
## 📊 Model Profiles
The system includes pre-configured profiles for popular models:
| Model | Provider | Best For | Cost/1k tokens |
|-------|----------|----------|----------------|
| gpt-5-nano | OpenAI | Simple tasks, speed | $0.00075 |
| gemini-1.5-flash | Google | Cost-effective, multimodal | $0.000125 |
| claude-3-haiku | Anthropic | Fast responses | $0.0008 |
| gpt-5-nano | OpenAI | General purpose | $0.0075 |
| claude-3-5-sonnet-20241022 | Anthropic | Complex reasoning | $0.009 |
| deepseek-chat | DeepSeek | Code & math | $0.0014 |
## 🔍 Task Complexity Analysis
The system analyzes tasks to determine complexity:
- **Simple**: Basic calculations, definitions, yes/no questions
- **Moderate**: Summarization, basic analysis, classification
- **Complex**: Code generation, algorithm implementation
- **Very Complex**: Multi-step reasoning, system design
## 📈 Usage Tracking
Track model usage and costs:
```python
# Get usage report
report = agent.get_usage_report()
print(report)
# Output:
{
'agent_name': 'Smart Assistant',
'routing_strategy': 'auto',
'model_usage': {
'gpt-5-nano': {'calls': 5, 'tokens': 1500, 'cost': 0.0011},
'gpt-5-nano': {'calls': 2, 'tokens': 3000, 'cost': 0.0225}
},
'total_cost_estimate': 0.0236,
'total_calls': 7
}
```
## 🛠️ Custom Model Configuration
Add custom model profiles:
```python
from praisonaiagents.llm import ModelProfile, TaskComplexity
custom_model = ModelProfile(
name="custom-model",
provider="custom",
complexity_range=(TaskComplexity.SIMPLE, TaskComplexity.MODERATE),
cost_per_1k_tokens=0.002,
strengths=["domain-specific"],
capabilities=["text"],
context_window=32000
)
router = ModelRouter(models=[custom_model])
```
## 🔗 Integration with AutoAgents
Works seamlessly with AutoAgents:
```python
from praisonaiagents.agents import AutoAgents
# Create auto agents
auto = AutoAgents(
instructions="Analyze market trends and create a report",
max_agents=3
)
# Convert to multi-model agents
for i, agent in enumerate(auto.agents):
auto.agents[i] = RouterAgent(
name=agent.name,
role=agent.role,
goal=agent.goal,
models=["gpt-5-nano", "gpt-5-nano", "claude-3-5-sonnet"],
routing_strategy="auto"
)
results = auto.start()
```
## 🌟 Best Practices
1. **Start with Auto Routing**: Let the system learn your needs
2. **Monitor Costs**: Use usage reports to optimize
3. **Set Cost Thresholds**: Prevent unexpected expenses
4. **Use Appropriate Models**: Don't use GPT-4 for simple math
5. **Leverage Fallbacks**: Configure fallback models for reliability
## 🔐 Environment Variables
Set API keys for each provider:
```bash
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export GEMINI_API_KEY="..."
export GROQ_API_KEY="..."
```
## 🤝 Contributing
The multi-provider system is extensible. To add new models:
1. Add model profile to `ModelRouter.DEFAULT_MODELS`
2. Ensure the provider is supported by LiteLLM
3. Test with various task complexities
## 📚 Examples
See the complete example in `examples/python/agents/multi-provider-agent.py` for:
- Auto-routing examples
- Cost-optimized workflows
- Performance-optimized agents
- Custom routing logic
- Integration patterns
## 🎉 Benefits
- **Cost Savings**: Reduce API costs by 50-80%
- **Better Performance**: Use the right tool for each job
- **Flexibility**: Switch providers without code changes
- **Reliability**: Automatic fallbacks and error handling
- **Transparency**: Track usage and costs
@@ -0,0 +1,73 @@
"""
AutoAgents Hierarchical Generation Example
This example demonstrates hierarchical agent patterns using PraisonAI
for structured task delegation and coordinated workflows.
"""
from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import internet_search
print("=== AutoAgents Hierarchical Generation Example ===\n")
# Create manager agent for hierarchical coordination
manager_agent = Agent(
name="Project Manager",
role="Project Coordinator",
goal="Coordinate hierarchical task execution and manage team workflow",
backstory="Experienced manager who excels at breaking down complex projects and coordinating teams",
tools=[internet_search],
allow_delegation=True,
verbose=True
)
# Create specialist agent for execution
research_agent = Agent(
name="Research Specialist",
role="Market Research Analyst",
goal="Conduct thorough market research and analysis",
backstory="Expert researcher skilled in market analysis and competitive intelligence",
tools=[internet_search],
verbose=True
)
# Hierarchical task structure
planning_task = Task(
description="""Plan a comprehensive market research project for electric vehicles:
1. Define research scope and objectives
2. Identify key research areas and methodologies
3. Create task breakdown structure
4. Set deliverable requirements for execution team
Prepare clear instructions for the research specialist.""",
expected_output="Detailed project plan with clear research instructions",
agent=manager_agent
)
execution_task = Task(
description="""Execute the market research plan:
1. Follow the research plan from the project manager
2. Conduct comprehensive market analysis
3. Gather competitive intelligence and market data
4. Prepare detailed findings report
Use the planning guidance to ensure complete coverage.""",
expected_output="Comprehensive market research report with findings",
agent=research_agent,
context=[planning_task]
)
# Run hierarchical workflow
agents_system = PraisonAIAgents(
agents=[manager_agent, research_agent],
tasks=[planning_task, execution_task],
process="sequential",
verbose=True
)
print("Starting hierarchical agent generation...")
result = agents_system.start()
print(f"\nHierarchical Result: {result[:200]}...")
print("\n✅ AutoAgents hierarchical generation complete!")
print("Demonstrated coordinated hierarchical workflow between manager and specialist agents.")
@@ -0,0 +1,132 @@
"""
AutoAgents Workflow Patterns Example
This example demonstrates the new workflow auto-generation features:
- Dynamic agent count based on task complexity
- Multiple workflow patterns (sequential, parallel, routing, orchestrator-workers, evaluator-optimizer)
- Pattern recommendation based on task keywords
Documentation: https://docs.praison.ai/features/autoagents
CLI Reference: https://docs.praison.ai/nocode/auto
"""
from praisonai.auto import AutoGenerator, WorkflowAutoGenerator
import os
import tempfile
# Ensure API key is set
if not os.environ.get("OPENAI_API_KEY"):
print("Please set OPENAI_API_KEY environment variable")
exit(1)
print("=" * 60)
print("AutoAgents Workflow Patterns Demo")
print("=" * 60)
# =============================================================================
# Example 1: Dynamic Agent Count (Simple vs Complex Tasks)
# =============================================================================
print("\n📊 Example 1: Dynamic Agent Count")
print("-" * 40)
# Simple task - should create 1-2 agents
with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
simple_file = f.name
simple_generator = AutoGenerator(
topic="Write a haiku about spring",
agent_file=simple_file,
framework="praisonai"
)
print("Simple task: 'Write a haiku about spring'")
result = simple_generator.generate()
print(f"Generated: {result}")
# Complex task - should create 3-4 agents
with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
complex_file = f.name
complex_generator = AutoGenerator(
topic="Research AI trends, analyze market data, write a comprehensive report with executive summary",
agent_file=complex_file,
framework="praisonai"
)
print("\nComplex task: 'Research AI trends, analyze market data...'")
result = complex_generator.generate()
print(f"Generated: {result}")
# =============================================================================
# Example 2: Pattern Recommendation
# =============================================================================
print("\n🎯 Example 2: Pattern Recommendation")
print("-" * 40)
test_tasks = [
("Write a blog post", "sequential"),
("Research from multiple sources simultaneously", "parallel"),
("Classify and route customer requests", "routing"),
("Comprehensive analysis and break down the problem", "orchestrator-workers"),
("Refine and improve content quality", "evaluator-optimizer"),
]
for task, expected in test_tasks:
generator = WorkflowAutoGenerator(topic=task)
recommended = generator.recommend_pattern()
status = "✅" if recommended == expected else "⚠️"
print(f"{status} Task: '{task[:40]}...'")
print(f" Recommended: {recommended}")
# =============================================================================
# Example 3: Generate Workflow with Specific Pattern
# =============================================================================
print("\n🔄 Example 3: Generate Workflows with Patterns")
print("-" * 40)
patterns = ["sequential", "parallel", "orchestrator-workers", "evaluator-optimizer"]
for pattern in patterns:
with tempfile.NamedTemporaryFile(mode='w', suffix='.yaml', delete=False) as f:
workflow_file = f.name
generator = WorkflowAutoGenerator(
topic="Create a market analysis report",
workflow_file=workflow_file
)
print(f"\n📋 Pattern: {pattern}")
result = generator.generate(pattern=pattern)
print(f" Generated: {result}")
# Read and show structure
import yaml
with open(result, 'r') as f:
data = yaml.safe_load(f)
print(f" Agents: {list(data.get('agents', {}).keys())}")
print(f" Steps: {len(data.get('steps', []))}")
# =============================================================================
# Example 4: CLI Usage (for reference)
# =============================================================================
print("\n💻 Example 4: CLI Commands (for reference)")
print("-" * 40)
print("""
# Auto-generate agents (dynamic count)
praisonai --auto "Write a haiku about spring"
# Auto-generate workflow with pattern
praisonai workflow auto "Research and write a report" --pattern sequential
praisonai workflow auto "Research from multiple sources" --pattern parallel
praisonai workflow auto "Comprehensive market analysis" --pattern orchestrator-workers
praisonai workflow auto "Refine content quality" --pattern evaluator-optimizer
# With output file
praisonai workflow auto "Customer support routing" --pattern routing --output support.yaml
""")
print("\n" + "=" * 60)
print("✅ AutoAgents Workflow Patterns Demo Complete!")
print("=" * 60)
print("\nDocumentation: https://docs.praison.ai/features/autoagents")
print("CLI Reference: https://docs.praison.ai/nocode/auto")
Loaded 100 of 943 files, more files were not shown because too many files have changed in this diff. Show more