From 3f143240367dc3ba0a6ecce35e2841afdad12c07 Mon Sep 17 00:00:00 2001 From: Dhivya-Bharathy Date: Thu, 4 Jun 2026 16:28:48 +0530 Subject: [PATCH 1/8] fix(examples): resolve syntax errors and align with consolidated-params API --- examples/agent_centric_api.py | 2 +- examples/benchmark/benchmark_example.py | 6 ++--- examples/compare/cli_compare_advanced.py | 2 +- examples/compare/cli_compare_basic.py | 2 +- .../consolidated_params/advanced_memory.py | 2 +- .../consolidated_params/basic_workflow.py | 14 ++++++++++- examples/eval/accuracy_example.py | 4 +-- examples/eval/criteria_example.py | 4 +-- examples/eval/performance_example.py | 2 +- examples/eval/reliability_example.py | 4 +-- examples/knowledge/compression_demo.py | 2 +- .../knowledge/hierarchical_summaries_demo.py | 2 +- .../knowledge/large_corpus_strategy_demo.py | 4 +-- examples/knowledge/mem0_backend_example.py | 2 +- .../knowledge/scope_identifiers_example.py | 4 +-- examples/knowledge/scope_isolation_example.py | 4 +-- examples/persistence/knowledge_qdrant.py | 4 +-- .../python/cli/git_integration_example.py | 2 +- examples/python/cli/repo_map_example.py | 2 +- .../python/cli/sandbox_execution_example.py | 2 +- examples/python/concepts/chat-with-pdf.py | 3 +-- .../python/concepts/knowledge-agents-task.py | 25 +++++++++++++++---- .../concepts/knowledge-reranker-example.py | 3 +-- examples/python/concepts/rag-agents.py | 10 +++++--- examples/python/general/memory_example.py | 4 +-- .../advanced-graph-memory-integration.py | 4 +-- .../advanced-memory-search-optimization.py | 4 +-- .../python/memory/gemini-embedding-example.py | 2 +- examples/python/memory/graph-memory-agent.py | 3 +-- .../python/memory_with_tracing_example.py | 2 +- .../deepseek/deepseek-rag-agents-streamlit.py | 5 ++-- .../models/deepseek/deepseek-rag-agents.py | 5 ++-- .../mongodb/mongodb_comprehensive_example.py | 4 +-- .../mongodb/mongodb_knowledge_example.py | 6 +++-- .../python/mongodb/mongodb_memory_example.py | 4 +-- examples/python/rag/agent_vs_auto_rag.py | 2 +- examples/python/rag/auto_rag_agent_basic.py | 7 +++--- examples/python/rag/auto_rag_agent_policy.py | 2 +- examples/python/rag/rag_basic.py | 2 +- examples/python/rag/rag_hybrid.py | 2 +- examples/python/rag/rag_with_citations.py | 2 +- .../comprehensive-session-management.py | 2 +- .../python/stateful/memory-quality-example.py | 10 +++----- examples/python/stateful/session-example.py | 2 +- .../python/stateful/workflow-state-example.py | 3 +-- .../python/ui/ollama-rag-agents-streamlit.py | 5 ++-- .../usecases/domain-context-solution.py | 7 +++--- examples/rag/external_sources.py | 2 +- .../examples/recipe_runtime_example.yaml | 2 +- 49 files changed, 114 insertions(+), 90 deletions(-) diff --git a/examples/agent_centric_api.py b/examples/agent_centric_api.py index dc128704d..fe78f4f77 100644 --- a/examples/agent_centric_api.py +++ b/examples/agent_centric_api.py @@ -52,7 +52,7 @@ def example_with_config(): instructions="You are a research assistant", memory=MemoryConfig( backend="file", - user_id="researcher_001", + memory={"user_id": "researcher_001"}, auto_memory=True, ), reflection=ReflectionConfig( diff --git a/examples/benchmark/benchmark_example.py b/examples/benchmark/benchmark_example.py index 1df238077..e957b5976 100644 --- a/examples/benchmark/benchmark_example.py +++ b/examples/benchmark/benchmark_example.py @@ -35,7 +35,7 @@ def run_quick_comparison(): prompt="What is 2+2?", iterations=2, paths=["openai_sdk", "praisonai_agent"], - output="verbose" + verbose=True ) # Print comparison table @@ -56,7 +56,7 @@ def run_full_benchmark(): report = handler.run_full_benchmark( prompt="Hi", iterations=3, - output="verbose" + verbose=True ) # Print full report @@ -78,7 +78,7 @@ def run_agent_benchmark(): prompt="Explain Python in one sentence", iterations=3, paths=["openai_sdk", "praisonai_agent"], - output="verbose" + verbose=True ) # Show timeline diagrams diff --git a/examples/compare/cli_compare_advanced.py b/examples/compare/cli_compare_advanced.py index 45a10265b..819602f8b 100644 --- a/examples/compare/cli_compare_advanced.py +++ b/examples/compare/cli_compare_advanced.py @@ -22,7 +22,7 @@ } # Create handler with verbose output -handler = CompareHandler(output="verbose") +handler = CompareHandler(verbose=True) # Example: Manually create comparison results for analysis # (useful for testing without API calls) diff --git a/examples/compare/cli_compare_basic.py b/examples/compare/cli_compare_basic.py index 9c4a433e1..272b33e32 100644 --- a/examples/compare/cli_compare_basic.py +++ b/examples/compare/cli_compare_basic.py @@ -22,7 +22,7 @@ print(f"\nParsed modes: {modes}") # Create compare handler -handler = CompareHandler(output="verbose") +handler = CompareHandler(verbose=True) # Compare modes (this will run actual agent calls) # Uncomment to run: diff --git a/examples/consolidated_params/advanced_memory.py b/examples/consolidated_params/advanced_memory.py index be1cac14e..3cb6be071 100644 --- a/examples/consolidated_params/advanced_memory.py +++ b/examples/consolidated_params/advanced_memory.py @@ -15,7 +15,7 @@ # With array [preset, overrides] agent_override = Agent( instructions="You are a helpful assistant.", - memory=["redis", {"user_id": "custom_user"}], + memory=MemoryConfig(backend="redis", user_id="custom_user"), ) if __name__ == "__main__": diff --git a/examples/consolidated_params/basic_workflow.py b/examples/consolidated_params/basic_workflow.py index 72d07e171..975c46c78 100644 --- a/examples/consolidated_params/basic_workflow.py +++ b/examples/consolidated_params/basic_workflow.py @@ -15,8 +15,20 @@ ], output="verbose", planning=True, + variables={"topic": "AI agents"}, ) if __name__ == "__main__": - result = workflow.run(variables={"topic": "AI agents"}) + import os + import sys + + if not os.environ.get("OPENAI_API_KEY"): + print("Set OPENAI_API_KEY to run this example.") + sys.exit(0) + if sys.platform == "win32": + try: + sys.stdout.reconfigure(encoding="utf-8") + except Exception: + pass + result = workflow.run("AI agents") print(result) diff --git a/examples/eval/accuracy_example.py b/examples/eval/accuracy_example.py index be2b80324..4ed779e86 100644 --- a/examples/eval/accuracy_example.py +++ b/examples/eval/accuracy_example.py @@ -24,7 +24,7 @@ input_text="What is 2 + 2?", expected_output="4", num_iterations=3, # Run 3 times for statistical significance - output="verbose" + verbose=True ) # Run evaluation @@ -42,7 +42,7 @@ input_text="What is 2 + 2?", expected_output="4", num_iterations=1, - output="verbose" + verbose=True ) # Test with mock output diff --git a/examples/eval/criteria_example.py b/examples/eval/criteria_example.py index 60752dc0f..02074b4a5 100644 --- a/examples/eval/criteria_example.py +++ b/examples/eval/criteria_example.py @@ -27,7 +27,7 @@ scoring_type="numeric", # Score 1-10 threshold=7.0, # Pass if score >= 7 num_iterations=2, - output="verbose" + verbose=True ) # Run evaluation @@ -45,7 +45,7 @@ agent=agent, input_text="Tell me a joke", scoring_type="binary", # Pass or Fail - output="verbose" + verbose=True ) binary_result = binary_evaluator.run(print_summary=True) diff --git a/examples/eval/performance_example.py b/examples/eval/performance_example.py index 784dc1723..8c6df30e6 100644 --- a/examples/eval/performance_example.py +++ b/examples/eval/performance_example.py @@ -26,7 +26,7 @@ num_iterations=10, # Run 10 benchmark iterations warmup_runs=2, # 2 warmup runs before measurement track_memory=True, # Track memory usage - output="verbose" + verbose=True ) # Run evaluation diff --git a/examples/eval/reliability_example.py b/examples/eval/reliability_example.py index e5fb646b6..0603faf82 100644 --- a/examples/eval/reliability_example.py +++ b/examples/eval/reliability_example.py @@ -48,7 +48,7 @@ def _ev(n): input_text="Search for the weather in Paris and calculate 25 * 4", expected_tools=["search_web", "calculate"], # Tools that should be called forbidden_tools=["delete_file"], # Tools that should NOT be called - output="verbose" + verbose=True ) # Run evaluation @@ -70,7 +70,7 @@ def _ev(n): agent=mock_agent, expected_tools=["search_web", "calculate"], # Tools that should be called forbidden_tools=["delete_file"], # Tools that should NOT be called - output="verbose" + verbose=True ) result2 = evaluator.evaluate_tool_calls( diff --git a/examples/knowledge/compression_demo.py b/examples/knowledge/compression_demo.py index 70059a457..17f2eeaec 100644 --- a/examples/knowledge/compression_demo.py +++ b/examples/knowledge/compression_demo.py @@ -184,7 +184,7 @@ def main(): When asked about codes, provide the EXACT code from the documents. Be concise but accurate.""", knowledge=[temp_dir], - user_id="compression_demo_user", + memory={"user_id": "compression_demo_user"}, output="verbose", ) diff --git a/examples/knowledge/hierarchical_summaries_demo.py b/examples/knowledge/hierarchical_summaries_demo.py index a9b973ad3..2715d4563 100644 --- a/examples/knowledge/hierarchical_summaries_demo.py +++ b/examples/knowledge/hierarchical_summaries_demo.py @@ -164,7 +164,7 @@ def main(): When asked about department codes, provide the EXACT code from the documents. Be specific about which department you're referring to.""", knowledge=[temp_dir], - user_id="hierarchy_demo_user", + memory={"user_id": "hierarchy_demo_user"}, output="verbose", ) diff --git a/examples/knowledge/large_corpus_strategy_demo.py b/examples/knowledge/large_corpus_strategy_demo.py index 7d00e9385..b20858618 100644 --- a/examples/knowledge/large_corpus_strategy_demo.py +++ b/examples/knowledge/large_corpus_strategy_demo.py @@ -124,7 +124,7 @@ def main(): # Show strategy selection for different corpus sizes print(f"\nStrategy selection by corpus size:") for size in [100, 1000, 10000, 50000, 100000]: - strategy = select_strategy(corpus_tokens=size) + strategy = select_strategy(CorpusStats(file_count=max(1, size // 1000), total_tokens=size)) print(f" {size:>6} tokens -> {strategy.value}") except ImportError as e: @@ -142,7 +142,7 @@ def main(): When asked about verification codes, provide the EXACT code from the documents. If information is not in the context, say 'Information not found in documents.'""", knowledge=[temp_dir], - user_id="strategy_demo_user", + memory={"user_id": "strategy_demo_user"}, output="verbose", # Use new consolidated param ) diff --git a/examples/knowledge/mem0_backend_example.py b/examples/knowledge/mem0_backend_example.py index 484b15521..603794890 100644 --- a/examples/knowledge/mem0_backend_example.py +++ b/examples/knowledge/mem0_backend_example.py @@ -65,7 +65,7 @@ def main(): name="PolicyExpert", instructions="You are a company policy expert. Answer questions based ONLY on the provided knowledge. Quote exact values when asked about codes or numbers.", knowledge=[temp_dir], # Add directory with documents - user_id="example_user", # Required for mem0 backend + memory={"user_id": "example_user"}, ) print("\n1. Testing Agent.chat() with context-required question:") diff --git a/examples/knowledge/scope_identifiers_example.py b/examples/knowledge/scope_identifiers_example.py index 4ef213fd1..31753d011 100644 --- a/examples/knowledge/scope_identifiers_example.py +++ b/examples/knowledge/scope_identifiers_example.py @@ -50,7 +50,7 @@ def main(): name="HR_Assistant_User1", instructions="You are an HR assistant.", knowledge=[temp_dir], - user_id="user_alice", # Knowledge scoped to Alice + memory={"user_id": "user_alice"}, ) response = user1_agent.chat("What is the policy on remote work?") @@ -80,7 +80,7 @@ def main(): name="Personal_HR_Bot", instructions="You are a personal HR assistant.", knowledge=[temp_dir], - user_id="user_bob", + memory={"user_id": "user_bob"}, agent_id="hr_bot_v2", ) diff --git a/examples/knowledge/scope_isolation_example.py b/examples/knowledge/scope_isolation_example.py index e7d0aabf8..90c11a7de 100644 --- a/examples/knowledge/scope_isolation_example.py +++ b/examples/knowledge/scope_isolation_example.py @@ -49,7 +49,7 @@ def main(): name="AgentA_Ingester", instructions="You ingest and store knowledge.", knowledge=[temp_dir], - user_id="user_alice", # Scoped to Alice + memory={"user_id": "user_alice"}, output="silent", ) @@ -103,7 +103,7 @@ def main(): name="AgentB_Querier", instructions="Answer questions based on the provided knowledge. If you don't have the information, say so.", knowledge=[temp_dir], - user_id="user_alice", # Same scope as Agent A + memory={"user_id": "user_alice"}, output="silent", ) diff --git a/examples/persistence/knowledge_qdrant.py b/examples/persistence/knowledge_qdrant.py index 9e9e09c76..b22e40016 100644 --- a/examples/persistence/knowledge_qdrant.py +++ b/examples/persistence/knowledge_qdrant.py @@ -50,10 +50,10 @@ agent = Agent( name="KnowledgeAssistant", instructions="You are a helpful assistant with access to technical documentation.", - knowledge=[doc_path], knowledge={ + "sources": [doc_path], "vector_store": "qdrant", - "url": "http://localhost:6333" + "url": "http://localhost:6333", } ) diff --git a/examples/python/cli/git_integration_example.py b/examples/python/cli/git_integration_example.py index b94f34c03..304202ce5 100644 --- a/examples/python/cli/git_integration_example.py +++ b/examples/python/cli/git_integration_example.py @@ -8,7 +8,7 @@ from praisonai.cli.features import GitIntegrationHandler # Initialize -handler = GitIntegrationHandler(output="verbose") +handler = GitIntegrationHandler(verbose=True) git = handler.initialize(repo_path=".") # Check if it's a git repo diff --git a/examples/python/cli/repo_map_example.py b/examples/python/cli/repo_map_example.py index 71192492a..81c578cac 100644 --- a/examples/python/cli/repo_map_example.py +++ b/examples/python/cli/repo_map_example.py @@ -8,7 +8,7 @@ from praisonai.cli.features import RepoMapHandler # Initialize with current directory -handler = RepoMapHandler(output="verbose") +handler = RepoMapHandler(verbose=True) repo_map = handler.initialize(root=".") # Get the repository map diff --git a/examples/python/cli/sandbox_execution_example.py b/examples/python/cli/sandbox_execution_example.py index 37afd36e7..2b278aa9d 100644 --- a/examples/python/cli/sandbox_execution_example.py +++ b/examples/python/cli/sandbox_execution_example.py @@ -9,7 +9,7 @@ from praisonai.cli.features.sandbox_executor import SandboxMode # Initialize with basic sandbox -handler = SandboxExecutorHandler(output="verbose") +handler = SandboxExecutorHandler(verbose=True) sandbox = handler.initialize(mode="basic") print(f"Sandbox mode: {handler.get_mode()}") diff --git a/examples/python/concepts/chat-with-pdf.py b/examples/python/concepts/chat-with-pdf.py index 3e9e53e02..a1bb4158b 100644 --- a/examples/python/concepts/chat-with-pdf.py +++ b/examples/python/concepts/chat-with-pdf.py @@ -25,8 +25,7 @@ goal="Help users understand and extract information from PDF documents", backstory="You are an expert at reading, analyzing, and answering questions about PDF documents. You provide accurate, detailed answers based on the document content.", instructions="Read the provided PDF document and answer questions about its content. Be specific and cite relevant sections when possible.", - knowledge=["document.pdf"], # Replace with your PDF file path - knowledge=config, + knowledge={**config, "sources": ["document.pdf"]}, # Replace with your PDF path reflection=True, diff --git a/examples/python/concepts/knowledge-agents-task.py b/examples/python/concepts/knowledge-agents-task.py index 5ea98255d..4c27a77d3 100644 --- a/examples/python/concepts/knowledge-agents-task.py +++ b/examples/python/concepts/knowledge-agents-task.py @@ -1,6 +1,9 @@ +from pathlib import Path + from praisonaiagents import Agent, Task, AgentTeam import logging import os +import sys # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') @@ -17,14 +20,18 @@ } } +_sample_path = Path(__file__).with_name("sample_knowledge.txt") +if not _sample_path.exists(): + _sample_path.write_text("Mervin Praison is the creator of PraisonAI.\n", encoding="utf-8") + # Create an agent with knowledge capabilities knowledge_agent = Agent( name="KnowledgeAgent", role="Information Specialist", goal="Store and retrieve knowledge efficiently", backstory="Expert in managing and utilizing stored knowledge", - knowledge=["sample.pdf"], - knowledge=config) + knowledge={**config, "sources": [str(_sample_path)]}, +) # Define a task for the agent knowledge_task = Task( @@ -39,8 +46,16 @@ agents=[knowledge_agent], tasks=[knowledge_task], process="sequential", - user_id="user1" ) -# Start execution -result = agents.start() +if __name__ == "__main__": + if not os.environ.get("OPENAI_API_KEY"): + print("Set OPENAI_API_KEY to run this example.") + sys.exit(0) + if sys.platform == "win32": + try: + sys.stdout.reconfigure(encoding="utf-8") + except Exception: + pass + result = agents.start() + print(result) diff --git a/examples/python/concepts/knowledge-reranker-example.py b/examples/python/concepts/knowledge-reranker-example.py index 169030734..5eea32fd7 100644 --- a/examples/python/concepts/knowledge-reranker-example.py +++ b/examples/python/concepts/knowledge-reranker-example.py @@ -138,8 +138,7 @@ def main(): agent = Agent( name="AI Research Assistant", instructions="You are an AI research assistant. Use your knowledge base to answer questions about artificial intelligence topics.", - knowledge=sample_documents, # Will use default knowledge config - knowledge=rerank_config, # Use reranking config + knowledge={**rerank_config, "sources": sample_documents}, llm="gpt-4o-mini" ) diff --git a/examples/python/concepts/rag-agents.py b/examples/python/concepts/rag-agents.py index e606477e0..60d825ec9 100644 --- a/examples/python/concepts/rag-agents.py +++ b/examples/python/concepts/rag-agents.py @@ -32,8 +32,12 @@ agents = AgentTeam( agents=[rag_agent], tasks=[rag_task], - user_id="user1" ) -# Start Agents -agents.start() \ No newline at end of file +if __name__ == "__main__": + import os + import sys + if not os.environ.get("OPENAI_API_KEY"): + print("Set OPENAI_API_KEY to run this example.") + sys.exit(0) + agents.start() \ No newline at end of file diff --git a/examples/python/general/memory_example.py b/examples/python/general/memory_example.py index 724980026..15dfc671a 100644 --- a/examples/python/general/memory_example.py +++ b/examples/python/general/memory_example.py @@ -5,7 +5,7 @@ def main(): # Initialize memory config memory_config = { - "provider": "rag", + "backend": "sqlite", "use_embedding": True, "storage": { "type": "sqlite", @@ -105,7 +105,7 @@ def main(): agents=[researcher, retriever], tasks=[store_task, verify_task, query_task, query_both_task], # Use same verbose level as memory memory={ - "provider": "rag", + "backend": "sqlite", "embedder": { "provider": "openai", "config": { diff --git a/examples/python/memory/advanced-graph-memory-integration.py b/examples/python/memory/advanced-graph-memory-integration.py index 643b892b4..4b9eab376 100644 --- a/examples/python/memory/advanced-graph-memory-integration.py +++ b/examples/python/memory/advanced-graph-memory-integration.py @@ -60,8 +60,8 @@ agents_system = AgentTeam( agents=[knowledge_agent], tasks=[build_task, query_task], - memory=True, - memory=memory_config, output="verbose" + memory=memory_config, + output="verbose", ) print("Starting graph memory demonstration...") diff --git a/examples/python/memory/advanced-memory-search-optimization.py b/examples/python/memory/advanced-memory-search-optimization.py index 857fd896d..794e6e8e6 100644 --- a/examples/python/memory/advanced-memory-search-optimization.py +++ b/examples/python/memory/advanced-memory-search-optimization.py @@ -61,8 +61,8 @@ agents_system = AgentTeam( agents=[research_agent], tasks=[build_memory_task, search_task], - memory=True, - memory=memory_config, output="verbose" + memory=memory_config, + output="verbose", ) print("Starting memory search optimization demonstration...") diff --git a/examples/python/memory/gemini-embedding-example.py b/examples/python/memory/gemini-embedding-example.py index 43efed889..5e0e0c355 100644 --- a/examples/python/memory/gemini-embedding-example.py +++ b/examples/python/memory/gemini-embedding-example.py @@ -86,7 +86,7 @@ def main(): agents=[researcher, retriever], tasks=[store_task, retrieve_task], memory={ - "provider": "rag", + "backend": "sqlite", "embedder": { "provider": "gemini", "config": { diff --git a/examples/python/memory/graph-memory-agent.py b/examples/python/memory/graph-memory-agent.py index ee65d62c9..84c0e7ae3 100644 --- a/examples/python/memory/graph-memory-agent.py +++ b/examples/python/memory/graph-memory-agent.py @@ -152,8 +152,7 @@ def main(): agents_system = AgentTeam( agents=[researcher], tasks=[build_knowledge_task, query_knowledge_task, expand_knowledge_task], - memory=True, - memory=memory_config + memory=memory_config, ) print("\nšŸš€ Starting graph memory demonstration...") diff --git a/examples/python/memory_with_tracing_example.py b/examples/python/memory_with_tracing_example.py index 87151ad05..3243c4d04 100644 --- a/examples/python/memory_with_tracing_example.py +++ b/examples/python/memory_with_tracing_example.py @@ -30,7 +30,7 @@ def main(): try: # Create memory instance memory = Memory(config={ - "provider": "rag", + "backend": "sqlite", "use_embedding": False, "agent_name": "demo_agent", # Used in trace events }) diff --git a/examples/python/models/deepseek/deepseek-rag-agents-streamlit.py b/examples/python/models/deepseek/deepseek-rag-agents-streamlit.py index b73761afb..b36c92740 100644 --- a/examples/python/models/deepseek/deepseek-rag-agents-streamlit.py +++ b/examples/python/models/deepseek/deepseek-rag-agents-streamlit.py @@ -32,9 +32,8 @@ def init_agent(): return Agent( name="Knowledge Agent", instructions="You answer questions based on the provided knowledge.", - knowledge=["kag-research-paper.pdf"], - knowledge=config, - user_id="user1", + knowledge={**config, "sources": ["kag-research-paper.pdf"]}, + memory={"user_id": "user1"}, llm="deepseek-r1" ) diff --git a/examples/python/models/deepseek/deepseek-rag-agents.py b/examples/python/models/deepseek/deepseek-rag-agents.py index 88b43a307..44df9f831 100644 --- a/examples/python/models/deepseek/deepseek-rag-agents.py +++ b/examples/python/models/deepseek/deepseek-rag-agents.py @@ -30,9 +30,8 @@ agent = Agent( name="Knowledge Agent", instructions="You answer questions based on the provided knowledge.", - knowledge=["kag-research-paper.pdf"], # Indexing - knowledge=config, - user_id="user1", + knowledge={**config, "sources": ["kag-research-paper.pdf"]}, + memory={"user_id": "user1"}, llm="deepseek-r1" ) diff --git a/examples/python/mongodb/mongodb_comprehensive_example.py b/examples/python/mongodb/mongodb_comprehensive_example.py index d79ac3d3d..68b8b1ace 100644 --- a/examples/python/mongodb/mongodb_comprehensive_example.py +++ b/examples/python/mongodb/mongodb_comprehensive_example.py @@ -189,8 +189,8 @@ def main(): business_system = AgentTeam( agents=[data_manager, knowledge_curator, business_analyst, customer_service], tasks=business_tasks, - memory=True, - memory=mongodb_memory_config, output="verbose" + memory=mongodb_memory_config, + output="verbose", ) # Execute the comprehensive business pipeline diff --git a/examples/python/mongodb/mongodb_knowledge_example.py b/examples/python/mongodb/mongodb_knowledge_example.py index 40817e07f..7bb3c3dfc 100644 --- a/examples/python/mongodb/mongodb_knowledge_example.py +++ b/examples/python/mongodb/mongodb_knowledge_example.py @@ -55,8 +55,10 @@ def main(): retrieve information from a comprehensive MongoDB knowledge base. You excel at finding relevant information, synthesizing knowledge from multiple sources, and providing accurate, context-aware responses.""", - knowledge=mongodb_knowledge_config, - knowledge=[os.path.join(os.path.dirname(__file__), "llms.md")], + knowledge={ + **mongodb_knowledge_config, + "sources": [os.path.join(os.path.dirname(__file__), "llms.md")], + }, memory=True, llm="gpt-4o-mini" ) diff --git a/examples/python/mongodb/mongodb_memory_example.py b/examples/python/mongodb/mongodb_memory_example.py index c6f0be21c..86196962a 100644 --- a/examples/python/mongodb/mongodb_memory_example.py +++ b/examples/python/mongodb/mongodb_memory_example.py @@ -93,8 +93,8 @@ def main(): research_system = AgentTeam( agents=[research_agent], tasks=research_tasks, - memory=True, - memory=mongodb_memory_config, output="verbose" + memory=mongodb_memory_config, + output="verbose", ) # Execute the research pipeline diff --git a/examples/python/rag/agent_vs_auto_rag.py b/examples/python/rag/agent_vs_auto_rag.py index abef87c17..a3dd90222 100644 --- a/examples/python/rag/agent_vs_auto_rag.py +++ b/examples/python/rag/agent_vs_auto_rag.py @@ -50,7 +50,7 @@ name="TechSupport", instructions="You are a technical support assistant.", knowledge=[sample_doc], - user_id="comparison_user", + memory={"user_id": "comparison_user"}, llm="openai/gpt-4o-mini", output="minimal", ) diff --git a/examples/python/rag/auto_rag_agent_basic.py b/examples/python/rag/auto_rag_agent_basic.py index c57794fb7..2e48e7d24 100644 --- a/examples/python/rag/auto_rag_agent_basic.py +++ b/examples/python/rag/auto_rag_agent_basic.py @@ -20,8 +20,9 @@ exit(1) # Create a sample document for testing -sample_doc = "/tmp/sample_doc.txt" -with open(sample_doc, "w") as f: +from pathlib import Path +sample_doc = str(Path(__file__).with_name("sample_doc.txt")) +with open(sample_doc, "w", encoding="utf-8") as f: f.write(""" PraisonAI Framework Documentation @@ -44,7 +45,7 @@ name="DocBot", instructions="You are a helpful documentation assistant. Answer questions based on the provided context.", knowledge=[sample_doc], - user_id="example_user", # Required for RAG retrieval + memory={"user_id": "example_user"}, llm="openai/gpt-4o-mini", output="minimal", ) diff --git a/examples/python/rag/auto_rag_agent_policy.py b/examples/python/rag/auto_rag_agent_policy.py index b8a388672..ff7156fc0 100644 --- a/examples/python/rag/auto_rag_agent_policy.py +++ b/examples/python/rag/auto_rag_agent_policy.py @@ -38,7 +38,7 @@ name="PolicyBot", instructions="You are a customer service assistant.", knowledge=[sample_doc], - user_id="policy_user", + memory={"user_id": "policy_user"}, llm="openai/gpt-4o-mini", output="minimal", ) diff --git a/examples/python/rag/rag_basic.py b/examples/python/rag/rag_basic.py index fd6e98ec0..67b46df5c 100644 --- a/examples/python/rag/rag_basic.py +++ b/examples/python/rag/rag_basic.py @@ -44,7 +44,7 @@ name="MLExpert", instructions="You are a machine learning expert. Answer questions based on the provided context.", knowledge=[sample_doc], - user_id="rag_user", + memory={"user_id": "rag_user"}, llm="openai/gpt-4o-mini", output="minimal", ) diff --git a/examples/python/rag/rag_hybrid.py b/examples/python/rag/rag_hybrid.py index 9e58bca32..93da6735d 100644 --- a/examples/python/rag/rag_hybrid.py +++ b/examples/python/rag/rag_hybrid.py @@ -59,7 +59,7 @@ name="APIDocBot", instructions="You are an API documentation assistant.", knowledge=[sample_doc], - user_id="hybrid_user", + memory={"user_id": "hybrid_user"}, llm="openai/gpt-4o-mini", output="minimal", ) diff --git a/examples/python/rag/rag_with_citations.py b/examples/python/rag/rag_with_citations.py index d4022f0c2..26ead2c4c 100644 --- a/examples/python/rag/rag_with_citations.py +++ b/examples/python/rag/rag_with_citations.py @@ -44,7 +44,7 @@ name="ResearchBot", instructions="You are a research assistant. Always cite your sources.", knowledge=[doc1, doc2], - user_id="citation_user", + memory={"user_id": "citation_user"}, llm="openai/gpt-4o-mini", output="minimal", ) diff --git a/examples/python/sessions/comprehensive-session-management.py b/examples/python/sessions/comprehensive-session-management.py index 06b4ef253..df84023b5 100644 --- a/examples/python/sessions/comprehensive-session-management.py +++ b/examples/python/sessions/comprehensive-session-management.py @@ -172,7 +172,7 @@ # Create sessions for different users working on the same project reviewer_session = Session( session_id="peer_review_001", - user_id="user_reviewer_01", # Different user + user_id="user_reviewer_01", storage_path=session_dir ) diff --git a/examples/python/stateful/memory-quality-example.py b/examples/python/stateful/memory-quality-example.py index ca1edb3e3..c1fd1f9c9 100644 --- a/examples/python/stateful/memory-quality-example.py +++ b/examples/python/stateful/memory-quality-example.py @@ -14,13 +14,12 @@ def main(): # Initialize memory with quality-based configuration memory_config = { - "provider": "rag", - "use_embedding": True, - "rag_db_path": "quality_memory_db" + "backend": "sqlite", + "user_id": "quality_demo_user", } memory = Memory(config=memory_config, verbose=5) - print(f"šŸ“¦ Initialized memory system with provider: {memory_config['provider']}") + print(f"šŸ“¦ Initialized memory system with backend: {memory_config['backend']}") # Create agent with memory agent = Agent( @@ -28,7 +27,6 @@ def main(): role="Information Quality Specialist", instructions="Store and retrieve information with quality assessment", memory=memory, - user_id="quality_demo_user" ) print(f"šŸ¤– Created agent: {agent.name}") @@ -181,7 +179,7 @@ def main(): context = memory.build_context_for_task( task_descr="Explain AI alignment challenges", - user_id="quality_demo_user", + memory={"user_id": "quality_demo_user"}, max_items=3 ) diff --git a/examples/python/stateful/session-example.py b/examples/python/stateful/session-example.py index 7f3a1bd29..f7c636fa4 100644 --- a/examples/python/stateful/session-example.py +++ b/examples/python/stateful/session-example.py @@ -15,7 +15,7 @@ def main(): # Create a session with persistent storage session = Session( session_id="demo_chat_001", - user_id="demo_user" + memory={"user_id": "demo_user"}, ) print(f"šŸ“ Created session: {session}") diff --git a/examples/python/stateful/workflow-state-example.py b/examples/python/stateful/workflow-state-example.py index 170d0232b..dd8c2de70 100644 --- a/examples/python/stateful/workflow-state-example.py +++ b/examples/python/stateful/workflow-state-example.py @@ -88,9 +88,8 @@ def main(): workflow = AgentTeam( agents=[researcher, analyzer, writer], tasks=[research_task, analysis_task, report_task], - memory=True, + memory={"user_id": "research_project_001"}, process="workflow", - user_id="research_project_001", ) print(f"šŸ¤– Created workflow with {len(workflow.agents)} agents and {len(workflow.tasks)} tasks") diff --git a/examples/python/ui/ollama-rag-agents-streamlit.py b/examples/python/ui/ollama-rag-agents-streamlit.py index b73761afb..b36c92740 100644 --- a/examples/python/ui/ollama-rag-agents-streamlit.py +++ b/examples/python/ui/ollama-rag-agents-streamlit.py @@ -32,9 +32,8 @@ def init_agent(): return Agent( name="Knowledge Agent", instructions="You answer questions based on the provided knowledge.", - knowledge=["kag-research-paper.pdf"], - knowledge=config, - user_id="user1", + knowledge={**config, "sources": ["kag-research-paper.pdf"]}, + memory={"user_id": "user1"}, llm="deepseek-r1" ) diff --git a/examples/python/usecases/domain-context-solution.py b/examples/python/usecases/domain-context-solution.py index c2d3e4101..ef292553c 100644 --- a/examples/python/usecases/domain-context-solution.py +++ b/examples/python/usecases/domain-context-solution.py @@ -264,13 +264,12 @@ def is_in_scope(domain: str) -> bool: tasks=[tool_query_task, pentester_analysis_task, ciso_review_task], process="hierarchical", manager_llm="gpt-4o-mini", - memory=True, # Enable shared memory for domain context memory={ - "provider": "rag", + "backend": "sqlite", "config": { "collection_name": f"{domain.replace('.', '_')}_security_analysis" - } - } + }, + }, ) # Main Execution Workflow diff --git a/examples/rag/external_sources.py b/examples/rag/external_sources.py index cb6582cf5..611df3037 100644 --- a/examples/rag/external_sources.py +++ b/examples/rag/external_sources.py @@ -207,7 +207,7 @@ def api_augmented_rag(): instructions="""You are a financial assistant with access to market APIs. Provide accurate financial information and context. Always note that prices are subject to change.""", - user_id="api_demo" + memory={"user_id": "api_demo"}, ) queries = [ diff --git a/src/praisonai/examples/recipe_runtime_example.yaml b/src/praisonai/examples/recipe_runtime_example.yaml index 5bdabcfdd..6a0669dc0 100644 --- a/src/praisonai/examples/recipe_runtime_example.yaml +++ b/src/praisonai/examples/recipe_runtime_example.yaml @@ -85,7 +85,7 @@ examples: - name: Basic usage command: praisonai recipe run news-monitor - name: With custom topic - command: praisonai recipe run news-monitor -i '{"topic": "LLMs"}' + command: 'praisonai recipe run news-monitor -i ''{"topic": "LLMs"}''' - name: Background execution command: praisonai recipe run news-monitor --background - name: Submit as job From bfa9d0ca486e7648618265cc91b04f79aeef0329 Mon Sep 17 00:00:00 2001 From: "praisonai-triage-agent[bot]" <272766704+praisonai-triage-agent[bot]@users.noreply.github.com> Date: Thu, 4 Jun 2026 11:12:18 +0000 Subject: [PATCH 2/8] fix: correct TypeError in 3 example files by using proper parameter names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix MemoryConfig(memory=...) → user_id=... in agent_centric_api.py - Fix Session(memory=...) → user_id=... in session-example.py - Fix build_context_for_task(memory=...) → user_id=... in memory-quality-example.py Co-authored-by: Mervin Praison --- examples/agent_centric_api.py | 2 +- examples/python/stateful/memory-quality-example.py | 2 +- examples/python/stateful/session-example.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/agent_centric_api.py b/examples/agent_centric_api.py index fe78f4f77..dc128704d 100644 --- a/examples/agent_centric_api.py +++ b/examples/agent_centric_api.py @@ -52,7 +52,7 @@ def example_with_config(): instructions="You are a research assistant", memory=MemoryConfig( backend="file", - memory={"user_id": "researcher_001"}, + user_id="researcher_001", auto_memory=True, ), reflection=ReflectionConfig( diff --git a/examples/python/stateful/memory-quality-example.py b/examples/python/stateful/memory-quality-example.py index c1fd1f9c9..f7d25394f 100644 --- a/examples/python/stateful/memory-quality-example.py +++ b/examples/python/stateful/memory-quality-example.py @@ -179,7 +179,7 @@ def main(): context = memory.build_context_for_task( task_descr="Explain AI alignment challenges", - memory={"user_id": "quality_demo_user"}, + user_id="quality_demo_user", max_items=3 ) diff --git a/examples/python/stateful/session-example.py b/examples/python/stateful/session-example.py index f7c636fa4..20181d405 100644 --- a/examples/python/stateful/session-example.py +++ b/examples/python/stateful/session-example.py @@ -15,7 +15,7 @@ def main(): # Create a session with persistent storage session = Session( session_id="demo_chat_001", - memory={"user_id": "demo_user"}, + user_id="demo_user", ) print(f"šŸ“ Created session: {session}") From 3d3fdd045ee8c8033e9bd0673a9a88133476826c Mon Sep 17 00:00:00 2001 From: Dhivya-Bharathy Date: Fri, 5 Jun 2026 15:37:37 +0530 Subject: [PATCH 3/8] fix(examples): align AgentTeam memory and knowledge configs with v4.6.52 API --- examples/persistence/knowledge_qdrant.py | 6 ++++-- examples/python/general/memory_example.py | 4 ++-- examples/python/memory/advanced-graph-memory-integration.py | 2 +- .../python/memory/advanced-memory-search-optimization.py | 2 +- examples/python/memory/gemini-embedding-example.py | 4 ++-- examples/python/models/deepseek/deepseek-rag-agents.py | 6 +++++- examples/python/mongodb/mongodb_memory_example.py | 2 +- examples/python/token-metrics/01_basic_token_tracking.py | 2 +- examples/python/token-metrics/02_session_metrics.py | 4 ++-- examples/python/token-metrics/03_cost_estimation.py | 4 ++-- 10 files changed, 21 insertions(+), 15 deletions(-) diff --git a/examples/persistence/knowledge_qdrant.py b/examples/persistence/knowledge_qdrant.py index b22e40016..462d7e955 100644 --- a/examples/persistence/knowledge_qdrant.py +++ b/examples/persistence/knowledge_qdrant.py @@ -52,8 +52,10 @@ instructions="You are a helpful assistant with access to technical documentation.", knowledge={ "sources": [doc_path], - "vector_store": "qdrant", - "url": "http://localhost:6333", + "vector_store": { + "provider": "qdrant", + "url": "http://localhost:6333", + }, } ) diff --git a/examples/python/general/memory_example.py b/examples/python/general/memory_example.py index 15dfc671a..8a32cb671 100644 --- a/examples/python/general/memory_example.py +++ b/examples/python/general/memory_example.py @@ -105,13 +105,13 @@ def main(): agents=[researcher, retriever], tasks=[store_task, verify_task, query_task, query_both_task], # Use same verbose level as memory memory={ - "backend": "sqlite", "embedder": { "provider": "openai", "config": { "model": "text-embedding-3-small" } - } + }, + "config": {"provider": "sqlite"}, } ) diff --git a/examples/python/memory/advanced-graph-memory-integration.py b/examples/python/memory/advanced-graph-memory-integration.py index 4b9eab376..91dfe678a 100644 --- a/examples/python/memory/advanced-graph-memory-integration.py +++ b/examples/python/memory/advanced-graph-memory-integration.py @@ -12,8 +12,8 @@ # Configure simple graph memory memory_config = { - "provider": "mem0", "config": { + "provider": "mem0", "vector_store": { "provider": "chroma", "config": { diff --git a/examples/python/memory/advanced-memory-search-optimization.py b/examples/python/memory/advanced-memory-search-optimization.py index 794e6e8e6..21bdc46dd 100644 --- a/examples/python/memory/advanced-memory-search-optimization.py +++ b/examples/python/memory/advanced-memory-search-optimization.py @@ -12,8 +12,8 @@ # Configure optimized memory settings memory_config = { - "provider": "mem0", "config": { + "provider": "mem0", "vector_store": { "provider": "chroma", "config": { diff --git a/examples/python/memory/gemini-embedding-example.py b/examples/python/memory/gemini-embedding-example.py index 5e0e0c355..f13d37ae9 100644 --- a/examples/python/memory/gemini-embedding-example.py +++ b/examples/python/memory/gemini-embedding-example.py @@ -86,13 +86,13 @@ def main(): agents=[researcher, retriever], tasks=[store_task, retrieve_task], memory={ - "backend": "sqlite", "embedder": { "provider": "gemini", "config": { "model": "text-embedding-004", } - } + }, + "config": {"provider": "sqlite"}, } ) diff --git a/examples/python/models/deepseek/deepseek-rag-agents.py b/examples/python/models/deepseek/deepseek-rag-agents.py index 44df9f831..bbb2264bc 100644 --- a/examples/python/models/deepseek/deepseek-rag-agents.py +++ b/examples/python/models/deepseek/deepseek-rag-agents.py @@ -30,7 +30,11 @@ agent = Agent( name="Knowledge Agent", instructions="You answer questions based on the provided knowledge.", - knowledge={**config, "sources": ["kag-research-paper.pdf"]}, + knowledge={ + "sources": ["kag-research-paper.pdf"], + "vector_store": config["vector_store"], + "embedder": config["embedder"], + }, memory={"user_id": "user1"}, llm="deepseek-r1" ) diff --git a/examples/python/mongodb/mongodb_memory_example.py b/examples/python/mongodb/mongodb_memory_example.py index 86196962a..add6c0aed 100644 --- a/examples/python/mongodb/mongodb_memory_example.py +++ b/examples/python/mongodb/mongodb_memory_example.py @@ -28,8 +28,8 @@ def main(): # MongoDB memory configuration mongodb_memory_config = { - "provider": "mongodb", "config": { + "provider": "mongodb", "connection_string": "mongodb://localhost:27017/", # Replace with your MongoDB connection string "database": "praisonai_memory", "use_vector_search": True, # Enable Atlas Vector Search (requires MongoDB Atlas) diff --git a/examples/python/token-metrics/01_basic_token_tracking.py b/examples/python/token-metrics/01_basic_token_tracking.py index 7375a3f64..d6cf89770 100644 --- a/examples/python/token-metrics/01_basic_token_tracking.py +++ b/examples/python/token-metrics/01_basic_token_tracking.py @@ -14,7 +14,7 @@ def main(): goal="Find information about a topic", backstory="You are an expert researcher who finds comprehensive information.", llm="gpt-4o-mini", # Use a cost-effective model for examples - metrics=True # šŸŽÆ SIMPLIFIED: Just add this parameter! + output={"metrics": True} # Token metrics via consolidated output config ) # Create a simple task diff --git a/examples/python/token-metrics/02_session_metrics.py b/examples/python/token-metrics/02_session_metrics.py index f0b973c6f..c59730393 100644 --- a/examples/python/token-metrics/02_session_metrics.py +++ b/examples/python/token-metrics/02_session_metrics.py @@ -14,7 +14,7 @@ def main(): goal="Analyze data and provide insights", backstory="You are an experienced data analyst with expertise in market research.", llm="gpt-4o-mini", - metrics=True # šŸŽÆ Enable metrics tracking + output={"metrics": True} ) writer_agent = Agent( @@ -23,7 +23,7 @@ def main(): goal="Create well-structured content", backstory="You are a skilled technical writer who creates clear, engaging content.", llm="gpt-4o-mini", - metrics=True # šŸŽÆ Enable metrics tracking + output={"metrics": True} ) # Create multiple tasks diff --git a/examples/python/token-metrics/03_cost_estimation.py b/examples/python/token-metrics/03_cost_estimation.py index fbeac2b8e..de6e3f211 100644 --- a/examples/python/token-metrics/03_cost_estimation.py +++ b/examples/python/token-metrics/03_cost_estimation.py @@ -14,7 +14,7 @@ def main(): goal="Conduct comprehensive market research", backstory="You are a seasoned market researcher with 10+ years of experience.", llm="gpt-4o-mini", - metrics=True # šŸŽÆ Enable automatic metrics tracking + output={"metrics": True} ) strategy_agent = Agent( @@ -23,7 +23,7 @@ def main(): goal="Develop actionable business strategies", backstory="You are a strategic consultant who translates research into business plans.", llm="gpt-4o-mini", - metrics=True # šŸŽÆ Enable automatic metrics tracking + output={"metrics": True} ) # Create tasks that will generate substantial token usage From 4cc066cf51b9abc3126f663ff069f51a053e5402 Mon Sep 17 00:00:00 2001 From: Dhivya-Bharathy Date: Mon, 8 Jun 2026 10:54:02 +0530 Subject: [PATCH 4/8] fix(examples): phase-3 API alignment for consolidated params on v4.6.52 --- .../advanced_workflow_full_features.py | 4 ++-- .../persistence/cockroachdb_managed.py | 6 ++++-- .../managed-agents/persistence/neon_managed.py | 6 ++++-- .../persistence/supabase_direct_managed.py | 6 ++++-- .../managed-agents/persistence/turso_managed.py | 10 ++++++---- examples/middleware/configurable_model.py | 3 +-- examples/middleware/injected_state.py | 2 +- examples/policy/basic_policy.py | 2 +- examples/python/camera/camera-continuous.py | 2 +- examples/python/concepts/repetitive-agents.py | 2 +- .../custom_tools/example_latency_tracking.py | 1 - examples/python/data/cot-agents.py | 3 ++- examples/python/failover_example.py | 6 +++--- .../guardrails/production-guardrails-patterns.py | 5 +++-- examples/python/linear_agent_example.py | 2 +- .../googlegemini/any-llm-agents-advanced.py | 7 +++---- .../session/session_persistence_example.py | 6 +++--- .../rag_examples/agentic_rag/rag_agent.py | 3 ++- .../python/workflows/workflow_mixed_steps.py | 2 +- examples/retrieval/basic_retrieval.py | 16 +++++++++------- examples/skills/basic_skill_usage.py | 2 +- examples/yaml/workflows/example_usage.py | 2 +- 22 files changed, 54 insertions(+), 44 deletions(-) diff --git a/examples/consolidated_params/advanced_workflow_full_features.py b/examples/consolidated_params/advanced_workflow_full_features.py index faa98920e..7ac7b884c 100644 --- a/examples/consolidated_params/advanced_workflow_full_features.py +++ b/examples/consolidated_params/advanced_workflow_full_features.py @@ -2,7 +2,7 @@ from praisonaiagents import Agent from praisonaiagents import AgentFlow, Task from praisonaiagents.workflows.workflow_configs import ( - WorkflowOutputConfig, WorkflowPlanningConfig, WorkflowMemoryConfig, + WorkflowPlanningConfig, WorkflowMemoryConfig, ) # Full-featured workflow with all consolidated params @@ -32,7 +32,7 @@ ), ], # Workflow-level consolidated params - output=WorkflowOutputConfig(output="verbose", stream=True), + output="verbose", planning=WorkflowPlanningConfig(enabled=True, reasoning=True), memory=WorkflowMemoryConfig(backend="file"), # Agent-like params diff --git a/examples/managed-agents/persistence/cockroachdb_managed.py b/examples/managed-agents/persistence/cockroachdb_managed.py index ef8adb4b8..0e745f6b0 100644 --- a/examples/managed-agents/persistence/cockroachdb_managed.py +++ b/examples/managed-agents/persistence/cockroachdb_managed.py @@ -17,8 +17,10 @@ agent = Agent( name="CockroachDB Agent", instructions="You are a helpful assistant.", - db={"database_url": os.getenv("COCKROACHDB_URL")}, - session_id="crdb-demo-session", + memory={ + "session_id": "crdb-demo-session", + "db": {"database_url": os.getenv("COCKROACHDB_URL")}, + }, ) result = agent.start("What is distributed SQL? Explain in 2 sentences.") diff --git a/examples/managed-agents/persistence/neon_managed.py b/examples/managed-agents/persistence/neon_managed.py index 174a9a62b..7cb2ecacb 100644 --- a/examples/managed-agents/persistence/neon_managed.py +++ b/examples/managed-agents/persistence/neon_managed.py @@ -18,8 +18,10 @@ agent = Agent( name="Neon Agent", instructions="You are a helpful assistant.", - db={"database_url": os.getenv("NEON_DATABASE_URL")}, - session_id="neon-demo-session", + memory={ + "session_id": "neon-demo-session", + "db": {"database_url": os.getenv("NEON_DATABASE_URL")}, + }, ) # Option 2: Direct URL diff --git a/examples/managed-agents/persistence/supabase_direct_managed.py b/examples/managed-agents/persistence/supabase_direct_managed.py index 31338652a..e924af090 100644 --- a/examples/managed-agents/persistence/supabase_direct_managed.py +++ b/examples/managed-agents/persistence/supabase_direct_managed.py @@ -20,8 +20,10 @@ agent = Agent( name="Supabase Agent", instructions="You are a helpful assistant.", - db={"database_url": os.getenv("SUPABASE_DATABASE_URL")}, - session_id="supabase-demo-session", + memory={ + "session_id": "supabase-demo-session", + "db": {"database_url": os.getenv("SUPABASE_DATABASE_URL")}, + }, ) result = agent.start("What is Supabase? Explain in 2 sentences.") diff --git a/examples/managed-agents/persistence/turso_managed.py b/examples/managed-agents/persistence/turso_managed.py index 98297e329..fdb082936 100644 --- a/examples/managed-agents/persistence/turso_managed.py +++ b/examples/managed-agents/persistence/turso_managed.py @@ -18,11 +18,13 @@ agent = Agent( name="Turso Agent", instructions="You are a helpful assistant.", - db={ - "database_url": os.getenv("TURSO_DATABASE_URL"), - "auth_token": os.getenv("TURSO_AUTH_TOKEN"), + memory={ + "session_id": "turso-demo-session", + "db": { + "database_url": os.getenv("TURSO_DATABASE_URL"), + "auth_token": os.getenv("TURSO_AUTH_TOKEN"), + }, }, - session_id="turso-demo-session", ) result = agent.start("What is edge computing? Explain in 2 sentences.") diff --git a/examples/middleware/configurable_model.py b/examples/middleware/configurable_model.py index f0ce4f25c..9a60b37a2 100644 --- a/examples/middleware/configurable_model.py +++ b/examples/middleware/configurable_model.py @@ -10,8 +10,7 @@ agent = Agent( name="FlexBot", instructions="You are a helpful assistant.", - llm="gpt-4o-mini", - llm_config={"configurable": True} + llm={"model": "gpt-4o-mini", "configurable": True}, ) if __name__ == "__main__": diff --git a/examples/middleware/injected_state.py b/examples/middleware/injected_state.py index 85f70520a..8cefa5900 100644 --- a/examples/middleware/injected_state.py +++ b/examples/middleware/injected_state.py @@ -21,7 +21,7 @@ def show_context(query: str, state: Injected[dict]) -> str: name="ContextBot", instructions="You help show context information.", tools=[show_context], - session_id="my-session-123" + memory={"session_id": "my-session-123"}, ) if __name__ == "__main__": diff --git a/examples/policy/basic_policy.py b/examples/policy/basic_policy.py index b00a27dfb..f6e303f09 100644 --- a/examples/policy/basic_policy.py +++ b/examples/policy/basic_policy.py @@ -57,8 +57,8 @@ def main(): agent = Agent( name="SecureAgent", instructions="You are a file management assistant.", - policy=engine ) + agent.policy = engine print("\n--- Agent with Policy Enforcement Created ---") print(f"Agent: {agent.name}") diff --git a/examples/python/camera/camera-continuous.py b/examples/python/camera/camera-continuous.py index 5e93514bd..e75fc7ab6 100644 --- a/examples/python/camera/camera-continuous.py +++ b/examples/python/camera/camera-continuous.py @@ -75,7 +75,7 @@ def analyze_frame(self, image_path): agents=[self.vision_agent], tasks=[task], process="sequential", - verbose=0 # Reduced verbosity for continuous monitoring + output="silent", # Reduced verbosity for continuous monitoring ) return agents.start() diff --git a/examples/python/concepts/repetitive-agents.py b/examples/python/concepts/repetitive-agents.py index 7acea8673..90e2acbec 100644 --- a/examples/python/concepts/repetitive-agents.py +++ b/examples/python/concepts/repetitive-agents.py @@ -16,7 +16,7 @@ agents=[agent], tasks=[task], process="workflow", - max_iter=30 + execution={"max_iter": 30}, ) agents.start() \ No newline at end of file diff --git a/examples/python/custom_tools/example_latency_tracking.py b/examples/python/custom_tools/example_latency_tracking.py index 589c9b1c4..6695149e1 100644 --- a/examples/python/custom_tools/example_latency_tracking.py +++ b/examples/python/custom_tools/example_latency_tracking.py @@ -61,7 +61,6 @@ def example_with_wrappers(): role="Data Analyst", goal="Analyze data and provide insights", llm="gpt-4o-mini", - request_id="request_2" # Unique request ID ) # Operations are automatically tracked diff --git a/examples/python/data/cot-agents.py b/examples/python/data/cot-agents.py index 1d2628b49..b293428b9 100644 --- a/examples/python/data/cot-agents.py +++ b/examples/python/data/cot-agents.py @@ -132,7 +132,8 @@ def count_questions(file_path): agents=[qa_generator, total_questions_evaluator, cot_generator, upload_to_huggingface], tasks=[generate_task, evaluate_total_questions_task, generate_cot_task, upload_to_huggingface_task], process="workflow", - max_iter=30, output="minimal" + execution={"max_iter": 30}, + output="minimal", ) agents.start() \ No newline at end of file diff --git a/examples/python/failover_example.py b/examples/python/failover_example.py index 3fae101e8..18ceb31bc 100644 --- a/examples/python/failover_example.py +++ b/examples/python/failover_example.py @@ -18,7 +18,7 @@ provider="openai", api_key=os.environ.get("OPENAI_API_KEY", "sk-..."), priority=1, # Highest priority - rate_limit=100, + rate_limit_rpm=100, ) anthropic_profile = AuthProfile( @@ -26,7 +26,7 @@ provider="anthropic", api_key=os.environ.get("ANTHROPIC_API_KEY", "sk-ant-..."), priority=2, # Second priority - rate_limit=50, + rate_limit_rpm=50, ) groq_profile = AuthProfile( @@ -34,7 +34,7 @@ provider="groq", api_key=os.environ.get("GROQ_API_KEY", "gsk-..."), priority=3, # Third priority (fast but limited) - rate_limit=30, + rate_limit_rpm=30, ) # Configure failover behavior diff --git a/examples/python/guardrails/production-guardrails-patterns.py b/examples/python/guardrails/production-guardrails-patterns.py index 169926075..7d17eaec2 100644 --- a/examples/python/guardrails/production-guardrails-patterns.py +++ b/examples/python/guardrails/production-guardrails-patterns.py @@ -6,6 +6,7 @@ """ from praisonaiagents import Agent, Task, AgentTeam +from praisonaiagents.config.feature_configs import GuardrailConfig from praisonaiagents.tools import internet_search print("=== Production Guardrails Patterns Example ===\n") @@ -38,8 +39,8 @@ def content_guardrail(response, context): goal="Generate safe, compliant content for production use", backstory="Production-ready agent with built-in safety and compliance checks", tools=[internet_search], - guardrails=content_guardrail, - max_retries=3) + guardrails=GuardrailConfig(validator=content_guardrail, max_retries=3), +) # Create secure task with validation secure_task = Task( diff --git a/examples/python/linear_agent_example.py b/examples/python/linear_agent_example.py index d6ba1c50c..b37717255 100644 --- a/examples/python/linear_agent_example.py +++ b/examples/python/linear_agent_example.py @@ -40,7 +40,7 @@ "execute_command" ], memory=True, - web_search=True, + web=True, auto_approve_tools=True, ) diff --git a/examples/python/models/googlegemini/any-llm-agents-advanced.py b/examples/python/models/googlegemini/any-llm-agents-advanced.py index ea0ef3de4..608616076 100644 --- a/examples/python/models/googlegemini/any-llm-agents-advanced.py +++ b/examples/python/models/googlegemini/any-llm-agents-advanced.py @@ -31,10 +31,9 @@ agent = Agent( instructions="You are a helpful Assistant specialized in scientific explanations. " "Provide clear, accurate, and engaging responses.", - llm=llm_config, # Pass the detailed configuration - # Enable detailed output - markdown=True, # Format responses in markdown - reflection=True # Enable self-reflection + llm=llm_config, + output={"markdown": True}, + reflection=True, ) # Test the agent diff --git a/examples/python/session/session_persistence_example.py b/examples/python/session/session_persistence_example.py index 4b9b5fcfc..73d75788b 100644 --- a/examples/python/session/session_persistence_example.py +++ b/examples/python/session/session_persistence_example.py @@ -28,7 +28,7 @@ def example_basic_persistence(): agent = Agent( name="Assistant", instructions="You are a helpful assistant. Be very brief.", - session_id=session_id, + memory={"session_id": session_id}, output="minimal", ) @@ -59,7 +59,7 @@ def example_session_restoration(): agent1 = Agent( name="MemoryBot", instructions="You are a helpful assistant. Be very brief.", - session_id=session_id, + memory={"session_id": session_id}, output="minimal", ) @@ -72,7 +72,7 @@ def example_session_restoration(): agent2 = Agent( name="MemoryBot", instructions="You are a helpful assistant. Be very brief.", - session_id=session_id, + memory={"session_id": session_id}, output="minimal", ) diff --git a/examples/python/tools/exa-tool/rag_examples/agentic_rag/rag_agent.py b/examples/python/tools/exa-tool/rag_examples/agentic_rag/rag_agent.py index 8db9afc8a..af5e6d9c1 100644 --- a/examples/python/tools/exa-tool/rag_examples/agentic_rag/rag_agent.py +++ b/examples/python/tools/exa-tool/rag_examples/agentic_rag/rag_agent.py @@ -22,7 +22,8 @@ You can use the internet_search function to search the web when needed.""", llm="gpt-4o", - markdown=True) + output={"markdown": True}, +) if __name__ == "__main__": print("šŸ¤– Thai Recipe RAG Agent is ready!") diff --git a/examples/python/workflows/workflow_mixed_steps.py b/examples/python/workflows/workflow_mixed_steps.py index 20d477b0d..9c8f7321f 100644 --- a/examples/python/workflows/workflow_mixed_steps.py +++ b/examples/python/workflows/workflow_mixed_steps.py @@ -53,7 +53,7 @@ def format_output(ctx: WorkflowContext) -> StepResult: # Step 4: Function - formats output format_output ], - default_llm="gpt-4o-mini" # Used for action-based steps + llm="gpt-4o-mini", # Used for action-based steps ) if __name__ == "__main__": diff --git a/examples/retrieval/basic_retrieval.py b/examples/retrieval/basic_retrieval.py index 4f8367e4e..d8ec81f29 100644 --- a/examples/retrieval/basic_retrieval.py +++ b/examples/retrieval/basic_retrieval.py @@ -51,13 +51,15 @@ agent = Agent( name="Knowledge Agent", instructions="You are a helpful assistant that answers questions based on the provided knowledge. Be concise.", - knowledge=[".praison/test_docs/overview.txt"], - retrieval_config={ - "policy": "always", # Always retrieve for this demo - "top_k": 3, # Get top 3 chunks - "citations": True, # Include citations - "max_context_tokens": 2000, - } + knowledge={ + "sources": [".praison/test_docs/overview.txt"], + "config": { + "policy": "always", + "top_k": 3, + "citations": True, + "max_context_tokens": 2000, + }, + }, ) # Test 1: Basic chat with retrieval diff --git a/examples/skills/basic_skill_usage.py b/examples/skills/basic_skill_usage.py index f255ba966..eb07c855e 100644 --- a/examples/skills/basic_skill_usage.py +++ b/examples/skills/basic_skill_usage.py @@ -60,7 +60,7 @@ agent_with_discovery = Agent( name="Multi-Skill Agent", instructions="You are a versatile assistant with multiple skills.", - skills_dirs=["./"], # Scan current directory for skill subdirectories + skills=["./"], # Scan current directory for skill subdirectories ) if agent_with_discovery.skill_manager: diff --git a/examples/yaml/workflows/example_usage.py b/examples/yaml/workflows/example_usage.py index abce142f6..f8551e458 100644 --- a/examples/yaml/workflows/example_usage.py +++ b/examples/yaml/workflows/example_usage.py @@ -93,7 +93,7 @@ def example_3_execute_yaml_directly(): result = manager.execute_yaml( yaml_file, input_data="The future of AI", - output="verbose" + verbose=True, ) print(f"Status: {result['status']}") From b120e13550a1ad684c1fc0d7b5b522826cc8fd7e Mon Sep 17 00:00:00 2001 From: Dhivya-Bharathy Date: Mon, 8 Jun 2026 13:23:51 +0530 Subject: [PATCH 5/8] fix(examples): phase-4 API alignment for 40 validation failures on v4.6.52 --- examples/approval/agent_approval.py | 7 +- examples/consolidated_params/basic_web.py | 2 +- .../knowledge/context_required_example.py | 4 +- examples/observability/multi_agent_tracing.py | 16 +- examples/persistence/minimal_agent_db.py | 13 +- examples/persistence/postgres_runs_traces.py | 9 +- examples/persistence/redis_state.py | 9 +- examples/persistence/session_resume.py | 9 +- examples/persistence/simple_db_agent.py | 9 +- examples/persistence/sqlite_local.py | 9 +- .../autoagents-hierarchical-generation.py | 2 +- examples/python/api/simple-mcp-server.py | 5 +- examples/python/camera/camera-basic.py | 13 +- examples/python/camera/camera-multi-agent.py | 13 +- examples/python/cli/autonomy_modes_example.py | 2 +- examples/python/cli/cost_tracking_example.py | 2 +- examples/python/cli/slash_commands_example.py | 6 +- .../self-reflection-optimization-patterns.py | 10 +- examples/python/general/multimodal.py | 13 +- .../managed-agents/19_manage_environments.py | 53 +-- examples/python/mcp/mcp-resumability.py | 13 +- examples/python/mcp/mcp-session-management.py | 13 +- examples/python/mcp/streamable-http-mcp.py | 47 ++- examples/python/mcp/websocket-mcp.py | 51 ++- .../save_output/03_workflow_output_file.py | 29 +- .../advanced-state-management-patterns.py | 2 +- .../telemetry/production-telemetry-example.py | 321 +++--------------- .../tools/langchain/google-serper-search.py | 18 +- .../usecases/analysis/code-analysis-agents.py | 26 +- .../python/usecases/analysis/cv-analysis.py | 29 +- .../analysis/hackathon-judge-agent.py | 2 + examples/python/video/video_azure.py | 12 +- examples/python/workflows/task_callbacks.py | 7 +- .../python/workflows/workflow_conditional.py | 2 + .../python/workflows/workflow_robustness.py | 3 + examples/storage/storage_backends_example.py | 2 +- examples/terminal_bench/test_integration.py | 2 +- examples/web/00_agent_web_basic.py | 2 +- examples/web/01_agent_web_config.py | 14 +- .../praisonaiagents/agent/router_agent.py | 4 +- 40 files changed, 354 insertions(+), 451 deletions(-) diff --git a/examples/approval/agent_approval.py b/examples/approval/agent_approval.py index b5c4a59cc..a538239c4 100644 --- a/examples/approval/agent_approval.py +++ b/examples/approval/agent_approval.py @@ -12,10 +12,15 @@ from praisonaiagents.approval import AgentApproval from praisonaiagents.tools.shell_tools import execute_command -reviewer = AgentApproval( +reviewer_agent = Agent( + name="CommandReviewer", instructions="Only approve read-only commands like 'ls' or 'cat'. Deny destructive commands.", ) +reviewer = AgentApproval( + approver_agent=reviewer_agent, +) + agent = Agent( name="DevOps", instructions="You are a DevOps assistant. Use shell tools when asked.", diff --git a/examples/consolidated_params/basic_web.py b/examples/consolidated_params/basic_web.py index ea71be099..333a469a9 100644 --- a/examples/consolidated_params/basic_web.py +++ b/examples/consolidated_params/basic_web.py @@ -10,7 +10,7 @@ # Basic: Enable web search with preset agent = Agent( instructions="You are a research assistant with web access.", - web="duckduckgo", # Presets: duckduckgo, tavily, google, bing, serper + web="search_only", # Compatible across models without web_fetch ) if __name__ == "__main__": diff --git a/examples/knowledge/context_required_example.py b/examples/knowledge/context_required_example.py index 6329e035a..023b7b943 100644 --- a/examples/knowledge/context_required_example.py +++ b/examples/knowledge/context_required_example.py @@ -80,7 +80,7 @@ def main(): print(f"\nAnswer: {response}\n") # Verify the answer contains the unique code - if "ZEBRA-71" in response.upper(): + if "ZEBRA-71" in str(response or "").upper(): print("āœ… VERIFIED: Agent correctly retrieved the unique code from context!\n") else: print("āŒ WARNING: Agent did not find the code - check retrieval\n") @@ -104,7 +104,7 @@ def main(): response = agent.chat("What is the security incident code?") print(f"\nAnswer: {response}\n") - if "HAWK-88" in response.upper(): + if "HAWK-88" in str(response or "").upper(): print("āœ… VERIFIED: Agent correctly retrieved the security code!\n") else: print("āŒ WARNING: Agent did not find the code - check retrieval\n") diff --git a/examples/observability/multi_agent_tracing.py b/examples/observability/multi_agent_tracing.py index 00acdf43b..b74a52f21 100644 --- a/examples/observability/multi_agent_tracing.py +++ b/examples/observability/multi_agent_tracing.py @@ -19,6 +19,16 @@ # Initialize observability obs.init() + +def set_span_attr(span, key, value): + """Set span attribute safely across observability implementations.""" + if hasattr(span, "set_attribute"): + span.set_attribute(key, value) + return + attrs = getattr(span, "attributes", None) + if attrs is not None: + attrs[key] = value + # Create agents researcher = Agent( name="Researcher", @@ -37,13 +47,13 @@ # Research phase with obs.span("research-phase", kind=SpanKind.AGENT) as research_span: - research_span.attributes["agent"] = "Researcher" + set_span_attr(research_span, "agent", "Researcher") research_result = researcher.chat("Research the benefits of AI in healthcare") # Writing phase with obs.span("writing-phase", kind=SpanKind.AGENT) as write_span: - write_span.attributes["agent"] = "Writer" - write_span.attributes["input_length"] = len(str(research_result)) + set_span_attr(write_span, "agent", "Writer") + set_span_attr(write_span, "input_length", len(str(research_result))) final_content = writer.chat(f"Write a blog post based on: {research_result}") print("Final Content:") diff --git a/examples/persistence/minimal_agent_db.py b/examples/persistence/minimal_agent_db.py index 25f9da901..59cf408d5 100644 --- a/examples/persistence/minimal_agent_db.py +++ b/examples/persistence/minimal_agent_db.py @@ -13,7 +13,8 @@ - Session can be resumed later with same session_id """ -from praisonaiagents import Agent, db +from praisonaiagents import Agent +from praisonaiagents.db import db # Create database connection (PostgreSQL + Redis) my_db = db( @@ -25,10 +26,12 @@ agent = Agent( name="Assistant", instructions="You are a helpful assistant. Be concise.", - db=my_db, - # session_id is optional - defaults to per-hour ID (YYYYMMDDHH-hash) - # Set explicitly for session continuity across runs: - session_id="my-persistent-session" + memory={ + "db": my_db, + # session_id is optional - defaults to per-hour ID (YYYYMMDDHH-hash) + # Set explicitly for session continuity across runs: + "session_id": "my-persistent-session", + }, ) # Chat - messages are automatically persisted diff --git a/examples/persistence/postgres_runs_traces.py b/examples/persistence/postgres_runs_traces.py index 9b4cd0970..b497f7b14 100644 --- a/examples/persistence/postgres_runs_traces.py +++ b/examples/persistence/postgres_runs_traces.py @@ -12,7 +12,8 @@ - Export shows full session data """ -from praisonaiagents import Agent, db +from praisonaiagents import Agent +from praisonaiagents.db import db def get_weather(city: str) -> str: """Get weather for a city.""" @@ -29,8 +30,10 @@ def get_weather(city: str) -> str: name="WeatherBot", instructions="You help with weather. Use the get_weather tool when asked.", tools=[get_weather], - db=my_db, - session_id="weather-session-001" + memory={ + "db": my_db, + "session_id": "weather-session-001", + }, ) # First chat - triggers run tracking diff --git a/examples/persistence/redis_state.py b/examples/persistence/redis_state.py index bcedb7651..a449e1b69 100644 --- a/examples/persistence/redis_state.py +++ b/examples/persistence/redis_state.py @@ -13,7 +13,8 @@ Agent responds with state persisted to Redis """ -from praisonaiagents import Agent, db +from praisonaiagents import Agent +from praisonaiagents.db import db print("=== Redis State Store (Agent-First) ===") @@ -26,8 +27,10 @@ agent = Agent( name="Assistant", instructions="You are a helpful assistant.", - db=my_db, - session_id="redis-state-session" + memory={ + "db": my_db, + "session_id": "redis-state-session", + }, ) # Chat - state is automatically managed via Redis diff --git a/examples/persistence/session_resume.py b/examples/persistence/session_resume.py index 2ae185f34..fa973f3c8 100644 --- a/examples/persistence/session_resume.py +++ b/examples/persistence/session_resume.py @@ -11,7 +11,8 @@ - Second run: Resumes with history """ -from praisonaiagents import Agent, db +from praisonaiagents import Agent +from praisonaiagents.db import db # Create database my_db = db( @@ -25,8 +26,10 @@ agent = Agent( name="MemoryBot", instructions="You remember our conversation. Be helpful and concise.", - db=my_db, - session_id=SESSION_ID + memory={ + "db": my_db, + "session_id": SESSION_ID, + }, ) # Check if this is a new or resumed session diff --git a/examples/persistence/simple_db_agent.py b/examples/persistence/simple_db_agent.py index 0a42bcf47..f4c701f7c 100644 --- a/examples/persistence/simple_db_agent.py +++ b/examples/persistence/simple_db_agent.py @@ -26,7 +26,8 @@ Messages persisted: 2 """ -from praisonaiagents import Agent, db +from praisonaiagents import Agent +from praisonaiagents.db import db # Create database adapter (simplified import) db_instance = db( @@ -37,8 +38,10 @@ agent = Agent( name="Assistant", instructions="You are a helpful assistant. Keep responses brief.", - db=db_instance, - session_id="demo-session-001", # Same session_id = resume conversation + memory={ + "db": db_instance, + "session_id": "demo-session-001", # Same session_id = resume conversation + }, output="silent" ) diff --git a/examples/persistence/sqlite_local.py b/examples/persistence/sqlite_local.py index 44196a830..64df49cbb 100644 --- a/examples/persistence/sqlite_local.py +++ b/examples/persistence/sqlite_local.py @@ -11,7 +11,8 @@ - Data persisted to local SQLite file """ -from praisonaiagents import Agent, db +from praisonaiagents import Agent +from praisonaiagents.db import db import tempfile import os @@ -25,8 +26,10 @@ agent = Agent( name="LocalBot", instructions="You are a helpful assistant.", - db=my_db, - session_id="local-session" + memory={ + "db": my_db, + "session_id": "local-session", + }, ) # Chat diff --git a/examples/python/agents/autoagents-hierarchical-generation.py b/examples/python/agents/autoagents-hierarchical-generation.py index b73cc815f..57a9e8712 100644 --- a/examples/python/agents/autoagents-hierarchical-generation.py +++ b/examples/python/agents/autoagents-hierarchical-generation.py @@ -63,6 +63,6 @@ print("Starting hierarchical agent generation...") result = agents_system.start() -print(f"\nHierarchical Result: {result[:200]}...") +print(f"\nHierarchical Result: {str(result)[:200]}...") print("\nāœ… AutoAgents hierarchical generation complete!") print("Demonstrated coordinated hierarchical workflow between manager and specialist agents.") \ No newline at end of file diff --git a/examples/python/api/simple-mcp-server.py b/examples/python/api/simple-mcp-server.py index 74b20f5ec..9a92145c5 100644 --- a/examples/python/api/simple-mcp-server.py +++ b/examples/python/api/simple-mcp-server.py @@ -1,4 +1,5 @@ from praisonaiagents import Agent -agent = Agent(name="TweetAgent", instructions="Create a Tweet based on the topic provided") -agent.launch(port=8080, protocol="mcp") \ No newline at end of file +if __name__ == "__main__": + agent = Agent(name="TweetAgent", instructions="Create a Tweet based on the topic provided") + agent.launch(port=8080, protocol="mcp", path="/") \ No newline at end of file diff --git a/examples/python/camera/camera-basic.py b/examples/python/camera/camera-basic.py index d97f63076..9a3d509a2 100644 --- a/examples/python/camera/camera-basic.py +++ b/examples/python/camera/camera-basic.py @@ -90,9 +90,18 @@ def main(): if result: print("\nšŸ” Analysis Results:") - for task_id, task_result in result["task_results"].items(): + task_results = result.get("task_results") if isinstance(result, dict) else result + if isinstance(task_results, dict): + iterable = task_results.items() + elif isinstance(task_results, list): + iterable = enumerate(task_results) + else: + iterable = [("result", task_results)] + + for task_id, task_result in iterable: print(f"\nTask {task_id}:") - print(task_result.raw) + raw_value = getattr(task_result, "raw", None) + print(raw_value if raw_value is not None else str(task_result)) else: print("āŒ Failed to capture and analyze camera feed") diff --git a/examples/python/camera/camera-multi-agent.py b/examples/python/camera/camera-multi-agent.py index 0468d0333..15759c7d7 100644 --- a/examples/python/camera/camera-multi-agent.py +++ b/examples/python/camera/camera-multi-agent.py @@ -148,10 +148,19 @@ def main(): "scene_analysis": "šŸŒ SCENE ANALYSIS" } - for task_id, task_result in result["task_results"].items(): + task_results = result.get("task_results") if isinstance(result, dict) else result + if isinstance(task_results, dict): + iterable = task_results.items() + elif isinstance(task_results, list): + iterable = enumerate(task_results) + else: + iterable = [("result", task_results)] + + for task_id, task_result in iterable: print(f"\n{agent_names.get(task_id, f'Task {task_id}')}:") print("-" * 40) - print(task_result.raw) + raw_value = getattr(task_result, "raw", None) + print(raw_value if raw_value is not None else str(task_result)) print("\n" + "="*60) print("āœ… Multi-agent analysis complete!") diff --git a/examples/python/cli/autonomy_modes_example.py b/examples/python/cli/autonomy_modes_example.py index 66d3ee21c..24639065d 100644 --- a/examples/python/cli/autonomy_modes_example.py +++ b/examples/python/cli/autonomy_modes_example.py @@ -34,5 +34,5 @@ print("File edits now auto-approved, shell commands still require approval") # Get statistics -stats = handler.get_stats() +stats = manager.get_stats() print(f"\nStats: {stats}") diff --git a/examples/python/cli/cost_tracking_example.py b/examples/python/cli/cost_tracking_example.py index b0c95c5e3..9611905df 100644 --- a/examples/python/cli/cost_tracking_example.py +++ b/examples/python/cli/cost_tracking_example.py @@ -31,4 +31,4 @@ print(f"Avg cost/request: ${summary['avg_cost_per_request']:.4f}") # Display formatted (uses Rich if available) -handler.display_summary() +handler.print_summary() diff --git a/examples/python/cli/slash_commands_example.py b/examples/python/cli/slash_commands_example.py index 9802d15b6..bf284e787 100644 --- a/examples/python/cli/slash_commands_example.py +++ b/examples/python/cli/slash_commands_example.py @@ -41,9 +41,9 @@ def my_custom_handler(args, context): custom_cmd = SlashCommand( name="mycommand", description="My custom command", - handler=my_custom_handler, - kind=CommandKind.ACTION, - aliases=["mc"] + action=my_custom_handler, + kind=CommandKind.CUSTOM, + alt_names=["mc"] ) handler.register(custom_cmd) diff --git a/examples/python/concepts/self-reflection-optimization-patterns.py b/examples/python/concepts/self-reflection-optimization-patterns.py index 887faa184..8a903b8d6 100644 --- a/examples/python/concepts/self-reflection-optimization-patterns.py +++ b/examples/python/concepts/self-reflection-optimization-patterns.py @@ -34,8 +34,14 @@ # Run with self-reflection optimization print("Starting self-reflection optimization demonstration...") -result = reflection_agent.execute_task(reflection_task) +agents = AgentTeam( + agents=[reflection_agent], + tasks=[reflection_task], + process="sequential", + output="verbose", +) +result = agents.start() -print(f"\nSelf-Reflection Result: {result[:200]}...") +print(f"\nSelf-Reflection Result: {str(result)[:200]}...") print("\nāœ… Self-reflection optimization complete!") print("Agent demonstrated iterative improvement through built-in self-reflection capabilities.") \ No newline at end of file diff --git a/examples/python/general/multimodal.py b/examples/python/general/multimodal.py index 17a89d6cc..e2adfb784 100644 --- a/examples/python/general/multimodal.py +++ b/examples/python/general/multimodal.py @@ -53,6 +53,15 @@ result = agents.start() # Print results -for task_id, task_result in result["task_results"].items(): +task_results = result.get("task_results") if isinstance(result, dict) else result +if isinstance(task_results, dict): + iterable = task_results.items() +elif isinstance(task_results, list): + iterable = enumerate(task_results) +else: + iterable = [("result", task_results)] + +for task_id, task_result in iterable: print(f"\nTask {task_id} Result:") - print(task_result.raw) \ No newline at end of file + raw_value = getattr(task_result, "raw", None) + print(raw_value if raw_value is not None else str(task_result)) \ No newline at end of file diff --git a/examples/python/managed-agents/19_manage_environments.py b/examples/python/managed-agents/19_manage_environments.py index 1c06339e8..02d548464 100644 --- a/examples/python/managed-agents/19_manage_environments.py +++ b/examples/python/managed-agents/19_manage_environments.py @@ -14,30 +14,33 @@ # First call creates agent + environment + session agent.start("Say hello briefly") -# Access the underlying Anthropic client for environment management -client = managed._get_client() -env_id = managed.environment_id -print(f"Environment ID: {env_id}") - -# List all environments -environments = client.beta.environments.list() -print(f"\nTotal environments: {len(environments.data)}") -for env in environments.data[:5]: - print(f" {env.id} | {env.name} | {getattr(env, 'status', 'active')}") - -# Retrieve a specific environment -env = client.beta.environments.retrieve(env_id) -print(f"\nRetrieved: {env.id} | {env.name}") - -# Archive (read-only, existing sessions continue) -archived = client.beta.environments.archive(env_id) -print(f"Archived: {archived.id} | status: {getattr(archived, 'status', 'archived')}") - -# Delete (only if no sessions reference it — may fail if sessions exist) -try: - client.beta.environments.delete(env_id) - print(f"Deleted: {env_id}") -except Exception as e: - print(f"Delete skipped (expected if sessions exist): {e}") +if hasattr(managed, "_get_client"): + # Access the underlying Anthropic client for environment management + client = managed._get_client() + env_id = managed.environment_id + print(f"Environment ID: {env_id}") + + # List all environments + environments = client.beta.environments.list() + print(f"\nTotal environments: {len(environments.data)}") + for env in environments.data[:5]: + print(f" {env.id} | {env.name} | {getattr(env, 'status', 'active')}") + + # Retrieve a specific environment + env = client.beta.environments.retrieve(env_id) + print(f"\nRetrieved: {env.id} | {env.name}") + + # Archive (read-only, existing sessions continue) + archived = client.beta.environments.archive(env_id) + print(f"Archived: {archived.id} | status: {getattr(archived, 'status', 'archived')}") + + # Delete (only if no sessions reference it — may fail if sessions exist) + try: + client.beta.environments.delete(env_id) + print(f"Deleted: {env_id}") + except Exception as e: + print(f"Delete skipped (expected if sessions exist): {e}") +else: + print("Environment management demo skipped: backend does not expose _get_client().") print("\nEnvironment management complete.") diff --git a/examples/python/mcp/mcp-resumability.py b/examples/python/mcp/mcp-resumability.py index 2d8d968a3..d6d0eabbe 100644 --- a/examples/python/mcp/mcp-resumability.py +++ b/examples/python/mcp/mcp-resumability.py @@ -15,13 +15,6 @@ from praisonaiagents import Agent, MCP -# Agent with resumability support (automatic) -agent = Agent( - name="Resumable Assistant", - instructions="You are a helpful assistant with resumable connections.", - tools=MCP("https://api.example.com/mcp") -) - # Resumability is automatic - the MCP client: # 1. Tracks event IDs from SSE streams (id: field) # 2. Stores last event ID per stream @@ -29,6 +22,12 @@ # 4. Respects retry delay from server (retry: field) if __name__ == "__main__": + agent = Agent( + name="Resumable Assistant", + instructions="You are a helpful assistant with resumable connections.", + tools=MCP("https://api.example.com/mcp"), + ) + print("MCP Resumability Example") print("=" * 40) print() diff --git a/examples/python/mcp/mcp-session-management.py b/examples/python/mcp/mcp-session-management.py index 4a16604fa..3e4e094ad 100644 --- a/examples/python/mcp/mcp-session-management.py +++ b/examples/python/mcp/mcp-session-management.py @@ -15,13 +15,6 @@ from praisonaiagents import Agent, MCP -# Basic agent with automatic session management -agent = Agent( - name="Session Assistant", - instructions="You are a helpful assistant with session support.", - tools=MCP("https://api.example.com/mcp") -) - # Session management is automatic - the MCP client: # 1. Receives Mcp-Session-Id from server during initialization # 2. Includes session ID in all subsequent requests @@ -29,6 +22,12 @@ # 4. Can terminate session explicitly when done if __name__ == "__main__": + agent = Agent( + name="Session Assistant", + instructions="You are a helpful assistant with session support.", + tools=MCP("https://api.example.com/mcp"), + ) + print("MCP Session Management Example") print("=" * 40) print() diff --git a/examples/python/mcp/streamable-http-mcp.py b/examples/python/mcp/streamable-http-mcp.py index 0384e1c71..32cd31669 100644 --- a/examples/python/mcp/streamable-http-mcp.py +++ b/examples/python/mcp/streamable-http-mcp.py @@ -16,34 +16,31 @@ from praisonaiagents import Agent, MCP -# Basic Streamable HTTP connection -agent = Agent( - name="HTTP Stream Assistant", - instructions="You are a helpful assistant connected via Streamable HTTP.", - tools=MCP("https://api.example.com/mcp") -) - -# With authentication headers -agent_auth = Agent( - name="Authenticated Assistant", - instructions="You are a helpful assistant with authenticated connection.", - tools=MCP( - "https://api.example.com/mcp", - headers={"Authorization": "Bearer your-token"} +if __name__ == "__main__": + agent = Agent( + name="HTTP Stream Assistant", + instructions="You are a helpful assistant connected via Streamable HTTP.", + tools=MCP("https://api.example.com/mcp"), ) -) - -# With timeout and debug -agent_debug = Agent( - name="Debug Assistant", - tools=MCP( - "https://api.example.com/mcp", - timeout=120, - debug=True + + agent_auth = Agent( + name="Authenticated Assistant", + instructions="You are a helpful assistant with authenticated connection.", + tools=MCP( + "https://api.example.com/mcp", + headers={"Authorization": "Bearer your-token"}, + ), + ) + + agent_debug = Agent( + name="Debug Assistant", + tools=MCP( + "https://api.example.com/mcp", + timeout=120, + debug=True, + ), ) -) -if __name__ == "__main__": print("Streamable HTTP MCP Transport Example") print("=" * 40) print("This example requires a Streamable HTTP MCP server running.") diff --git a/examples/python/mcp/websocket-mcp.py b/examples/python/mcp/websocket-mcp.py index 4020dd119..f981466f6 100644 --- a/examples/python/mcp/websocket-mcp.py +++ b/examples/python/mcp/websocket-mcp.py @@ -16,36 +16,33 @@ from praisonaiagents import Agent, MCP -# Basic WebSocket connection -agent = Agent( - name="WebSocket Assistant", - instructions="You are a helpful assistant connected via WebSocket.", - tools=MCP("ws://localhost:8080/mcp") -) - -# Secure WebSocket with authentication -agent_secure = Agent( - name="Secure WebSocket Assistant", - instructions="You are a helpful assistant with secure WebSocket connection.", - tools=MCP( - "wss://api.example.com/mcp", - auth_token="Bearer your-secret-token", - timeout=60 +if __name__ == "__main__": + agent = Agent( + name="WebSocket Assistant", + instructions="You are a helpful assistant connected via WebSocket.", + tools=MCP("ws://localhost:8080/mcp"), ) -) - -# WebSocket with custom options -agent_custom = Agent( - name="Custom WebSocket Assistant", - tools=MCP( - "wss://api.example.com/mcp", - auth_token="your-token", - timeout=120, - debug=True + + agent_secure = Agent( + name="Secure WebSocket Assistant", + instructions="You are a helpful assistant with secure WebSocket connection.", + tools=MCP( + "wss://api.example.com/mcp", + auth_token="Bearer your-secret-token", + timeout=60, + ), + ) + + agent_custom = Agent( + name="Custom WebSocket Assistant", + tools=MCP( + "wss://api.example.com/mcp", + auth_token="your-token", + timeout=120, + debug=True, + ), ) -) -if __name__ == "__main__": # Note: Requires a running WebSocket MCP server # Example server: https://github.com/modelcontextprotocol/servers diff --git a/examples/python/save_output/03_workflow_output_file.py b/examples/python/save_output/03_workflow_output_file.py index fc697b8f6..38cd91cb5 100644 --- a/examples/python/save_output/03_workflow_output_file.py +++ b/examples/python/save_output/03_workflow_output_file.py @@ -4,7 +4,7 @@ Workflow step output is automatically saved with variable substitution. """ -from praisonaiagents import AgentFlow +from praisonaiagents import Agent, AgentFlow, Task # Define workflow with output_file workflow_config = { @@ -33,9 +33,30 @@ ] } -# Run workflow -workflow = AgentFlow(config=workflow_config) -result = workflow.run() +# Build agent and workflow from config dict +writer_cfg = workflow_config["agents"]["writer"] +writer = Agent( + name="writer", + role=writer_cfg["role"], + goal=writer_cfg["goal"], + llm=writer_cfg["llm"], +) + +step_cfg = workflow_config["steps"][0] +workflow = AgentFlow( + name=workflow_config["metadata"]["name"], + variables=workflow_config["variables"], + steps=[ + Task( + name="write_tutorial", + description=step_cfg["action"], + expected_output=step_cfg["expected_output"], + output_file=step_cfg["output_file"], + agent=writer, + ) + ], +) +result = workflow.start() print("āœ… Workflow completed!") print("Output saved to: generated/tutorial.md") diff --git a/examples/python/stateful/advanced-state-management-patterns.py b/examples/python/stateful/advanced-state-management-patterns.py index 41a944e0b..910b22424 100644 --- a/examples/python/stateful/advanced-state-management-patterns.py +++ b/examples/python/stateful/advanced-state-management-patterns.py @@ -72,6 +72,6 @@ print("Starting state management demonstration...") result = agents_system.start() -print(f"\nState Management Result: {result[:200]}...") +print(f"\nState Management Result: {str(result)[:200]}...") print("\nāœ… State management patterns complete!") print("Agent demonstrated persistent state tracking across multiple tasks.") \ No newline at end of file diff --git a/examples/python/telemetry/production-telemetry-example.py b/examples/python/telemetry/production-telemetry-example.py index d672ae5ba..2757fd6a1 100644 --- a/examples/python/telemetry/production-telemetry-example.py +++ b/examples/python/telemetry/production-telemetry-example.py @@ -1,284 +1,55 @@ """ Production Telemetry Example -This example demonstrates comprehensive telemetry and monitoring setup for -production AI agent systems, including metrics collection, performance tracking, -and observability. - -Features demonstrated: -- OpenTelemetry integration for distributed tracing -- Custom metrics collection and monitoring -- Performance tracking and analytics -- Error tracking and alerting -- Usage analytics and reporting +Demonstrates compatible telemetry setup with `enable_telemetry()` and +`TelemetryCollector` patterns. """ +from contextlib import nullcontext from praisonaiagents import Agent, Task, AgentTeam from praisonaiagents.tools import duckduckgo -from praisonaiagents.telemetry import enable_telemetry -import time -import random -from datetime import datetime - -# Initialize telemetry for production monitoring -print("="*80) -print("PRODUCTION TELEMETRY SETUP") -print("="*80) - -# Configure telemetry (in production, you'd use actual telemetry backends) -telemetry = enable_telemetry( - backend="opentelemetry", - config={ - "service_name": "praisonai_production_agents", - "service_version": "1.0.0", - "environment": "production", - "export_console": True, # For demo purposes - "export_file": True, # Export to file for analysis - "sample_rate": 1.0, # 100% sampling for demo - "attributes": { - "deployment": "cloud", - "region": "us-east-1", - "cluster": "main" - } - } -) - -# Create agents for production workflow with telemetry -customer_service_agent = Agent( - name="CustomerServiceAgent", - role="Customer Service Representative", - goal="Provide excellent customer service with fast response times", - backstory="You are a customer service representative focused on resolving customer issues quickly and effectively.", - tools=[duckduckgo], - instructions="Provide helpful, accurate customer service responses. Research solutions when needed." -) - -technical_support_agent = Agent( - name="TechnicalSupportAgent", - role="Technical Support Specialist", - goal="Resolve technical issues with detailed solutions", - backstory="You are a technical support specialist who provides detailed technical solutions and troubleshooting.", - instructions="Provide detailed technical solutions with step-by-step instructions." -) - -quality_assurance_agent = Agent( - name="QualityAssuranceAgent", - role="Quality Assurance Specialist", - goal="Ensure all customer interactions meet quality standards", - backstory="You review and assess the quality of customer service interactions to ensure high standards.", - instructions="Review customer service interactions and provide quality scores with detailed feedback." -) - -# Production workflow simulation with telemetry tracking -def simulate_customer_requests(): - """Simulate various customer requests for telemetry demonstration""" - - customer_requests = [ - { - "type": "billing_inquiry", - "complexity": "low", - "description": "Customer asking about their monthly bill charges", - "expected_duration": 30 - }, - { - "type": "technical_issue", - "complexity": "high", - "description": "Customer experiencing connectivity issues with the service", - "expected_duration": 120 - }, - { - "type": "account_setup", - "complexity": "medium", - "description": "New customer needs help setting up their account", - "expected_duration": 60 - }, - { - "type": "feature_question", - "complexity": "low", - "description": "Customer asking about product features and capabilities", - "expected_duration": 45 - } +from praisonaiagents.telemetry import enable_telemetry, TelemetryCollector + + +def main() -> None: + print("=" * 80) + print("PRODUCTION TELEMETRY SETUP") + print("=" * 80) + + # New API: no args + enable_telemetry() + collector = TelemetryCollector() + + customer_service_agent = Agent( + name="CustomerServiceAgent", + role="Customer Service Representative", + goal="Provide excellent customer service with fast response times", + backstory="Customer service expert focused on quick issue resolution.", + tools=[duckduckgo], + instructions="Provide accurate customer-service responses.", + ) + + requests = [ + "Customer asking about monthly bill charges", + "Customer experiencing connectivity issues", ] - - return customer_requests - -# Execute production workflow with comprehensive telemetry -print("Starting production workflow with telemetry tracking...") - -customer_requests = simulate_customer_requests() - -for i, request in enumerate(customer_requests): - print(f"\n{'='*60}") - print(f"PROCESSING CUSTOMER REQUEST {i+1}: {request['type'].upper()}") - print(f"Complexity: {request['complexity']} | Expected Duration: {request['expected_duration']}s") - print(f"{'='*60}") - - # Start telemetry trace for this customer interaction - with telemetry.trace_operation(f"customer_request_{request['type']}") as trace: - - # Add custom attributes to the trace - trace.set_attributes({ - "request.type": request['type'], - "request.complexity": request['complexity'], - "request.expected_duration": request['expected_duration'], - "customer.id": f"customer_{random.randint(1000, 9999)}", - "agent.assigned": "CustomerServiceAgent" - }) - - start_time = time.time() - - # Create customer service task with telemetry - customer_task = Task( - name=f"customer_request_{i+1}", - description=request['description'], - expected_output="Professional customer service response with solution", - agent=customer_service_agent - ) - - # Execute with telemetry tracking - try: - # Customer service response - with telemetry.trace_agent_execution("CustomerServiceAgent") as agent_trace: - agents = AgentTeam( - agents=[customer_service_agent], - tasks=[customer_task], - output="minimal" # Reduce verbosity for telemetry demo - ) - - cs_result = agents.start() - agent_trace.set_attributes({ - "agent.response_length": len(str(cs_result)), - "agent.tools_used": len(customer_service_agent.tools) if customer_service_agent.tools else 0 - }) - - # Technical support (if needed for high complexity) - if request['complexity'] == 'high': - with telemetry.trace_agent_execution("TechnicalSupportAgent") as tech_trace: - tech_task = Task( - name=f"technical_support_{i+1}", - description=f"Provide detailed technical support for: {request['description']}", - expected_output="Detailed technical solution with troubleshooting steps", - agent=technical_support_agent, - context=[customer_task] - ) - - tech_agents = AgentTeam( - agents=[technical_support_agent], - tasks=[tech_task], output="minimal" - ) - - tech_result = tech_agents.start() - tech_trace.set_attributes({ - "agent.response_length": len(str(tech_result)), - "agent.escalation": True - }) - - # Quality assurance check - with telemetry.trace_agent_execution("QualityAssuranceAgent") as qa_trace: - qa_task = Task( - name=f"quality_check_{i+1}", - description=f"Review the quality of customer service provided for: {request['description']}", - expected_output="Quality assessment score and feedback", - agent=quality_assurance_agent - ) - - qa_agents = AgentTeam( - agents=[quality_assurance_agent], - tasks=[qa_task], output="minimal" - ) - - qa_result = qa_agents.start() - - # Extract quality score (simulated) - quality_score = random.uniform(0.8, 1.0) # Simulated score - qa_trace.set_attributes({ - "qa.score": quality_score, - "qa.passed": quality_score >= 0.85 - }) - - # Calculate performance metrics - end_time = time.time() - duration = end_time - start_time - - # Record custom metrics - telemetry.record_metric("request_duration", duration, { - "request_type": request['type'], - "complexity": request['complexity'] - }) - - telemetry.record_metric("request_success", 1, { - "request_type": request['type'] - }) - - # Set final trace attributes - trace.set_attributes({ - "request.duration_seconds": duration, - "request.status": "completed", - "request.quality_score": quality_score, - "request.escalated": request['complexity'] == 'high' - }) - - print(f"āœ… Request completed successfully in {duration:.2f}s (Quality: {quality_score:.2f})") - - except Exception as e: - # Record error metrics - telemetry.record_metric("request_error", 1, { - "request_type": request['type'], - "error_type": type(e).__name__ - }) - - trace.set_attributes({ - "request.status": "error", - "request.error": str(e) - }) - - print(f"āŒ Request failed: {str(e)}") - - # Add some delay between requests - time.sleep(2) - -# Generate telemetry summary -print(f"\n{'='*80}") -print("TELEMETRY SUMMARY AND ANALYTICS") -print(f"{'='*80}") - -# Simulated telemetry analytics (in production, this would come from your telemetry backend) -print("šŸ“Š Performance Metrics:") -print("- Total Requests Processed: 4") -print("- Average Response Time: 3.2s") -print("- Success Rate: 100%") -print("- Quality Score Average: 0.91") -print("- High Complexity Requests: 25%") - -print("\nšŸ“ˆ Usage Analytics:") -print("- Most Common Request Type: technical_issue") -print("- Peak Performance Window: All requests within SLA") -print("- Agent Utilization: CustomerService (100%), TechnicalSupport (25%), QA (100%)") - -print("\nšŸ” Observability Features Demonstrated:") -print("- Distributed tracing across agent interactions") -print("- Custom metrics for business KPIs") -print("- Performance monitoring and SLA tracking") -print("- Error tracking and alerting") -print("- Quality assurance metrics") -print("- User journey tracking") -print("- Resource utilization monitoring") - -print("\nāš™ļø Production Monitoring Setup:") -print("- OpenTelemetry integration for standardized observability") -print("- Custom metrics for business-specific KPIs") -print("- Trace correlation across multi-agent workflows") -print("- Performance benchmarking against expected durations") -print("- Quality scoring and automated validation") -print("- Error categorization and alerting") -print(f"\n{'='*80}") -print("TELEMETRY DEMONSTRATION COMPLETED") -print(f"{'='*80}") -print("This example demonstrated comprehensive production telemetry including:") -print("- Request tracing and performance monitoring") -print("- Custom business metrics collection") -print("- Quality assurance tracking") -print("- Error handling and alerting") -print("- Multi-agent workflow observability") -print("- Production-ready monitoring patterns") \ No newline at end of file + for idx, description in enumerate(requests, start=1): + trace_ctx = getattr(collector, "trace", None) + trace_cm = trace_ctx(f"customer_request_{idx}") if callable(trace_ctx) else nullcontext() + with trace_cm: + task = Task( + name=f"customer_request_{idx}", + description=description, + expected_output="Professional customer service response with solution", + agent=customer_service_agent, + ) + agents = AgentTeam(agents=[customer_service_agent], tasks=[task], output="minimal") + result = agents.start() + print(f"āœ… Request {idx} completed, response length={len(str(result))}") + + print("\nTelemetry demonstration completed.") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/examples/python/tools/langchain/google-serper-search.py b/examples/python/tools/langchain/google-serper-search.py index 61fa224d1..65c018b81 100644 --- a/examples/python/tools/langchain/google-serper-search.py +++ b/examples/python/tools/langchain/google-serper-search.py @@ -5,11 +5,17 @@ load_dotenv() -os.environ['SERPER_API_KEY'] = os.getenv('SERPER_API_KEY') +serper_api_key = os.getenv("SERPER_API_KEY") +if serper_api_key is not None: + os.environ["SERPER_API_KEY"] = serper_api_key -search = GoogleSerperAPIWrapper() -data_agent = Agent(instructions="Suggest me top 5 most visited websites for Dosa Recipe", tools=[search]) -editor_agent = Agent(instructions="List out the websites with their url and a short description") -agents = AgentTeam(agents=[data_agent, editor_agent]) -agents.start() \ No newline at end of file +if __name__ == "__main__": + if not serper_api_key: + print("SERPER_API_KEY is not set. Skipping Google Serper example.") + else: + search = GoogleSerperAPIWrapper() + data_agent = Agent(instructions="Suggest me top 5 most visited websites for Dosa Recipe", tools=[search]) + editor_agent = Agent(instructions="List out the websites with their url and a short description") + agents = AgentTeam(agents=[data_agent, editor_agent]) + agents.start() \ No newline at end of file diff --git a/examples/python/usecases/analysis/code-analysis-agents.py b/examples/python/usecases/analysis/code-analysis-agents.py index 47bb6f271..85151e38c 100644 --- a/examples/python/usecases/analysis/code-analysis-agents.py +++ b/examples/python/usecases/analysis/code-analysis-agents.py @@ -2,6 +2,7 @@ from pydantic import BaseModel from typing import List, Dict from gitingest import ingest +import sys class CodeMetrics(BaseModel): category: str @@ -60,7 +61,10 @@ def analyze_code(code_source: str) -> CodeAnalysisReport: Analyze code from directory path or GitHub URL """ # Ingest code content - summary, tree, content = ingest(code_source) + try: + summary, tree, content = ingest(code_source) + except Exception as exc: + raise RuntimeError(f"Failed to ingest code source: {exc}") from exc # Concatenate context into structured format context_text = f""" @@ -86,10 +90,22 @@ def analyze_code(code_source: str) -> CodeAnalysisReport: tasks=[code_analysis_task] ) - return agents.start(context_text) + result = agents.start(context_text) + if result is None: + raise RuntimeError("No analysis result returned by AgentTeam.start()") + return result -if __name__ == "__main__": + +def main() -> None: # Example usage code_source = "https://github.com/openai/openai-python/tree/main/src/openai/cli/_api/chat" # GitHub URL or local directory - result = analyze_code(code_source) - print(result) \ No newline at end of file + try: + result = analyze_code(code_source) + except RuntimeError as exc: + print(f"Code analysis failed: {exc}") + sys.exit(1) + print(result) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/examples/python/usecases/analysis/cv-analysis.py b/examples/python/usecases/analysis/cv-analysis.py index 1a6914569..9ff55e332 100644 --- a/examples/python/usecases/analysis/cv-analysis.py +++ b/examples/python/usecases/analysis/cv-analysis.py @@ -77,25 +77,44 @@ class CVAnalysisReport(BaseModel): process="sequential", output="verbose" ) + +def _extract_pydantic_result(result_obj): + """Extract pydantic payload from AgentTeam.start() output shapes.""" + if hasattr(result_obj, "pydantic"): + return result_obj.pydantic + if isinstance(result_obj, dict): + task_results = result_obj.get("task_results") + if isinstance(task_results, dict): + values = list(task_results.values()) + if values and hasattr(values[-1], "pydantic"): + return values[-1].pydantic + if isinstance(task_results, list) and task_results and hasattr(task_results[-1], "pydantic"): + return task_results[-1].pydantic + return None + + # Start the analysis result = agents.start() +pydantic_result = _extract_pydantic_result(result) +if pydantic_result is None: + raise ValueError("Could not extract structured CVAnalysisReport from workflow result") # Access the structured results print("\nCV Analysis Results:") -print(f"\nOverall Score: {result.pydantic.overall_score}/100") +print(f"\nOverall Score: {pydantic_result.overall_score}/100") print("\nKey Strengths:") -for strength in result.pydantic.key_strengths: +for strength in pydantic_result.key_strengths: print(f"- {strength}") print("\nSkill Analysis:") print("\nTechnical Skills:") -for skill in result.pydantic.skill_analysis.technical_skills: +for skill in pydantic_result.skill_analysis.technical_skills: print(f"- {skill}") print("\nExperience Highlights:") -for achievement in result.pydantic.experience_analysis.key_achievements: +for achievement in pydantic_result.experience_analysis.key_achievements: print(f"- {achievement}") print("\nRecommendations:") -for recommendation in result.pydantic.recommendations: +for recommendation in pydantic_result.recommendations: print(f"- {recommendation}") diff --git a/examples/python/usecases/analysis/hackathon-judge-agent.py b/examples/python/usecases/analysis/hackathon-judge-agent.py index 49907d873..cb2f72867 100644 --- a/examples/python/usecases/analysis/hackathon-judge-agent.py +++ b/examples/python/usecases/analysis/hackathon-judge-agent.py @@ -100,6 +100,8 @@ def evaluate_project(video_path: str) -> ProjectEvaluation: evaluation_data = response print(f"Debug - Parsed evaluation_data: {evaluation_data}") + if not evaluation_data or not isinstance(evaluation_data, dict): + raise ValueError("No structured evaluation data returned by agent") # Create and return ProjectEvaluation instance return ProjectEvaluation( diff --git a/examples/python/video/video_azure.py b/examples/python/video/video_azure.py index 51e6c7da7..2d6815ea6 100644 --- a/examples/python/video/video_azure.py +++ b/examples/python/video/video_azure.py @@ -1,5 +1,11 @@ from praisonaiagents import VideoAgent +import os -agent = VideoAgent(llm="azure/sora-2") -video = agent.generate("Mountain landscape") -print(video.id) + +if __name__ == "__main__": + if not os.getenv("AZURE_API_BASE"): + print("AZURE_API_BASE is not configured. Skipping Azure video example.") + else: + agent = VideoAgent(llm="azure/sora-2") + video = agent.generate("Mountain landscape") + print(video.id) diff --git a/examples/python/workflows/task_callbacks.py b/examples/python/workflows/task_callbacks.py index d2864eab1..1fdb890b3 100644 --- a/examples/python/workflows/task_callbacks.py +++ b/examples/python/workflows/task_callbacks.py @@ -6,6 +6,7 @@ """ from praisonaiagents import Agent, Task, AgentTeam +from praisonaiagents.config.feature_configs import MultiAgentHooksConfig # Create an agent researcher = Agent( @@ -47,8 +48,10 @@ def on_complete(task, output): agents=[researcher], tasks=[task1, task2], process="workflow", - on_task_start=on_start, - on_task_complete=on_complete, + hooks=MultiAgentHooksConfig( + on_task_start=on_start, + on_task_complete=on_complete, + ), variables={"global_var": "shared_value"} # Global variables ) diff --git a/examples/python/workflows/workflow_conditional.py b/examples/python/workflows/workflow_conditional.py index 26eb88bc6..caf8aebd6 100644 --- a/examples/python/workflows/workflow_conditional.py +++ b/examples/python/workflows/workflow_conditional.py @@ -54,11 +54,13 @@ def needs_creative(ctx) -> bool: analyzer, # Always runs Task( name="tech_review", + description="Review technical aspects when technical keywords are detected.", agent=tech_reviewer, should_run=is_technical # Only runs for technical content ), Task( name="creative_enhance", + description="Enhance narrative quality when creative keywords are detected.", agent=creative_enhancer, should_run=needs_creative # Only runs for creative content ), diff --git a/examples/python/workflows/workflow_robustness.py b/examples/python/workflows/workflow_robustness.py index 0d62b0a33..68dfd9a7b 100644 --- a/examples/python/workflows/workflow_robustness.py +++ b/examples/python/workflows/workflow_robustness.py @@ -42,6 +42,7 @@ def main(): # Create tasks with robustness features research_task = Task( + name="research", description="Research the latest trends in AI agents for 2025", expected_output="A summary of key AI agent trends", agent=researcher, @@ -51,6 +52,7 @@ def main(): # Optional enrichment step - workflow continues even if this fails enrich_task = Task( + name="enrich", description="Enrich the research with real-world examples", expected_output="Research with added examples", agent=enricher, @@ -60,6 +62,7 @@ def main(): ) write_task = Task( + name="write", description="Write a brief summary based on the research", expected_output="A well-written summary paragraph", agent=writer, diff --git a/examples/storage/storage_backends_example.py b/examples/storage/storage_backends_example.py index f5a379f60..3cd9b1750 100644 --- a/examples/storage/storage_backends_example.py +++ b/examples/storage/storage_backends_example.py @@ -190,7 +190,7 @@ def example_run_history_with_backend(): # Use with RunHistory history = RunHistory(backend=backend) - runs = history.list() + runs = history.list_runs() print(f"RunHistory created with SQLite backend, {len(runs)} runs") print("Recipe runs will be stored in database instead of files") diff --git a/examples/terminal_bench/test_integration.py b/examples/terminal_bench/test_integration.py index 2c08d43cd..2e1fab732 100644 --- a/examples/terminal_bench/test_integration.py +++ b/examples/terminal_bench/test_integration.py @@ -257,7 +257,7 @@ def test_auto_approval_setup(self): # Check dependencies try: import praisonaiagents - print(f"āœ… PraisonAI version: {praisonaiagents.__version__}") + print(f"āœ… PraisonAI version: {getattr(praisonaiagents, '__version__', None)}") except ImportError: print("āŒ PraisonAI not installed: pip install praisonaiagents") sys.exit(1) diff --git a/examples/web/00_agent_web_basic.py b/examples/web/00_agent_web_basic.py index 25809235c..32d7393ff 100644 --- a/examples/web/00_agent_web_basic.py +++ b/examples/web/00_agent_web_basic.py @@ -12,7 +12,7 @@ # Enable web search and fetch agent = Agent( instructions="You are a research assistant with web access.", - web=True, + web="search_only", ) # Disable web (default) diff --git a/examples/web/01_agent_web_config.py b/examples/web/01_agent_web_config.py index 0fbddb076..b0fa8330d 100644 --- a/examples/web/01_agent_web_config.py +++ b/examples/web/01_agent_web_config.py @@ -4,7 +4,7 @@ Demonstrates using WebConfig for fine-grained control. """ import os -from praisonaiagents import Agent, WebConfig +from praisonaiagents import Agent # Ensure API key is set from environment assert os.getenv("OPENAI_API_KEY"), "OPENAI_API_KEY must be set" @@ -12,21 +12,13 @@ # Custom web configuration agent = Agent( instructions="You are a research assistant.", - web=WebConfig( - search=True, - fetch=True, - search_provider="duckduckgo", - max_results=5, - ), + web="search_only", ) # Search only (no fetch) agent_search_only = Agent( instructions="You are a research assistant.", - web=WebConfig( - search=True, - fetch=False, - ), + web="search_only", ) if __name__ == "__main__": diff --git a/src/praisonai-agents/praisonaiagents/agent/router_agent.py b/src/praisonai-agents/praisonaiagents/agent/router_agent.py index ff5252469..7a85a4797 100644 --- a/src/praisonai-agents/praisonaiagents/agent/router_agent.py +++ b/src/praisonai-agents/praisonaiagents/agent/router_agent.py @@ -353,9 +353,9 @@ def get_usage_report(self) -> Dict[str, Any]: return report - def _build_system_prompt(self) -> str: + def _build_system_prompt(self, tools=None, **kwargs) -> str: """Build system prompt (inherited from parent but can be customized).""" - base_prompt = super()._build_system_prompt() + base_prompt = super()._build_system_prompt(tools=tools, **kwargs) # Add multi-model context if needed if self.routing_strategy == "auto": From f1300ac201052cf5ff04c75a67ebff6d68e4fbf5 Mon Sep 17 00:00:00 2001 From: "praisonai-triage-agent[bot]" <272766704+praisonai-triage-agent[bot]@users.noreply.github.com> Date: Mon, 8 Jun 2026 08:05:59 +0000 Subject: [PATCH 6/8] fix: resolve critical RouterAgent **kwargs bug and add missing if __name__ guards - Fixed TypeError in RouterAgent._build_system_prompt() by removing **kwargs from super() call - Added if __name__ == '__main__' guards to 6 example files to prevent auto-execution on import - Addresses Gemini Code Assist review feedback Co-authored-by: Mervin Praison --- .../autoagents-hierarchical-generation.py | 11 +++---- examples/python/concepts/repetitive-agents.py | 3 +- .../self-reflection-optimization-patterns.py | 23 ++++++++------- examples/python/data/cot-agents.py | 3 +- examples/python/general/multimodal.py | 29 ++++++++++--------- .../advanced-state-management-patterns.py | 11 +++---- .../praisonaiagents/agent/router_agent.py | 2 +- 7 files changed, 44 insertions(+), 38 deletions(-) diff --git a/examples/python/agents/autoagents-hierarchical-generation.py b/examples/python/agents/autoagents-hierarchical-generation.py index 57a9e8712..79e943962 100644 --- a/examples/python/agents/autoagents-hierarchical-generation.py +++ b/examples/python/agents/autoagents-hierarchical-generation.py @@ -60,9 +60,10 @@ process="sequential", output="verbose" ) -print("Starting hierarchical agent generation...") -result = agents_system.start() +if __name__ == "__main__": + print("Starting hierarchical agent generation...") + result = agents_system.start() -print(f"\nHierarchical Result: {str(result)[:200]}...") -print("\nāœ… AutoAgents hierarchical generation complete!") -print("Demonstrated coordinated hierarchical workflow between manager and specialist agents.") \ No newline at end of file + print(f"\nHierarchical Result: {str(result)[:200]}...") + print("\nāœ… AutoAgents hierarchical generation complete!") + print("Demonstrated coordinated hierarchical workflow between manager and specialist agents.") \ No newline at end of file diff --git a/examples/python/concepts/repetitive-agents.py b/examples/python/concepts/repetitive-agents.py index 90e2acbec..b9648a506 100644 --- a/examples/python/concepts/repetitive-agents.py +++ b/examples/python/concepts/repetitive-agents.py @@ -19,4 +19,5 @@ execution={"max_iter": 30}, ) -agents.start() \ No newline at end of file +if __name__ == "__main__": + agents.start() \ No newline at end of file diff --git a/examples/python/concepts/self-reflection-optimization-patterns.py b/examples/python/concepts/self-reflection-optimization-patterns.py index 8a903b8d6..3e1543cc9 100644 --- a/examples/python/concepts/self-reflection-optimization-patterns.py +++ b/examples/python/concepts/self-reflection-optimization-patterns.py @@ -33,15 +33,16 @@ ) # Run with self-reflection optimization -print("Starting self-reflection optimization demonstration...") -agents = AgentTeam( - agents=[reflection_agent], - tasks=[reflection_task], - process="sequential", - output="verbose", -) -result = agents.start() +if __name__ == "__main__": + print("Starting self-reflection optimization demonstration...") + agents = AgentTeam( + agents=[reflection_agent], + tasks=[reflection_task], + process="sequential", + output="verbose", + ) + result = agents.start() -print(f"\nSelf-Reflection Result: {str(result)[:200]}...") -print("\nāœ… Self-reflection optimization complete!") -print("Agent demonstrated iterative improvement through built-in self-reflection capabilities.") \ No newline at end of file + print(f"\nSelf-Reflection Result: {str(result)[:200]}...") + print("\nāœ… Self-reflection optimization complete!") + print("Agent demonstrated iterative improvement through built-in self-reflection capabilities.") \ No newline at end of file diff --git a/examples/python/data/cot-agents.py b/examples/python/data/cot-agents.py index b293428b9..13aea349d 100644 --- a/examples/python/data/cot-agents.py +++ b/examples/python/data/cot-agents.py @@ -136,4 +136,5 @@ def count_questions(file_path): output="minimal", ) -agents.start() \ No newline at end of file +if __name__ == "__main__": + agents.start() \ No newline at end of file diff --git a/examples/python/general/multimodal.py b/examples/python/general/multimodal.py index e2adfb784..73a614f08 100644 --- a/examples/python/general/multimodal.py +++ b/examples/python/general/multimodal.py @@ -49,19 +49,20 @@ process="sequential" ) -# Run all tasks -result = agents.start() +if __name__ == "__main__": + # Run all tasks + result = agents.start() -# Print results -task_results = result.get("task_results") if isinstance(result, dict) else result -if isinstance(task_results, dict): - iterable = task_results.items() -elif isinstance(task_results, list): - iterable = enumerate(task_results) -else: - iterable = [("result", task_results)] + # Print results + task_results = result.get("task_results") if isinstance(result, dict) else result + if isinstance(task_results, dict): + iterable = task_results.items() + elif isinstance(task_results, list): + iterable = enumerate(task_results) + else: + iterable = [("result", task_results)] -for task_id, task_result in iterable: - print(f"\nTask {task_id} Result:") - raw_value = getattr(task_result, "raw", None) - print(raw_value if raw_value is not None else str(task_result)) \ No newline at end of file + for task_id, task_result in iterable: + print(f"\nTask {task_id} Result:") + raw_value = getattr(task_result, "raw", None) + print(raw_value if raw_value is not None else str(task_result)) \ No newline at end of file diff --git a/examples/python/stateful/advanced-state-management-patterns.py b/examples/python/stateful/advanced-state-management-patterns.py index 910b22424..f469bd688 100644 --- a/examples/python/stateful/advanced-state-management-patterns.py +++ b/examples/python/stateful/advanced-state-management-patterns.py @@ -69,9 +69,10 @@ memory=True, output="verbose" ) -print("Starting state management demonstration...") -result = agents_system.start() +if __name__ == "__main__": + print("Starting state management demonstration...") + result = agents_system.start() -print(f"\nState Management Result: {str(result)[:200]}...") -print("\nāœ… State management patterns complete!") -print("Agent demonstrated persistent state tracking across multiple tasks.") \ No newline at end of file + print(f"\nState Management Result: {str(result)[:200]}...") + print("\nāœ… State management patterns complete!") + print("Agent demonstrated persistent state tracking across multiple tasks.") \ No newline at end of file diff --git a/src/praisonai-agents/praisonaiagents/agent/router_agent.py b/src/praisonai-agents/praisonaiagents/agent/router_agent.py index 7a85a4797..d77b28d06 100644 --- a/src/praisonai-agents/praisonaiagents/agent/router_agent.py +++ b/src/praisonai-agents/praisonaiagents/agent/router_agent.py @@ -355,7 +355,7 @@ def get_usage_report(self) -> Dict[str, Any]: def _build_system_prompt(self, tools=None, **kwargs) -> str: """Build system prompt (inherited from parent but can be customized).""" - base_prompt = super()._build_system_prompt(tools=tools, **kwargs) + base_prompt = super()._build_system_prompt(tools=tools) # Add multi-model context if needed if self.routing_strategy == "auto": From 763f7c8dceb63f9709a397c47e7fe23cc86124f4 Mon Sep 17 00:00:00 2001 From: "praisonai-triage-agent[bot]" <272766704+praisonai-triage-agent[bot]@users.noreply.github.com> Date: Thu, 11 Jun 2026 09:37:42 +0000 Subject: [PATCH 7/8] fix: resolve missing AgentTeam import and RouterAgent kwargs forwarding - Fix missing AgentTeam import in self-reflection-optimization-patterns.py - Forward kwargs properly in RouterAgent._build_system_prompt to super() - Addresses critical issues identified by Gemini code reviewer Co-authored-by: Mervin Praison --- .../python/concepts/self-reflection-optimization-patterns.py | 3 ++- src/praisonai-agents/praisonaiagents/agent/router_agent.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/python/concepts/self-reflection-optimization-patterns.py b/examples/python/concepts/self-reflection-optimization-patterns.py index 3e1543cc9..401d28d1a 100644 --- a/examples/python/concepts/self-reflection-optimization-patterns.py +++ b/examples/python/concepts/self-reflection-optimization-patterns.py @@ -5,7 +5,8 @@ built-in reflection features for iterative improvement and quality optimization. """ -from praisonaiagents import Agent, Task, AgentTeam +from praisonaiagents import Agent, Task +from praisonaiagents.agents import AgentTeam from praisonaiagents.tools import internet_search print("=== Self-Reflection Optimization Patterns Example ===\n") diff --git a/src/praisonai-agents/praisonaiagents/agent/router_agent.py b/src/praisonai-agents/praisonaiagents/agent/router_agent.py index d77b28d06..7a85a4797 100644 --- a/src/praisonai-agents/praisonaiagents/agent/router_agent.py +++ b/src/praisonai-agents/praisonaiagents/agent/router_agent.py @@ -355,7 +355,7 @@ def get_usage_report(self) -> Dict[str, Any]: def _build_system_prompt(self, tools=None, **kwargs) -> str: """Build system prompt (inherited from parent but can be customized).""" - base_prompt = super()._build_system_prompt(tools=tools) + base_prompt = super()._build_system_prompt(tools=tools, **kwargs) # Add multi-model context if needed if self.routing_strategy == "auto": From 9c334bcaae83e88f82cba699f78b6f9bb08b7a6c Mon Sep 17 00:00:00 2001 From: Dhivya-Bharathy Date: Thu, 11 Jun 2026 15:29:16 +0530 Subject: [PATCH 8/8] fix(examples): remove merge-conflict residue for PR #1893 --- examples/persistence/knowledge_qdrant.py | 5 ++++- examples/python/general/memory_example.py | 1 - examples/python/memory/gemini-embedding-example.py | 1 - examples/python/models/deepseek/deepseek-rag-agents.py | 6 +++++- examples/python/stateful/session-example.py | 2 +- 5 files changed, 10 insertions(+), 5 deletions(-) diff --git a/examples/persistence/knowledge_qdrant.py b/examples/persistence/knowledge_qdrant.py index a6b55011c..462d7e955 100644 --- a/examples/persistence/knowledge_qdrant.py +++ b/examples/persistence/knowledge_qdrant.py @@ -52,7 +52,10 @@ instructions="You are a helpful assistant with access to technical documentation.", knowledge={ "sources": [doc_path], -main + "vector_store": { + "provider": "qdrant", + "url": "http://localhost:6333", + }, } ) diff --git a/examples/python/general/memory_example.py b/examples/python/general/memory_example.py index 334589039..8a32cb671 100644 --- a/examples/python/general/memory_example.py +++ b/examples/python/general/memory_example.py @@ -105,7 +105,6 @@ def main(): agents=[researcher, retriever], tasks=[store_task, verify_task, query_task, query_both_task], # Use same verbose level as memory memory={ -main "embedder": { "provider": "openai", "config": { diff --git a/examples/python/memory/gemini-embedding-example.py b/examples/python/memory/gemini-embedding-example.py index 7906cf39a..f13d37ae9 100644 --- a/examples/python/memory/gemini-embedding-example.py +++ b/examples/python/memory/gemini-embedding-example.py @@ -86,7 +86,6 @@ def main(): agents=[researcher, retriever], tasks=[store_task, retrieve_task], memory={ -main "embedder": { "provider": "gemini", "config": { diff --git a/examples/python/models/deepseek/deepseek-rag-agents.py b/examples/python/models/deepseek/deepseek-rag-agents.py index 7f92e8148..bbb2264bc 100644 --- a/examples/python/models/deepseek/deepseek-rag-agents.py +++ b/examples/python/models/deepseek/deepseek-rag-agents.py @@ -30,7 +30,11 @@ agent = Agent( name="Knowledge Agent", instructions="You answer questions based on the provided knowledge.", -main + knowledge={ + "sources": ["kag-research-paper.pdf"], + "vector_store": config["vector_store"], + "embedder": config["embedder"], + }, memory={"user_id": "user1"}, llm="deepseek-r1" ) diff --git a/examples/python/stateful/session-example.py b/examples/python/stateful/session-example.py index cb5d526cd..20181d405 100644 --- a/examples/python/stateful/session-example.py +++ b/examples/python/stateful/session-example.py @@ -15,7 +15,7 @@ def main(): # Create a session with persistent storage session = Session( session_id="demo_chat_001", -main + user_id="demo_user", ) print(f"šŸ“ Created session: {session}")