sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/history/continuous_execution.py
""" Continuous Execution ==================== Demonstrates single-step conversational execution with workflow history available to the step agent. """ from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.workflow.step import Step from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- tutor_agent = Agent( name="AI Tutor", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are an expert tutor who provides personalized educational support.", "You have access to our full conversation history.", "Build on previous discussions - do not repeat questions or information.", "Reference what the student has told you earlier in our conversation.", "Adapt your teaching style based on what you have learned about the student.", "Be encouraging, patient, and supportive.", "When asked about conversation history, provide a helpful summary.", "Focus on helping the student understand concepts and improve their skills.", ], ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- tutor_workflow = Workflow( name="Simple AI Tutor", description="Single-step conversational tutoring with history awareness", db=SqliteDb(db_file="tmp/simple_tutor_workflow.db"), steps=[Step(name="AI Tutoring", agent=tutor_agent)], add_workflow_history_to_steps=True, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- def demo_simple_tutoring_cli() -> None: print("Simple AI Tutor Demo - Type 'exit' to quit") print("Try asking about:") print("- 'I'm struggling with calculus derivatives'") print("- 'Can you help me with algebra?'") print("-" * 60) tutor_workflow.cli_app( session_id="simple_tutor_demo", user="Student", emoji="", stream=True, show_step_details=True, ) if __name__ == "__main__": demo_simple_tutoring_cli()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/history/continuous_execution.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/history/history_in_function.py
""" History In Function =================== Demonstrates reading workflow history inside a custom function step for strategic content planning. """ import json from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.workflow.step import Step from agno.workflow.types import StepInput, StepOutput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Define Analysis Function # --------------------------------------------------------------------------- def analyze_content_strategy(step_input: StepInput) -> StepOutput: current_topic = step_input.input or "" research_data = step_input.get_last_step_content() or "" history_data = step_input.get_workflow_history(num_runs=5) def extract_keywords(text: str) -> set: stop_words = { "create", "content", "about", "write", "the", "a", "an", "how", "is", "of", "this", "that", "in", "on", "for", "to", } words = set(text.lower().split()) - stop_words keyword_map = { "ai": ["ai", "artificial", "intelligence"], "ml": ["machine", "learning", "ml"], "healthcare": ["medical", "health", "healthcare", "medicine"], "blockchain": ["crypto", "cryptocurrency", "blockchain"], } expanded_keywords = set(words) for word in list(words): for synonyms in keyword_map.values(): if word in synonyms: expanded_keywords.update([word]) return expanded_keywords current_keywords = extract_keywords(current_topic) max_possible_overlap = len(current_keywords) topic_overlaps = [] covered_topics = [] for input_request, _content_output in history_data: if input_request: covered_topics.append(input_request.lower()) previous_keywords = extract_keywords(input_request) overlap = len(current_keywords.intersection(previous_keywords)) if overlap > 0: topic_overlaps.append(overlap) topic_overlap = max(topic_overlaps) if topic_overlaps else 0 overlap_percentage = (topic_overlap / max(max_possible_overlap, 1)) * 100 diversity_score = len(set(covered_topics)) / max(len(covered_topics), 1) recommendations = [] if overlap_percentage > 60: recommendations.append( "HIGH OVERLAP detected - consider a fresh angle or advanced perspective" ) elif overlap_percentage > 30: recommendations.append( "MODERATE OVERLAP detected - differentiate your approach" ) if diversity_score < 0.6: recommendations.append( "Low content diversity - explore different aspects of the topic" ) if len(history_data) > 0: recommendations.append( f"Building on {len(history_data)} previous content pieces - ensure progression" ) strategy_analysis = { "content_topic": current_topic, "historical_coverage": { "previous_topics": covered_topics[-3:], "topic_overlap_score": topic_overlap, "overlap_percentage": round(overlap_percentage, 1), "content_diversity": diversity_score, }, "strategic_recommendations": recommendations, "research_summary": research_data[:500] + "..." if len(research_data) > 500 else research_data, "suggested_angle": "unique perspective" if overlap_percentage > 30 else "comprehensive overview", "content_gap_analysis": { "avoid_repeating": [ topic for topic in covered_topics if any(word in current_topic.lower() for word in topic.split()[:2]) ], "build_upon": "previous insights" if len(history_data) > 0 else "foundational knowledge", }, } formatted_analysis = f""" CONTENT STRATEGY ANALYSIS ======================== STRATEGIC OVERVIEW: - Topic: {strategy_analysis["content_topic"]} - Previous Content Count: {len(history_data)} - Keyword Overlap: {strategy_analysis["historical_coverage"]["topic_overlap_score"]} keywords ({strategy_analysis["historical_coverage"]["overlap_percentage"]}%) - Content Diversity: {strategy_analysis["historical_coverage"]["content_diversity"]:.2f} RECOMMENDATIONS: {chr(10).join([f"- {rec}" for rec in strategy_analysis["strategic_recommendations"]])} RESEARCH FOUNDATION: {strategy_analysis["research_summary"]} CONTENT POSITIONING: - Suggested Angle: {strategy_analysis["suggested_angle"]} - Build Upon: {strategy_analysis["content_gap_analysis"]["build_upon"]} - Differentiate From: {", ".join(strategy_analysis["content_gap_analysis"]["avoid_repeating"]) if strategy_analysis["content_gap_analysis"]["avoid_repeating"] else "No similar content found"} CREATIVE DIRECTION: Based on historical analysis, focus on providing {strategy_analysis["suggested_angle"]} while ensuring the content complements rather than duplicates previous work. STRUCTURED_DATA: {json.dumps(strategy_analysis, indent=2)} """ return StepOutput(content=formatted_analysis.strip()) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- def create_content_workflow() -> Workflow: research_step = Step( name="Content Research", agent=Agent( name="Research Specialist", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are an expert research specialist for content creation.", "Conduct thorough research on the requested topic.", "Gather current trends, key insights, statistics, and expert perspectives.", "Structure your research with clear sections: Overview, Key Points, Recent Developments, Expert Insights.", "Prioritize accurate, up-to-date information from credible sources.", "Keep research comprehensive but concise for content creators to use.", ], ), ) strategy_step = Step( name="Content Strategy Analysis", executor=analyze_content_strategy, description="Analyze content strategy using historical data to prevent duplication and identify opportunities", ) writer_step = Step( name="Strategic Content Creation", agent=Agent( name="Content Strategist", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are a strategic content writer who creates high-quality, unique content.", "Use the research and strategic analysis to create compelling content.", "Follow the strategic recommendations to ensure content uniqueness.", "Structure content with: Hook, Main Content, Key Takeaways, Call-to-Action.", "Ensure your content builds upon previous work rather than repeating it.", "Include 'Target Audience:' and 'Content Type:' at the end for tracking.", "Make content engaging, actionable, and valuable to readers.", ], ), ) return Workflow( name="Strategic Content Creation", description="Research -> Strategic Analysis -> Content Creation with historical awareness", db=SqliteDb(db_file="tmp/content_workflow.db"), steps=[research_step, strategy_step, writer_step], add_workflow_history_to_steps=True, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- def demo_content_workflow() -> None: workflow = create_content_workflow() print("Strategic Content Creation Workflow") print("Flow: Research -> Strategy Analysis -> Content Writing") print("") print("This workflow prevents duplicate content and ensures strategic progression") print("") print("Try these content requests:") print("- 'Create content about AI in healthcare'") print("- 'Write about machine learning applications' (will detect overlap)") print("- 'Content on blockchain technology' (different topic)") print("") print("Type 'exit' to quit") print("-" * 70) workflow.cli_app( session_id="content_strategy_demo", user="Content Manager", emoji="", stream=True, ) if __name__ == "__main__": demo_content_workflow()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/history/history_in_function.py", "license": "Apache License 2.0", "lines": 201, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/history/intent_routing_with_history.py
""" Intent Routing With History =========================== Demonstrates simple intent routing where all specialist steps share workflow history for context continuity. """ from typing import List from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.workflow.router import Router from agno.workflow.step import Step from agno.workflow.types import StepInput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- tech_support_agent = Agent( name="Technical Support Specialist", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are a technical support specialist with deep product knowledge.", "You have access to the full conversation history with this customer.", "Reference previous interactions to provide better help.", "Build on any troubleshooting steps already attempted.", "Be patient and provide step-by-step technical guidance.", ], ) billing_agent = Agent( name="Billing & Account Specialist", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are a billing and account specialist.", "You have access to the full conversation history with this customer.", "Reference any account details or billing issues mentioned previously.", "Build on any payment or account information already discussed.", "Be helpful with billing questions, refunds, and account changes.", ], ) general_support_agent = Agent( name="General Customer Support", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are a general customer support representative.", "You have access to the full conversation history with this customer.", "Handle general inquiries, product information, and basic support.", "Reference the conversation context - build on what was discussed.", "Be friendly and acknowledge their previous interactions.", ], ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- tech_support_step = Step( name="Technical Support", agent=tech_support_agent, add_workflow_history=True, ) billing_support_step = Step( name="Billing Support", agent=billing_agent, add_workflow_history=True, ) general_support_step = Step( name="General Support", agent=general_support_agent, add_workflow_history=True, ) # --------------------------------------------------------------------------- # Define Router # --------------------------------------------------------------------------- def simple_intent_router(step_input: StepInput) -> List[Step]: current_message = step_input.input or "" current_message_lower = current_message.lower() tech_keywords = [ "api", "error", "bug", "technical", "login", "not working", "broken", "crash", ] billing_keywords = [ "billing", "payment", "refund", "charge", "subscription", "invoice", "plan", ] if any(keyword in current_message_lower for keyword in tech_keywords): print("Routing to Technical Support") return [tech_support_step] if any(keyword in current_message_lower for keyword in billing_keywords): print("Routing to Billing Support") return [billing_support_step] print("Routing to General Support") return [general_support_step] # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- def create_smart_customer_service_workflow() -> Workflow: return Workflow( name="Smart Customer Service", description="Simple routing to specialists with shared conversation history", db=SqliteDb(db_file="tmp/smart_customer_service.db"), steps=[ Router( name="Customer Service Router", selector=simple_intent_router, choices=[tech_support_step, billing_support_step, general_support_step], description="Routes to appropriate specialist based on simple intent detection", ) ], add_workflow_history_to_steps=True, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- def demo_smart_customer_service_cli() -> None: workflow = create_smart_customer_service_workflow() print("Smart Customer Service Demo") print("=" * 60) print("") print("This workflow demonstrates:") print("- Simple routing between Technical, Billing, and General support") print("- Shared conversation history across all agents") print("- Context continuity - agents remember your entire conversation") print("") print("TRY THESE CONVERSATIONS:") print("") print("TECHNICAL SUPPORT:") print(" - 'My API is not working'") print(" - 'I'm getting an error message'") print(" - 'There's a technical bug'") print("") print("BILLING SUPPORT:") print(" - 'I need help with billing'") print(" - 'Can I get a refund?'") print(" - 'My payment was charged twice'") print("") print("GENERAL SUPPORT:") print(" - 'Hello, I have a question'") print(" - 'What features do you offer?'") print(" - 'I need general help'") print("") print("Type 'exit' to quit") print("-" * 60) workflow.cli_app( session_id="smart_customer_service_demo", user="Customer", emoji="", stream=True, show_step_details=True, ) if __name__ == "__main__": demo_smart_customer_service_cli()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/history/intent_routing_with_history.py", "license": "Apache License 2.0", "lines": 159, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/history/step_history.py
""" Step History ============ Demonstrates workflow-level and step-level history controls for conversation-aware content workflows. """ from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.workflow.step import Step, StepInput, StepOutput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents (Meal Planning Workflow) # --------------------------------------------------------------------------- meal_suggester = Agent( name="Meal Suggester", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are a friendly meal planning assistant who suggests meal categories and cuisines.", "Consider the time of day, day of the week, and any context from the conversation.", "Keep suggestions broad (Italian, Asian, healthy, comfort food, quick meals, etc.)", "Ask follow-up questions to understand preferences better.", ], ) recipe_specialist = Agent( name="Recipe Specialist", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are a recipe expert who provides specific, detailed recipe recommendations.", "Pay close attention to the full conversation to understand user preferences and restrictions.", "If the user mentioned avoiding certain foods or wanting healthier options, respect that.", "Provide practical, easy-to-follow recipe suggestions with ingredients and basic steps.", "Reference the conversation naturally (e.g., 'Since you mentioned wanting something healthier...').", ], ) # --------------------------------------------------------------------------- # Define Function (Meal Preference Analysis) # --------------------------------------------------------------------------- def analyze_food_preferences(step_input: StepInput) -> StepOutput: current_request = step_input.input conversation_context = step_input.previous_step_content or "" preferences = { "dietary_restrictions": [], "cuisine_preferences": [], "avoid_list": [], "cooking_style": "any", } full_context = f"{conversation_context} {current_request}".lower() if any(word in full_context for word in ["healthy", "healthier", "light", "fresh"]): preferences["dietary_restrictions"].append("healthy") if any(word in full_context for word in ["vegetarian", "veggie", "no meat"]): preferences["dietary_restrictions"].append("vegetarian") if any(word in full_context for word in ["quick", "fast", "easy", "simple"]): preferences["cooking_style"] = "quick" if any(word in full_context for word in ["comfort", "hearty", "filling"]): preferences["cooking_style"] = "comfort" if "italian" in full_context and ( "had" in full_context or "yesterday" in full_context ): preferences["avoid_list"].append("Italian") if "chinese" in full_context and ( "had" in full_context or "recently" in full_context ): preferences["avoid_list"].append("Chinese") if "love asian" in full_context or "like asian" in full_context: preferences["cuisine_preferences"].append("Asian") if "mediterranean" in full_context: preferences["cuisine_preferences"].append("Mediterranean") guidance = [] if preferences["dietary_restrictions"]: guidance.append( f"Focus on {', '.join(preferences['dietary_restrictions'])} options" ) if preferences["avoid_list"]: guidance.append( f"Avoid {', '.join(preferences['avoid_list'])} cuisine since user had it recently" ) if preferences["cuisine_preferences"]: guidance.append( f"Consider {', '.join(preferences['cuisine_preferences'])} options" ) if preferences["cooking_style"] != "any": guidance.append(f"Prefer {preferences['cooking_style']} cooking style") analysis_result = f""" PREFERENCE ANALYSIS: Current Request: {current_request} Detected Preferences: {chr(10).join(f"- {g}" for g in guidance) if guidance else "- No specific preferences detected"} RECIPE AGENT GUIDANCE: Based on the conversation history, please provide recipe recommendations that align with these preferences. Reference the conversation naturally and explain why these recipes fit their needs. """.strip() return StepOutput(content=analysis_result) # --------------------------------------------------------------------------- # Define Steps (Meal Planning Workflow) # --------------------------------------------------------------------------- suggestion_step = Step(name="Meal Suggestion", agent=meal_suggester) preference_analysis_step = Step( name="Preference Analysis", executor=analyze_food_preferences ) recipe_step = Step(name="Recipe Recommendations", agent=recipe_specialist) # --------------------------------------------------------------------------- # Create Workflow (Workflow-Level History) # --------------------------------------------------------------------------- meal_workflow = Workflow( name="Conversational Meal Planner", description="Smart meal planning with conversation awareness and preference learning", db=SqliteDb(session_table="workflow_session", db_file="tmp/meal_workflow.db"), steps=[suggestion_step, preference_analysis_step, recipe_step], add_workflow_history_to_steps=True, ) # --------------------------------------------------------------------------- # Create Agents (Content Workflow) # --------------------------------------------------------------------------- research_agent = Agent( name="Research Specialist", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are a research specialist who gathers information on topics.", "Conduct thorough research and provide key facts, trends, and insights.", "Focus on current, accurate information from reliable sources.", "Organize your findings in a clear, structured format.", "Provide citations and context for your research.", ], ) content_creator = Agent( name="Content Creator", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are an expert content creator who writes engaging content.", "Use the research provided and CREATE UNIQUE content that stands out.", "IMPORTANT: Review workflow history to understand:", "- What content topics have been covered before", "- What writing styles and formats were used previously", "- User preferences and content patterns", "- Avoid repeating similar content or approaches", "Build on previous themes while keeping content fresh and original.", "Reference the conversation history to maintain consistency in tone and style.", "Create compelling headlines, engaging intros, and valuable content.", ], ) publisher_agent = Agent( name="Content Publisher", model=OpenAIChat(id="gpt-4o"), instructions=[ "You are a content publishing specialist.", "Review the created content and prepare it for publication.", "Add appropriate hashtags, formatting, and publishing recommendations.", "Suggest optimal posting times and distribution channels.", "Ensure content meets platform requirements and best practices.", ], ) # --------------------------------------------------------------------------- # Create Workflow (Step-Level History) # --------------------------------------------------------------------------- content_workflow = Workflow( name="Smart Content Creation Pipeline", description="Research -> Content Creation (with history awareness) -> Publishing", db=SqliteDb(db_file="tmp/content_workflow.db"), steps=[ Step(name="Research Phase", agent=research_agent, add_workflow_history=True), Step(name="Content Creation", agent=content_creator, add_workflow_history=True), Step(name="Content Publishing", agent=publisher_agent), ], ) # --------------------------------------------------------------------------- # Run Workflows # --------------------------------------------------------------------------- def demonstrate_conversational_meal_planning() -> None: session_id = "meal_planning_demo" print("Conversational Meal Planning Demo") print("=" * 60) print("\nUser: What should I cook for dinner tonight?") meal_workflow.print_response( input="What should I cook for dinner tonight?", session_id=session_id, markdown=True, ) print("\nUser: I had Italian yesterday, and I'm trying to eat healthier these days") meal_workflow.print_response( input="I had Italian yesterday, and I'm trying to eat healthier these days", session_id=session_id, markdown=True, ) print("\nUser: Actually, do you have something with fish? I love Asian flavors too") meal_workflow.print_response( input="Actually, do you have something with fish? I love Asian flavors too", session_id=session_id, markdown=True, ) def demo_content_history_cli() -> None: print("Content Creation Demo - Step-Level History Control") print("Only selected steps see previous workflow history") print("") print("Try these content requests:") print("- 'Create a LinkedIn post about AI trends in 2024'") print("- 'Write a Twitter thread about productivity tips'") print("- 'Create a blog intro about remote work benefits'") print("") print("Type 'exit' to quit") print("-" * 70) content_workflow.cli_app( session_id="content_demo", user="Content Requester", emoji="", stream=True, ) if __name__ == "__main__": demonstrate_conversational_meal_planning() demo_content_history_cli()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/history/step_history.py", "license": "Apache License 2.0", "lines": 209, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/long_running/disruption_catchup.py
""" Disruption Catchup ================== Tests full catch-up behavior for a running workflow when reconnecting with `last_event_index=None`. """ import asyncio import json from typing import Optional # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- try: import websockets except ImportError: print("websockets library not installed. Install with: uv pip install websockets") exit(1) # --------------------------------------------------------------------------- # Define Helpers # --------------------------------------------------------------------------- def parse_sse_message(message: str) -> dict: lines = message.strip().split("\n") for line in lines: if line.startswith("data: "): return json.loads(line[6:]) return json.loads(message) # --------------------------------------------------------------------------- # Create Catch-Up Test # --------------------------------------------------------------------------- async def test_full_catchup() -> None: print("\n" + "=" * 80) print("Full Catch-Up Test - Getting ALL Events from Running Workflow") print("=" * 80) ws_url = "ws://localhost:7777/workflows/ws" run_id: Optional[str] = None print("\nPhase 1: Starting workflow and receiving initial events...") try: async with websockets.connect(ws_url) as websocket: print(f"[OK] Connected to {ws_url}") response = await websocket.recv() data = parse_sse_message(response) print(f"[OK] {data.get('message', 'Connected')}") print("\nStarting workflow...") await websocket.send( json.dumps( { "action": "start-workflow", "workflow_id": "content-creation-workflow", "message": "Test full catch-up", "session_id": "full-catchup-test", } ) ) print("\nReceiving initial events:") event_count = 0 max_events = 3 async for message in websocket: data = parse_sse_message(message) event_type = data.get("event") event_index = data.get("event_index", "N/A") if data.get("run_id") and not run_id: run_id = data["run_id"] event_count += 1 print( f" [{event_count}] event_index={event_index}, event={event_type}" ) if event_count >= max_events: print(f"\nDisconnecting after {event_count} events...") break except Exception as e: print(f"Error in Phase 1: {e}") raise if not run_id: print("No run_id captured") return print("\nWaiting 3 seconds for workflow to generate more events...") await asyncio.sleep(3) print("\nPhase 3: Reconnecting with last_event_index=None...") print(" (Requesting ALL events from the start)") try: async with websockets.connect(ws_url) as websocket: print(f"[OK] Reconnected to {ws_url}") response = await websocket.recv() parse_sse_message(response) await websocket.send( json.dumps( { "action": "reconnect", "run_id": run_id, "last_event_index": None, "workflow_id": "content-creation-workflow", "session_id": "full-catchup-test", } ) ) print("\nReceiving catch-up events:") catchup_events = [] new_events = [] got_catch_up = False got_subscribed = False async for message in websocket: data = parse_sse_message(message) event_type = data.get("event") event_index = data.get("event_index") if event_type == "catch_up": got_catch_up = True print("\nCATCH_UP notification:") print(f" missed_events: {data.get('missed_events')}") print(f" current_event_count: {data.get('current_event_count')}") print(f" status: {data.get('status')}") continue if event_type == "subscribed": got_subscribed = True print("\nSUBSCRIBED - now listening for new events") print(f" current_event_count: {data.get('current_event_count')}") continue if event_index is not None: if not got_subscribed: catchup_events.append(data) if len(catchup_events) <= 10: print(f" event_index={event_index}, event={event_type}") elif len(catchup_events) == 11: print(" ... (more catch-up events)") else: new_events.append(data) if len(new_events) <= 5: print(f" event_index={event_index}, event={event_type}") if len(new_events) >= 5: print( f"\nStopping (received {len(catchup_events)} catch-up + {len(new_events)} new events)" ) break if event_type == "WorkflowCompleted": print("\nWorkflow completed") break print("\nVerification:") if not got_catch_up: print("Did not receive 'catch_up' notification") else: print("Received 'catch_up' notification") if catchup_events: first_index = catchup_events[0].get("event_index") last_catchup_index = catchup_events[-1].get("event_index") print("\nCatch-up events:") print(f" First event_index: {first_index}") print(f" Last event_index: {last_catchup_index}") print(f" Total received: {len(catchup_events)}") if first_index == 0: print("Catch-up started from event 0 (got FULL history)") else: print(f"Catch-up started from event {first_index} (should be 0)") event_indices = [e.get("event_index") for e in catchup_events] expected = set(range(min(event_indices), max(event_indices) + 1)) actual = set(event_indices) gaps = expected - actual if gaps: print(f"Gaps in event sequence: {sorted(gaps)}") else: print("No gaps in event sequence") else: print("No catch-up events received") if new_events: print("\nNew events (after subscription):") print(f" Total received: {len(new_events)}") print("Workflow continued streaming after catch-up") else: print("\nNo new events received (workflow may have completed)") except Exception as e: print(f"Error in Phase 3: {e}") raise print("\n" + "=" * 80) print("Full Catch-Up Test Completed") print("=" * 80) print("\nKey Takeaway:") print(" Send last_event_index=None to get ALL events from start,") print(" even when reconnecting to a RUNNING workflow") print("=" * 80) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- async def main() -> None: print("\nStarting Full Catch-Up Test") print("Prerequisites:") print(" 1. AgentOS server should be running at http://localhost:7777") print(" 2. Run: python cookbook/agent_os/workflow/basic_workflow.py") print("\nStarting test in 2 seconds...") await asyncio.sleep(2) try: await test_full_catchup() except ConnectionRefusedError: print("\nConnection refused. Is the AgentOS server running?") print(" Start it with: python cookbook/agent_os/workflow/basic_workflow.py") except Exception as e: print(f"\nTest failed: {e}") import traceback traceback.print_exc() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/long_running/disruption_catchup.py", "license": "Apache License 2.0", "lines": 197, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/long_running/events_replay.py
""" Events Replay ============= Tests replay behavior when reconnecting to a completed workflow run. """ import asyncio import json from typing import Optional # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- try: import websockets except ImportError: print( "[ERROR] websockets library not installed. Install with: uv pip install websockets" ) exit(1) # --------------------------------------------------------------------------- # Define Helpers # --------------------------------------------------------------------------- def parse_sse_message(message: str) -> dict: lines = message.strip().split("\n") for line in lines: if line.startswith("data: "): return json.loads(line[6:]) return json.loads(message) # --------------------------------------------------------------------------- # Create Replay Test # --------------------------------------------------------------------------- async def test_replay() -> None: print("\n" + "=" * 80) print("Replay Test - Reconnecting to Completed Workflow") print("=" * 80) ws_url = "ws://localhost:7777/workflows/ws" run_id: Optional[str] = None total_events = 0 print("\nPhase 1: Starting workflow and letting it complete...") try: async with websockets.connect(ws_url) as websocket: print(f"[OK] Connected to {ws_url}") response = await websocket.recv() data = parse_sse_message(response) print(f"[OK] {data.get('message', 'Connected')}") print("\nStarting workflow...") await websocket.send( json.dumps( { "action": "start-workflow", "workflow_id": "content-creation-workflow", "message": "Quick test workflow", "session_id": "replay-test-session", } ) ) print("\nWaiting for workflow to complete...") async for message in websocket: data = parse_sse_message(message) event_type = data.get("event") if data.get("run_id") and not run_id: run_id = data["run_id"] if data.get("event_index") is not None: total_events = max(total_events, data["event_index"] + 1) if event_type == "WorkflowStarted": print(f" Workflow started (run_id: {run_id})") if event_type == "WorkflowCompleted": print(f" Workflow completed ({total_events} events)") break except Exception as e: print(f"[ERROR] Phase 1: {e}") raise if not run_id: print("[ERROR] No run_id captured") return print("\nWaiting 2 seconds before reconnection...") await asyncio.sleep(2) print("\nPhase 2: Reconnecting to COMPLETED workflow...") print(" Sending last_event_index=10 (should be IGNORED)") try: async with websockets.connect(ws_url) as websocket: print(f"[OK] Reconnected to {ws_url}") response = await websocket.recv() parse_sse_message(response) await websocket.send( json.dumps( { "action": "reconnect", "run_id": run_id, "last_event_index": 10, "workflow_id": "content-creation-workflow", "session_id": "replay-test-session", } ) ) print("\nReceiving replay...") replay_events = [] got_replay_notification = False async for message in websocket: data = parse_sse_message(message) event_type = data.get("event") if event_type == "replay": got_replay_notification = True print("\nREPLAY notification:") print(f" status: {data.get('status')}") print(f" total_events: {data.get('total_events')}") print(f" message: {data.get('message')}") continue if data.get("event_index") is not None: replay_events.append(data) if len(replay_events) > 0 and event_type == "WorkflowCompleted": break print(f"\nReceived {len(replay_events)} events") print("\nVerification:") if not got_replay_notification: print("[ERROR] Did not receive 'replay' notification") else: print("[OK] Received 'replay' notification") if replay_events: first_index = replay_events[0].get("event_index") last_index = replay_events[-1].get("event_index") print(f" First event_index: {first_index}") print(f" Last event_index: {last_index}") if first_index == 0: print("[OK] Replay started from event 0 (correct)") else: print( f"[ERROR] Replay started from event {first_index} (should be 0)" ) if len(replay_events) == total_events: print( f"[OK] Received all {total_events} events (last_event_index was ignored)" ) else: print( f"[ERROR] Received {len(replay_events)} events, expected {total_events}" ) event_indices = [e.get("event_index") for e in replay_events] expected = set(range(min(event_indices), max(event_indices) + 1)) actual = set(event_indices) gaps = expected - actual if gaps: print(f"[ERROR] Gaps in event sequence: {sorted(gaps)}") else: print("[OK] No gaps in event sequence") else: print("[ERROR] No events received during replay") except Exception as e: print(f"[ERROR] Phase 2: {e}") raise print("\n" + "=" * 80) print("Replay Test Completed") print("=" * 80) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- async def main() -> None: print("\nStarting Replay Test") print("Prerequisites:") print(" 1. AgentOS server should be running at http://localhost:7777") print(" 2. Run: python cookbook/agent_os/workflow/basic_workflow.py") print("\nStarting test in 2 seconds...") await asyncio.sleep(2) try: await test_replay() except ConnectionRefusedError: print("\n[ERROR] Connection refused. Is the AgentOS server running?") print(" Start it with: python cookbook/agent_os/workflow/basic_workflow.py") except Exception as e: print(f"\n[ERROR] Test failed: {e}") import traceback traceback.print_exc() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/long_running/events_replay.py", "license": "Apache License 2.0", "lines": 173, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/long_running/websocket_reconnect.py
""" WebSocket Reconnect =================== Tests reconnect behavior for a running workflow: initial subscription, disconnection, reconnect, and missed-event catch-up. """ import asyncio import json from typing import Optional # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- try: import websockets except ImportError: print("websockets library not installed. Install with: uv pip install websockets") exit(1) # --------------------------------------------------------------------------- # Define Helpers # --------------------------------------------------------------------------- def parse_sse_message(message: str) -> dict: lines = message.strip().split("\n") data_line = None for line in lines: if line.startswith("data: "): data_line = line[6:] break if data_line: return json.loads(data_line) return json.loads(message) # --------------------------------------------------------------------------- # Create WebSocket Tester # --------------------------------------------------------------------------- class WorkflowWebSocketTester: def __init__(self, ws_url: str = "ws://localhost:7777/workflows/ws"): self.ws_url = ws_url self.run_id: Optional[str] = None self.last_event_index: Optional[int] = None self.received_events = [] async def test_workflow_execution_with_reconnection(self) -> None: print("\n" + "=" * 80) print("WebSocket Reconnection Test") print("=" * 80) print("\nPhase 1: Starting workflow and receiving initial events...") await self._phase1_start_workflow() print("\nSimulating user leaving page for 3 seconds...") await asyncio.sleep(3) print("\nPhase 2: Reconnecting to workflow...") await self._phase2_reconnect() print("\nTest completed") self._print_summary() async def _phase1_start_workflow(self) -> None: try: async with websockets.connect(self.ws_url) as websocket: print(f"[OK] Connected to {self.ws_url}") response = await websocket.recv() data = parse_sse_message(response) print(f"[OK] Server: {data.get('message', 'Connected')}") print("\nSending: start-workflow action") await websocket.send( json.dumps( { "action": "start-workflow", "workflow_id": "content-creation-workflow", "message": "Research and create content plan for AI agents", "session_id": "test-session-123", } ) ) event_count = 0 max_initial_events = 20 print("\nReceiving initial events:") async for message in websocket: data = parse_sse_message(message) event_type = data.get("event") if "run_id" in data and not self.run_id: self.run_id = data["run_id"] if "event_index" in data: self.last_event_index = data["event_index"] self.received_events.append(data) event_count += 1 event_index = data.get("event_index", "N/A") print( f" [{event_count}] event_index={event_index}, event={event_type}" ) if event_type in ["WorkflowCompleted", "WorkflowError"]: print( f"\nWorkflow finished during initial connection: {event_type}" ) break if event_count >= max_initial_events: print( f"\nSimulating disconnect after {event_count} events " f"(last_event_index={self.last_event_index})" ) break except Exception as e: print(f"Error in Phase 1: {e}") raise async def _phase2_reconnect(self) -> None: if not self.run_id: print("No run_id found, cannot reconnect") return try: async with websockets.connect(self.ws_url) as websocket: print(f"[OK] Reconnected to {self.ws_url}") response = await websocket.recv() data = parse_sse_message(response) print(f"[OK] Server: {data.get('message', 'Connected')}") print( f"\nSending: reconnect action (run_id={self.run_id}, " f"last_event_index={self.last_event_index})" ) await websocket.send( json.dumps( { "action": "reconnect", "run_id": self.run_id, "last_event_index": self.last_event_index, "workflow_id": "content-creation-workflow", "session_id": "test-session-123", } ) ) print("\nReceiving events after reconnection:") event_count = 0 missed_events_count = 0 async for message in websocket: data = parse_sse_message(message) event_type = data.get("event") if "event_index" in data: self.last_event_index = data["event_index"] self.received_events.append(data) event_count += 1 if event_type == "catch_up": missed_events_count = data.get("missed_events", 0) print(f"catch_up: {missed_events_count} missed events") print( f"status={data.get('status')}, current_event_count={data.get('current_event_count')}" ) continue if event_type == "replay": print( f"replay: status={data.get('status')}, total_events={data.get('total_events')}" ) print(f"message={data.get('message')}") continue if event_type == "subscribed": print(f"subscribed: status={data.get('status')}") print(f"current_event_count={data.get('current_event_count')}") print("\nNow listening for NEW events as workflow continues...") continue if event_type == "error": print(f"ERROR: {data.get('error', 'Unknown error')}") print(f"Full data: {data}") continue event_index = data.get("event_index", "N/A") is_missed = event_count <= missed_events_count marker = "MISSED" if is_missed else "NEW" print( f" [{event_count}] {marker} event_index={event_index}, event={event_type}" ) if event_type in ["WorkflowCompleted", "WorkflowError"]: print(f"\nWorkflow finished: {event_type}") break print("\nWebSocket connection closed (workflow may have completed)") except asyncio.TimeoutError: print("\nTimeout waiting for events (30s). Workflow may still be running.") except Exception as e: print(f"Error in Phase 2: {e}") raise def _print_summary(self) -> None: print("\n" + "=" * 80) print("Test Summary") print("=" * 80) print(f"Run ID: {self.run_id}") print(f"Last Event Index: {self.last_event_index}") print(f"Total Events Received: {len(self.received_events)}") event_types = {} for event in self.received_events: event_type = event.get("event", "unknown") event_types[event_type] = event_types.get(event_type, 0) + 1 print("\nEvent Type Breakdown:") for event_type, count in sorted(event_types.items()): print(f" {event_type}: {count}") print("\nEvent Index Validation:") event_indices = [ e.get("event_index") for e in self.received_events if "event_index" in e ] if event_indices: print(f" First event_index: {min(event_indices)}") print(f" Last event_index: {max(event_indices)}") print(f" Total with event_index: {len(event_indices)}") expected = set(range(min(event_indices), max(event_indices) + 1)) actual = set(event_indices) gaps = expected - actual if gaps: print(f"Gaps in event_index: {sorted(gaps)}") else: print("No gaps in event_index (all events received)") else: print("No events with event_index found") print("=" * 80) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- async def main() -> None: print("\nStarting WebSocket Reconnection Test") print("Prerequisites:") print(" 1. AgentOS server should be running at http://localhost:7777") print(" 2. Run: python cookbook/agent_os/workflow/basic_workflow.py") print("\nStarting test in 2 seconds...") await asyncio.sleep(2) tester = WorkflowWebSocketTester() try: await tester.test_workflow_execution_with_reconnection() except ConnectionRefusedError: print("\nConnection refused. Is the AgentOS server running?") print(" Start it with: python cookbook/agent_os/workflow/basic_workflow.py") except Exception as e: print(f"\nTest failed: {e}") import traceback traceback.print_exc() if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/long_running/websocket_reconnect.py", "license": "Apache License 2.0", "lines": 224, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/previous_step_outputs/access_previous_outputs.py
""" Access Previous Outputs ======================= Demonstrates accessing output from multiple prior steps using both named steps and implicit step keys. """ from agno.agent.agent import Agent from agno.tools.hackernews import HackerNewsTools from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step from agno.workflow.types import StepInput, StepOutput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- hackernews_agent = Agent( name="HackerNews Researcher", instructions="You are a researcher specializing in finding the latest tech news and discussions from Hacker News. Focus on startup trends, programming topics, and tech industry insights.", tools=[HackerNewsTools()], ) web_agent = Agent( name="Web Researcher", instructions="You are a comprehensive web researcher. Search across multiple sources including news sites, blogs, and official documentation to gather detailed information.", tools=[WebSearchTools()], ) reasoning_agent = Agent( name="Reasoning Agent", instructions="You are an expert analyst who creates comprehensive reports by analyzing and synthesizing information from multiple sources. Create well-structured, insightful reports.", ) anonymous_hackernews_agent = Agent( instructions="You are a researcher specializing in finding the latest tech news and discussions from Hacker News. Focus on startup trends, programming topics, and tech industry insights.", tools=[HackerNewsTools()], ) anonymous_web_agent = Agent( instructions="You are a comprehensive web researcher. Search across multiple sources including news sites, blogs, and official documentation to gather detailed information.", tools=[WebSearchTools()], ) anonymous_reasoning_agent = Agent( instructions="You are an expert analyst who creates comprehensive reports by analyzing and synthesizing information from multiple sources. Create well-structured, insightful reports.", ) # --------------------------------------------------------------------------- # Define Steps For Named Access # --------------------------------------------------------------------------- research_hackernews = Step( name="research_hackernews", agent=hackernews_agent, description="Research latest tech trends from Hacker News", ) research_web = Step( name="research_web", agent=web_agent, description="Comprehensive web research on the topic", ) def create_comprehensive_report(step_input: StepInput) -> StepOutput: original_topic = step_input.input or "" hackernews_data = step_input.get_step_content("research_hackernews") or "" web_data = step_input.get_step_content("research_web") or "" _ = step_input.get_all_previous_content() report = f""" # Comprehensive Research Report: {original_topic} ## Executive Summary Based on research from HackerNews and web sources, here's a comprehensive analysis of {original_topic}. ## HackerNews Insights {hackernews_data[:500]}... ## Web Research Findings {web_data[:500]}... """ return StepOutput( step_name="comprehensive_report", content=report.strip(), success=True ) comprehensive_report_step = Step( name="comprehensive_report", executor=create_comprehensive_report, description="Create comprehensive report from all research sources", ) reasoning_step = Step( name="final_reasoning", agent=reasoning_agent, description="Apply reasoning to create final insights and recommendations", ) # --------------------------------------------------------------------------- # Define Functions For Implicit Step-Key Access # --------------------------------------------------------------------------- def create_comprehensive_report_from_step_indices(step_input: StepInput) -> StepOutput: original_topic = step_input.input or "" hackernews_data = step_input.get_step_content("step_1") or "" web_data = step_input.get_step_content("step_2") or "" _ = step_input.get_all_previous_content() report = f""" # Comprehensive Research Report: {original_topic} ## Executive Summary Based on research from HackerNews and web sources, here's a comprehensive analysis of {original_topic}. ## HackerNews Insights {hackernews_data[:500]}... ## Web Research Findings {web_data[:500]}... """ return StepOutput(content=report.strip(), success=True) def print_final_report(step_input: StepInput) -> StepOutput: comprehensive_report = step_input.get_step_content("create_comprehensive_report") print("=" * 80) print("FINAL COMPREHENSIVE REPORT") print("=" * 80) print(comprehensive_report) print("=" * 80) print("\nDEBUG: All previous step outputs:") if step_input.previous_step_outputs: for step_name, output in step_input.previous_step_outputs.items(): print(f"- {step_name}: {len(str(output.content))} characters") return StepOutput( step_name="print_final_report", content=f"Printed comprehensive report ({len(comprehensive_report)} characters)", success=True, ) # --------------------------------------------------------------------------- # Create Workflows # --------------------------------------------------------------------------- workflow = Workflow( name="Enhanced Research Workflow", description="Multi-source research with custom data flow and reasoning", steps=[ research_hackernews, research_web, comprehensive_report_step, reasoning_step, ], ) direct_steps_workflow = Workflow( name="Enhanced Research Workflow", description="Multi-source research with custom data flow and reasoning", steps=[ anonymous_hackernews_agent, anonymous_web_agent, create_comprehensive_report_from_step_indices, print_final_report, ], ) # --------------------------------------------------------------------------- # Run Workflows # --------------------------------------------------------------------------- if __name__ == "__main__": workflow.print_response( "Latest developments in artificial intelligence and machine learning", markdown=True, stream=True, ) direct_steps_workflow.print_response( "Latest developments in artificial intelligence and machine learning", )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/previous_step_outputs/access_previous_outputs.py", "license": "Apache License 2.0", "lines": 148, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/run_control/cancel_run.py
""" Cancel Run ========== Demonstrates starting a workflow run in one thread and cancelling it from another. """ import threading import time from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.run.agent import RunEvent from agno.run.base import RunStatus from agno.run.workflow import WorkflowRunEvent from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Define Helpers # --------------------------------------------------------------------------- def long_running_task(workflow: Workflow, run_id_container: dict) -> None: try: final_response = None content_pieces = [] for chunk in workflow.run( "Write a very long story about a dragon who learns to code. " "Make it at least 2000 words with detailed descriptions and dialogue. " "Take your time and be very thorough.", stream=True, ): if "run_id" not in run_id_container and chunk.run_id: print(f"[START] Workflow run started: {chunk.run_id}") run_id_container["run_id"] = chunk.run_id if chunk.event in [RunEvent.run_content]: print(chunk.content, end="", flush=True) content_pieces.append(chunk.content) elif chunk.event == RunEvent.run_cancelled: print(f"\n[CANCELLED] Workflow run was cancelled: {chunk.run_id}") run_id_container["result"] = { "status": "cancelled", "run_id": chunk.run_id, "cancelled": True, "content": "".join(content_pieces)[:200] + "..." if content_pieces else "No content before cancellation", } return elif chunk.event == WorkflowRunEvent.workflow_cancelled: print(f"\n[CANCELLED] Workflow run was cancelled: {chunk.run_id}") run_id_container["result"] = { "status": "cancelled", "run_id": chunk.run_id, "cancelled": True, "content": "".join(content_pieces)[:200] + "..." if content_pieces else "No content before cancellation", } return elif hasattr(chunk, "status") and chunk.status == RunStatus.completed: final_response = chunk if final_response: run_id_container["result"] = { "status": final_response.status.value if final_response.status else "completed", "run_id": final_response.run_id, "cancelled": final_response.status == RunStatus.cancelled, "content": ("".join(content_pieces)[:200] + "...") if content_pieces else "No content", } else: run_id_container["result"] = { "status": "unknown", "run_id": run_id_container.get("run_id"), "cancelled": False, "content": ("".join(content_pieces)[:200] + "...") if content_pieces else "No content", } except Exception as e: print(f"\n[ERROR] Exception in run: {str(e)}") run_id_container["result"] = { "status": "error", "error": str(e), "run_id": run_id_container.get("run_id"), "cancelled": True, "content": "Error occurred", } def cancel_after_delay( workflow: Workflow, run_id_container: dict, delay_seconds: int = 3 ) -> None: print(f"[WAIT] Will cancel workflow run in {delay_seconds} seconds...") time.sleep(delay_seconds) run_id = run_id_container.get("run_id") if run_id: print(f"[CANCEL] Cancelling workflow run: {run_id}") success = workflow.cancel_run(run_id) if success: print(f"[OK] Workflow run {run_id} marked for cancellation") else: print( f"[ERROR] Failed to cancel workflow run {run_id} (may not exist or already completed)" ) else: print("[WARN] No run_id found to cancel") # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- def main() -> None: researcher = Agent( name="Research Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[WebSearchTools()], instructions="Research the given topic and provide key facts and insights.", ) writer = Agent( name="Writing Agent", model=OpenAIChat(id="gpt-4o"), instructions="Write a comprehensive article based on the research provided. Make it engaging and well-structured.", ) research_step = Step( name="research", agent=researcher, description="Research the topic and gather information", ) writing_step = Step( name="writing", agent=writer, description="Write an article based on the research", ) article_workflow = Workflow( description="Automated article creation from research to writing", steps=[research_step, writing_step], debug_mode=True, ) print("[START] Starting workflow run cancellation example...") print("=" * 50) run_id_container = {} workflow_thread = threading.Thread( target=lambda: long_running_task(article_workflow, run_id_container), name="WorkflowRunThread", ) cancel_thread = threading.Thread( target=cancel_after_delay, args=(article_workflow, run_id_container, 8), name="CancelThread", ) print("[RUN] Starting workflow run thread...") workflow_thread.start() print("[RUN] Starting cancellation thread...") cancel_thread.start() print("[WAIT] Waiting for threads to complete...") workflow_thread.join() cancel_thread.join() print("\n" + "=" * 50) print("RESULTS") print("=" * 50) result = run_id_container.get("result") if result: print(f"Status: {result['status']}") print(f"Run ID: {result['run_id']}") print(f"Was Cancelled: {result['cancelled']}") if result.get("error"): print(f"Error: {result['error']}") else: print(f"Content Preview: {result['content']}") if result["cancelled"]: print("\n[OK] SUCCESS: Workflow run was successfully cancelled") else: print("\n[WARN] Workflow run completed before cancellation") else: print( "[ERROR] No result obtained - check if cancellation happened during streaming" ) print("\nWorkflow cancellation example completed") # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": main()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/run_control/cancel_run.py", "license": "Apache License 2.0", "lines": 179, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/run_control/deep_copy.py
""" Workflow Deep Copy ================== Demonstrates creating isolated workflow copies with `deep_copy(update=...)`. """ from agno.agent import Agent from agno.models.openai import OpenAIResponses from agno.workflow import Workflow from agno.workflow.step import Step # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- outline_agent = Agent( name="Outline Agent", model=OpenAIResponses(id="gpt-5.2"), instructions="Create a concise outline for the requested topic.", ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- outline_step = Step(name="Draft Outline", agent=outline_agent) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- base_workflow = Workflow( name="Base Editorial Workflow", description="Produces editorial outlines.", steps=[outline_step], session_id="base-session", session_state={"audience": "engineers", "tone": "concise"}, metadata={"owner": "editorial"}, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": copied_workflow = base_workflow.deep_copy( update={ "name": "Copied Editorial Workflow", "session_id": "copied-session", } ) if copied_workflow.session_state is not None: copied_workflow.session_state["audience"] = "executives" if copied_workflow.metadata is not None: copied_workflow.metadata["owner"] = "growth" if isinstance(copied_workflow.steps, list) and copied_workflow.steps: copied_workflow.steps[0].name = "Draft Outline Copy" print("Original workflow") print(f" Name: {base_workflow.name}") print(f" Session ID: {base_workflow.session_id}") print(f" Session State: {base_workflow.session_state}") print(f" Metadata: {base_workflow.metadata}") if isinstance(base_workflow.steps, list) and base_workflow.steps: print(f" First Step: {base_workflow.steps[0].name}") print("\nCopied workflow") print(f" Name: {copied_workflow.name}") print(f" Session ID: {copied_workflow.session_id}") print(f" Session State: {copied_workflow.session_state}") print(f" Metadata: {copied_workflow.metadata}") if isinstance(copied_workflow.steps, list) and copied_workflow.steps: print(f" First Step: {copied_workflow.steps[0].name}")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/run_control/deep_copy.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/run_control/event_storage.py
""" Event Storage ============= Demonstrates storing workflow events while skipping selected high-volume events. """ from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.run.agent import ( RunContentEvent, RunEvent, ToolCallCompletedEvent, ToolCallStartedEvent, ) from agno.run.workflow import WorkflowRunEvent, WorkflowRunOutput from agno.tools.hackernews import HackerNewsTools from agno.workflow.parallel import Parallel from agno.workflow.step import Step from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- news_agent = Agent( name="News Agent", model=OpenAIChat(id="gpt-5.2"), tools=[HackerNewsTools()], instructions="You are a news researcher. Get the latest tech news and summarize key points.", ) search_agent = Agent( name="Search Agent", model=OpenAIChat(id="gpt-5.2"), instructions="You are a search specialist. Find relevant information on given topics.", ) analysis_agent = Agent( name="Analysis Agent", model=OpenAIChat(id="gpt-5.2"), instructions="You are an analyst. Analyze the provided information and give insights.", ) summary_agent = Agent( name="Summary Agent", model=OpenAIChat(id="gpt-5.2"), instructions="You are a summarizer. Create concise summaries of the provided content.", ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step(name="Research Step", agent=news_agent) search_step = Step(name="Search Step", agent=search_agent) # --------------------------------------------------------------------------- # Helper # --------------------------------------------------------------------------- def print_stored_events(run_response: WorkflowRunOutput, example_name: str) -> None: print(f"\n--- {example_name} - Stored Events ---") if run_response.events: print(f"Total stored events: {len(run_response.events)}") for i, event in enumerate(run_response.events, 1): print(f" {i}. {event.event}") else: print("No events stored") print() # --------------------------------------------------------------------------- # Run Examples # --------------------------------------------------------------------------- if __name__ == "__main__": print("=== Simple Step Workflow with Event Storage ===") step_workflow = Workflow( name="Simple Step Workflow", description="Basic workflow demonstrating step event storage", db=SqliteDb(session_table="workflow_session", db_file="tmp/workflow.db"), steps=[research_step, search_step], store_events=True, events_to_skip=[ WorkflowRunEvent.step_started, WorkflowRunEvent.workflow_completed, RunEvent.run_content, RunEvent.run_started, RunEvent.run_completed, ], ) print("Running Step workflow with streaming...") for event in step_workflow.run( input="AI trends in 2024", stream=True, stream_events=True, ): if not isinstance( event, (RunContentEvent, ToolCallStartedEvent, ToolCallCompletedEvent) ): print( f"Event: {event.event if hasattr(event, 'event') else type(event).__name__}" ) run_response = step_workflow.get_last_run_output() print("\nStep workflow completed") print( f"Total events stored: {len(run_response.events) if run_response and run_response.events else 0}" ) print_stored_events(run_response, "Simple Step Workflow") print("=== Parallel Example ===") parallel_workflow = Workflow( name="Parallel Research Workflow", steps=[ Parallel( Step(name="News Research", agent=news_agent), Step(name="Web Search", agent=search_agent), name="Parallel Research", ), Step(name="Combine Results", agent=analysis_agent), Step(name="Summarize", agent=summary_agent), ], db=SqliteDb( session_table="workflow_parallel", db_file="tmp/workflow_parallel.db" ), store_events=True, events_to_skip=[ WorkflowRunEvent.parallel_execution_started, WorkflowRunEvent.parallel_execution_completed, ], ) print("Running Parallel workflow...") for event in parallel_workflow.run( input="Research machine learning developments", stream=True, stream_events=True, ): if not isinstance(event, RunContentEvent): print( f"Event: {event.event if hasattr(event, 'event') else type(event).__name__}" ) run_response = parallel_workflow.get_last_run_output() print(f"Parallel workflow stored {len(run_response.events)} events") print_stored_events(run_response, "Parallel Workflow")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/run_control/event_storage.py", "license": "Apache License 2.0", "lines": 131, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/run_control/executor_events.py
""" Executor Events =============== Demonstrates filtering internal executor events during streamed workflow runs. """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow.step import Step from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- agent = Agent( name="ResearchAgent", model=OpenAIChat(id="gpt-4o"), instructions="You are a helpful research assistant. Be concise.", ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="Research Workflow", steps=[Step(name="Research", agent=agent)], stream=True, stream_executor_events=False, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- def main() -> None: print("\n" + "=" * 70) print("Workflow Streaming Example: stream_executor_events=False") print("=" * 70) print( "\nThis will show only workflow and step events and will not yield RunContent and TeamRunContent events" ) print("Filtering out internal agent/team events for cleaner output.\n") for event in workflow.run( "What is Python?", stream=True, stream_events=True, ): event_name = event.event if hasattr(event, "event") else type(event).__name__ print(f" -> {event_name}") if __name__ == "__main__": main()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/run_control/executor_events.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/run_control/metrics.py
""" Workflow Metrics ================ Demonstrates reading workflow and step-level metrics from `WorkflowRunOutput`. """ import json from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.run.workflow import WorkflowRunOutput from agno.team import Team from agno.tools.hackernews import HackerNewsTools from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- hackernews_agent = Agent( name="Hackernews Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[HackerNewsTools()], role="Extract key insights and content from Hackernews posts", ) web_agent = Agent( name="Web Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[WebSearchTools()], role="Search the web for the latest news and trends", ) content_planner = Agent( name="Content Planner", model=OpenAIChat(id="gpt-4o"), instructions=[ "Plan a content schedule over 4 weeks for the provided topic and research content", "Ensure that I have posts for 3 posts per week", ], ) # --------------------------------------------------------------------------- # Create Team # --------------------------------------------------------------------------- research_team = Team( name="Research Team", members=[hackernews_agent, web_agent], instructions="Research tech topics from Hackernews and the web", ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step(name="Research Step", team=research_team) content_planning_step = Step(name="Content Planning Step", agent=content_planner) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": content_creation_workflow = Workflow( name="Content Creation Workflow", description="Automated content creation from blog posts to social media", db=SqliteDb(session_table="workflow_session", db_file="tmp/workflow.db"), steps=[research_step, content_planning_step], ) workflow_run_response: WorkflowRunOutput = content_creation_workflow.run( input="AI trends in 2024" ) if workflow_run_response.metrics: print("\n" + "-" * 60) print("WORKFLOW METRICS") print("-" * 60) print(json.dumps(workflow_run_response.metrics.to_dict(), indent=2)) print("\nWORKFLOW DURATION") if workflow_run_response.metrics.duration: print( f"Total execution time: {workflow_run_response.metrics.duration:.2f} seconds" ) print("\nSTEP-LEVEL METRICS") for step_name, step_metrics in workflow_run_response.metrics.steps.items(): print(f"\nStep: {step_name}") if step_metrics.metrics and step_metrics.metrics.duration: print(f" Duration: {step_metrics.metrics.duration:.2f} seconds") if step_metrics.metrics and step_metrics.metrics.total_tokens: print(f" Tokens: {step_metrics.metrics.total_tokens}") else: print("\nNo workflow metrics available")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/run_control/metrics.py", "license": "Apache License 2.0", "lines": 83, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/run_control/remote_workflow.py
""" Remote Workflow =============== Demonstrates executing a workflow hosted on a remote server using `RemoteWorkflow`. """ import asyncio import os from agno.workflow import RemoteWorkflow # --------------------------------------------------------------------------- # Create Remote Workflow # --------------------------------------------------------------------------- remote_workflow = RemoteWorkflow( base_url=os.getenv("AGNO_REMOTE_BASE_URL", "http://localhost:7777"), workflow_id=os.getenv("AGNO_REMOTE_WORKFLOW_ID", "qa-workflow"), ) async def run_remote_examples() -> None: print("Remote workflow configuration") print(f" Base URL: {remote_workflow.base_url}") print(f" Workflow ID: {remote_workflow.id}") try: response = await remote_workflow.arun( input="Summarize the latest progress in AI coding assistants.", stream=False, ) print("\nNon-streaming response preview") print(f" Run ID: {response.run_id}") print(f" Content: {str(response.content)[:240]}") except Exception as exc: print("\nRemote run failed.") print(" Ensure AgentOS is running and the workflow ID exists.") print(f" Error: {exc}") return try: print("\nStreaming response preview") stream = remote_workflow.arun( input="List three practical use-cases for autonomous workflows.", stream=True, stream_events=True, ) async for event in stream: event_name = getattr(event, "event", type(event).__name__) content = getattr(event, "content", None) if content: print(content, end="", flush=True) elif event_name: print(f"\n[{event_name}]") print() except Exception as exc: print("\nStreaming run failed.") print(f" Error: {exc}") # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": asyncio.run(run_remote_examples())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/run_control/remote_workflow.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/run_control/workflow_cli.py
""" Workflow CLI ============ Demonstrates using `Workflow.cli_app()` for interactive command-line workflow runs. """ import os import sys from agno.agent import Agent from agno.models.openai import OpenAIResponses from agno.workflow import Workflow from agno.workflow.step import Step # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- assistant_agent = Agent( name="CLI Assistant", model=OpenAIResponses(id="gpt-5.2"), instructions="Answer clearly and provide concise, actionable output.", ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- assistant_step = Step(name="Assistant", agent=assistant_agent) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="Workflow CLI Demo", description="Simple workflow used to demonstrate the built-in CLI app.", steps=[assistant_step], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": starter_prompt = os.getenv( "WORKFLOW_CLI_PROMPT", "Create a three-step plan for shipping a workflow feature.", ) if sys.stdin.isatty(): print("Starting interactive workflow CLI. Type 'exit' to stop.") workflow.cli_app( input=starter_prompt, stream=True, user="Developer", exit_on=["exit", "quit"], ) else: print("Non-interactive environment detected; running a single response.") workflow.print_response(input=starter_prompt, stream=True) print("Run this script in a terminal to use interactive cli_app mode.")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/run_control/workflow_cli.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/run_control/workflow_serialization.py
""" Workflow Serialization ====================== Demonstrates `to_dict()`, `save()`, and `load()` for workflow persistence. """ import json from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIResponses from agno.workflow import Workflow from agno.workflow.step import Step # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- research_agent = Agent( name="Research Agent", model=OpenAIResponses(id="gpt-5.2"), instructions="Research the topic and gather key findings.", ) writer_agent = Agent( name="Writer Agent", model=OpenAIResponses(id="gpt-5.2"), instructions="Turn research notes into a concise summary.", ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step(name="Research", agent=research_agent) write_step = Step(name="Write", agent=writer_agent) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow_db = SqliteDb( db_file="tmp/workflow_serialization.db", session_table="workflow_serialization" ) workflow = Workflow( id="serialization-demo-workflow", name="Serialization Demo Workflow", description="Workflow used to demonstrate serialization and persistence APIs.", db=workflow_db, steps=[research_step, write_step], metadata={"owner": "cookbook", "topic": "serialization"}, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": workflow_dict = workflow.to_dict() print("Serialized workflow dictionary") print(json.dumps(workflow_dict, indent=2)[:1200]) version = workflow.save(db=workflow_db, label="serialization-demo") print(f"\nSaved workflow version: {version}") loaded_workflow = Workflow.load( id="serialization-demo-workflow", db=workflow_db, label="serialization-demo", ) if loaded_workflow is None: print("Failed to load workflow from the database.") else: step_names = [] if isinstance(loaded_workflow.steps, list): step_names = [ step.name for step in loaded_workflow.steps if hasattr(step, "name") ] print("\nLoaded workflow summary") print(f" Name: {loaded_workflow.name}") print(f" Description: {loaded_workflow.description}") print(f" Steps: {step_names}")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/run_control/workflow_serialization.py", "license": "Apache License 2.0", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/session_state/rename_session.py
""" Rename Session ============== Demonstrates auto-generating a workflow session name after a run. """ from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step from agno.workflow.steps import Steps from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- researcher = Agent( name="Research Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[WebSearchTools()], instructions="Research the given topic and provide key facts and insights.", ) writer = Agent( name="Writing Agent", model=OpenAIChat(id="gpt-4o"), instructions="Write a comprehensive article based on the research provided. Make it engaging and well-structured.", ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step( name="research", agent=researcher, description="Research the topic and gather information", ) writing_step = Step( name="writing", agent=writer, description="Write an article based on the research", ) article_creation_sequence = Steps( name="article_creation", description="Complete article creation workflow from research to writing", steps=[research_step, writing_step], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": article_workflow = Workflow( description="Automated article creation from research to writing", steps=[article_creation_sequence], db=SqliteDb(db_file="tmp/workflows.db"), debug_mode=True, ) article_workflow.print_response( input="Write an article about the benefits of renewable energy", markdown=True, ) article_workflow.set_session_name(autogenerate=True) print(f"New session name: {article_workflow.get_session_name()}")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/session_state/rename_session.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/session_state/state_in_condition.py
""" State In Condition ================== Demonstrates using workflow session state in a `Condition` evaluator and executor functions. """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow.condition import Condition from agno.workflow.step import Step, StepInput, StepOutput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Define Session-State Functions # --------------------------------------------------------------------------- def check_user_has_context(step_input: StepInput, session_state: dict) -> bool: print("\n=== Evaluating Condition ===") print(f"User ID: {session_state.get('current_user_id')}") print(f"Session ID: {session_state.get('current_session_id')}") print(f"Has been greeted: {session_state.get('has_been_greeted', False)}") return session_state.get("has_been_greeted", False) def mark_user_as_greeted(step_input: StepInput, session_state: dict) -> StepOutput: print("\n=== Marking User as Greeted ===") session_state["has_been_greeted"] = True session_state["greeting_count"] = session_state.get("greeting_count", 0) + 1 return StepOutput( content=f"User has been greeted. Total greetings: {session_state['greeting_count']}" ) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- greeter_agent = Agent( name="Greeter", model=OpenAIChat(id="gpt-5.2"), instructions="Greet the user warmly and introduce yourself.", markdown=True, ) contextual_agent = Agent( name="Contextual Assistant", model=OpenAIChat(id="gpt-5.2"), instructions="Continue the conversation with context. You already know the user.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="Conditional Greeting Workflow", steps=[ Condition( name="Check If New User", description="Check if this is a new user who needs greeting", evaluator=lambda step_input, session_state: ( not check_user_has_context( step_input, session_state, ) ), steps=[ Step( name="Greet User", description="Greet the new user", agent=greeter_agent, ), Step( name="Mark as Greeted", description="Mark user as greeted in session", executor=mark_user_as_greeted, ), ], ), Step( name="Handle Query", description="Handle the user's query with or without greeting", agent=contextual_agent, ), ], session_state={ "has_been_greeted": False, "greeting_count": 0, }, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- def run_example() -> None: print("=" * 80) print("First Run - New User (Condition will be True, greeting will happen)") print("=" * 80) workflow.print_response( input="Hi, can you help me with something?", session_id="user-123", user_id="user-123", stream=True, ) print("\n" + "=" * 80) print("Second Run - Same Session (Skips greeting)") print("=" * 80) workflow.print_response( input="Tell me a joke", session_id="user-123", user_id="user-123", stream=True, ) if __name__ == "__main__": run_example()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/session_state/state_in_condition.py", "license": "Apache License 2.0", "lines": 104, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/session_state/state_in_function.py
""" State In Function ================= Demonstrates reading and mutating workflow session state inside custom function executors. """ from typing import Iterator, Union from agno.agent import Agent from agno.db.in_memory import InMemoryDb from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.run.workflow import WorkflowRunOutputEvent from agno.team import Team from agno.tools.hackernews import HackerNewsTools from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step, StepInput, StepOutput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- hackernews_agent = Agent( name="Hackernews Agent", model=OpenAIChat(id="gpt-4o"), tools=[HackerNewsTools()], instructions="Extract key insights and content from Hackernews posts", ) web_agent = Agent( name="Web Agent", model=OpenAIChat(id="gpt-4o"), tools=[WebSearchTools()], instructions="Search the web for the latest news and trends", ) content_planner = Agent( name="Content Planner", model=OpenAIChat(id="gpt-4o"), instructions=[ "Plan a content schedule over 4 weeks for the provided topic and research content", "Ensure that I have posts for 3 posts per week", ], ) streaming_content_planner = Agent( name="Content Planner", model=OpenAIChat(id="gpt-4o"), instructions=[ "Plan a content schedule over 4 weeks for the provided topic and research content", "Ensure that I have posts for 3 posts per week", ], db=InMemoryDb(), ) # --------------------------------------------------------------------------- # Create Team # --------------------------------------------------------------------------- research_team = Team( name="Research Team", model=OpenAIChat(id="gpt-4o"), members=[hackernews_agent, web_agent], instructions="Analyze content and create comprehensive social media strategy", ) # --------------------------------------------------------------------------- # Define Function Executors # --------------------------------------------------------------------------- def custom_content_planning_function( step_input: StepInput, session_state: dict, ) -> StepOutput: message = step_input.input previous_step_content = step_input.previous_step_content if "content_plans" not in session_state: session_state["content_plans"] = [] if "plan_counter" not in session_state: session_state["plan_counter"] = 0 session_state["plan_counter"] += 1 current_plan_id = session_state["plan_counter"] planning_prompt = f""" STRATEGIC CONTENT PLANNING REQUEST: Core Topic: {message} Plan ID: #{current_plan_id} Research Results: {previous_step_content[:500] if previous_step_content else "No research results"} Previous Plans Count: {len(session_state["content_plans"])} Planning Requirements: 1. Create a comprehensive content strategy based on the research 2. Leverage the research findings effectively 3. Identify content formats and channels 4. Provide timeline and priority recommendations 5. Include engagement and distribution strategies Please create a detailed, actionable content plan. """ try: response = content_planner.run(planning_prompt) plan_data = { "id": current_plan_id, "topic": message, "content": response.content, "timestamp": f"Plan #{current_plan_id}", "has_research": bool(previous_step_content), } session_state["content_plans"].append(plan_data) enhanced_content = f""" ## Strategic Content Plan #{current_plan_id} **Planning Topic:** {message} **Research Integration:** {"[PASS] Research-based" if previous_step_content else "[FAIL] No research foundation"} **Total Plans Created:** {len(session_state["content_plans"])} **Content Strategy:** {response.content} **Custom Planning Enhancements:** - Research Integration: {"High" if previous_step_content else "Baseline"} - Strategic Alignment: Optimized for multi-channel distribution - Execution Ready: Detailed action items included - Session History: {len(session_state["content_plans"])} plans stored **Plan ID:** #{current_plan_id} """.strip() return StepOutput(content=enhanced_content) except Exception as e: return StepOutput( content=f"Custom content planning failed: {str(e)}", success=False, ) def content_summary_function(step_input: StepInput, session_state: dict) -> StepOutput: if "content_plans" not in session_state or not session_state["content_plans"]: return StepOutput( content="No content plans found in session state.", success=False ) plans = session_state["content_plans"] summary = f""" ## Content Planning Session Summary **Total Plans Created:** {len(plans)} **Session Statistics:** - Plans with research: {len([p for p in plans if p["has_research"]])} - Plans without research: {len([p for p in plans if not p["has_research"]])} **Plan Overview:** """ for plan in plans: summary += f""" ### Plan #{plan["id"]} - {plan["topic"]} - Research Available: {"[PASS]" if plan["has_research"] else "[FAIL]"} - Status: Completed """ session_state["session_summarized"] = True session_state["total_plans_summarized"] = len(plans) return StepOutput(content=summary.strip()) def custom_content_planning_function_stream( step_input: StepInput, session_state: dict, ) -> Iterator[Union[WorkflowRunOutputEvent, StepOutput]]: message = step_input.input previous_step_content = step_input.previous_step_content if "content_plans" not in session_state: session_state["content_plans"] = [] if "plan_counter" not in session_state: session_state["plan_counter"] = 0 session_state["plan_counter"] += 1 current_plan_id = session_state["plan_counter"] planning_prompt = f""" STRATEGIC CONTENT PLANNING REQUEST: Core Topic: {message} Plan ID: #{current_plan_id} Research Results: {previous_step_content[:500] if previous_step_content else "No research results"} Previous Plans Count: {len(session_state["content_plans"])} Planning Requirements: 1. Create a comprehensive content strategy based on the research 2. Leverage the research findings effectively 3. Identify content formats and channels 4. Provide timeline and priority recommendations 5. Include engagement and distribution strategies Please create a detailed, actionable content plan. """ try: response_iterator = streaming_content_planner.run( planning_prompt, stream=True, stream_events=True, ) for event in response_iterator: yield event response = streaming_content_planner.get_last_run_output() plan_data = { "id": current_plan_id, "topic": message, "content": response.content if response else "No content generated", "timestamp": f"Plan #{current_plan_id}", "has_research": bool(previous_step_content), } session_state["content_plans"].append(plan_data) enhanced_content = f""" ## Strategic Content Plan #{current_plan_id} **Planning Topic:** {message} **Research Integration:** {"[PASS] Research-based" if previous_step_content else "[FAIL] No research foundation"} **Total Plans Created:** {len(session_state["content_plans"])} **Content Strategy:** {response.content if response else "Content generation failed"} **Custom Planning Enhancements:** - Research Integration: {"High" if previous_step_content else "Baseline"} - Strategic Alignment: Optimized for multi-channel distribution - Execution Ready: Detailed action items included - Session History: {len(session_state["content_plans"])} plans stored **Plan ID:** #{current_plan_id} """.strip() yield StepOutput(content=enhanced_content) except Exception as e: yield StepOutput( content=f"Custom content planning failed: {str(e)}", success=False, ) def content_summary_function_stream( step_input: StepInput, session_state: dict, ) -> Iterator[StepOutput]: plans = session_state["content_plans"] summary = f""" ## Content Planning Session Summary **Total Plans Created:** {len(plans)} **Session Statistics:** - Plans with research: {len([p for p in plans if p["has_research"]])} - Plans without research: {len([p for p in plans if not p["has_research"]])} **Plan Overview:** """ for plan in plans: summary += f""" ### Plan #{plan["id"]} - {plan["topic"]} - Research Available: {"[PASS]" if plan["has_research"] else "[FAIL]"} - Status: Completed """ session_state["session_summarized"] = True session_state["total_plans_summarized"] = len(plans) yield StepOutput(content=summary.strip()) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step( name="Research Step", team=research_team, ) content_planning_step = Step( name="Content Planning Step", executor=custom_content_planning_function, ) content_summary_step = Step( name="Content Summary Step", executor=content_summary_function, ) stream_content_planning_step = Step( name="Content Planning Step", executor=custom_content_planning_function_stream, ) stream_content_summary_step = Step( name="Content Summary Step", executor=content_summary_function_stream, ) # --------------------------------------------------------------------------- # Create Workflows # --------------------------------------------------------------------------- content_creation_workflow = Workflow( name="Content Creation Workflow", description="Automated content creation with custom execution options and session state", db=SqliteDb( session_table="workflow_session", db_file="tmp/workflow.db", ), steps=[research_step, content_planning_step, content_summary_step], session_state={"content_plans": [], "plan_counter": 0}, ) streaming_content_workflow = Workflow( name="Streaming Content Creation Workflow", description="Automated content creation with streaming custom execution functions and session state", db=SqliteDb( session_table="workflow_session", db_file="tmp/workflow.db", ), steps=[research_step, stream_content_planning_step, stream_content_summary_step], session_state={"content_plans": [], "plan_counter": 0}, ) # --------------------------------------------------------------------------- # Run Workflows # --------------------------------------------------------------------------- if __name__ == "__main__": print("=== First Workflow Run ===") content_creation_workflow.print_response( input="AI trends in 2024", markdown=True, ) print( f"\nSession State After First Run: {content_creation_workflow.get_session_state()}" ) print("\n" + "=" * 60 + "\n") print("=== Second Workflow Run (Same Session) ===") content_creation_workflow.print_response( input="Machine Learning automation tools", markdown=True, ) print(f"\nFinal Session State: {content_creation_workflow.get_session_state()}") print("\n=== First Streaming Workflow Run ===") streaming_content_workflow.print_response( input="AI trends in 2024", markdown=True, stream=True, ) print( f"\nSession State After First Run: {streaming_content_workflow.get_session_state()}" ) print("\n" + "=" * 60 + "\n") print("=== Second Streaming Workflow Run (Same Session) ===") streaming_content_workflow.print_response( input="Machine Learning automation tools", markdown=True, stream=True, ) print(f"\nFinal Session State: {streaming_content_workflow.get_session_state()}")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/session_state/state_in_function.py", "license": "Apache License 2.0", "lines": 306, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/session_state/state_in_router.py
""" State In Router =============== Demonstrates router selectors that use and update workflow session state for adaptive routing. """ from typing import List from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.models.openai.chat import OpenAIChat as OpenAIChatLegacy from agno.run import RunContext from agno.workflow.router import Router from agno.workflow.step import Step, StepInput, StepOutput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Define Router Functions (Preference-Based Routing) # --------------------------------------------------------------------------- def route_based_on_user_preference(step_input: StepInput, session_state: dict) -> Step: print("\n=== Routing Decision ===") print(f"User ID: {session_state.get('current_user_id')}") print(f"Session ID: {session_state.get('current_session_id')}") user_preference = session_state.get("agent_preference", "general") interaction_count = session_state.get("interaction_count", 0) print(f"User Preference: {user_preference}") print(f"Interaction Count: {interaction_count}") session_state["interaction_count"] = interaction_count + 1 if user_preference == "technical": print("Routing to Technical Expert") return technical_step if user_preference == "friendly": print("Routing to Friendly Assistant") return friendly_step if interaction_count == 0: print("Routing to Onboarding (first interaction)") return onboarding_step print("Routing to General Assistant") return general_step def set_user_preference(step_input: StepInput, session_state: dict) -> StepOutput: print("\n=== Setting User Preference ===") interaction_count = session_state.get("interaction_count", 0) if interaction_count % 3 == 1: session_state["agent_preference"] = "technical" preference = "technical" elif interaction_count % 3 == 2: session_state["agent_preference"] = "friendly" preference = "friendly" else: session_state["agent_preference"] = "general" preference = "general" print(f"Set preference to: {preference}") return StepOutput(content=f"Preference set to: {preference}") # --------------------------------------------------------------------------- # Create Agents (Preference-Based Routing) # --------------------------------------------------------------------------- onboarding_agent = Agent( name="Onboarding Agent", model=OpenAIChat(id="gpt-5.2"), instructions=( "Welcome new users and ask about their preferences. " "Determine if they prefer technical or friendly assistance." ), markdown=True, ) technical_agent = Agent( name="Technical Expert", model=OpenAIChat(id="gpt-5.2"), instructions=( "You are a technical expert. Provide detailed, technical answers with code examples and best practices." ), markdown=True, ) friendly_agent = Agent( name="Friendly Assistant", model=OpenAIChat(id="gpt-5.2"), instructions=( "You are a friendly, casual assistant. Use simple language and make the conversation engaging." ), markdown=True, ) general_agent = Agent( name="General Assistant", model=OpenAIChat(id="gpt-5.2"), instructions=( "You are a balanced assistant. Provide helpful answers that are neither too technical nor too casual." ), markdown=True, ) # --------------------------------------------------------------------------- # Define Steps (Preference-Based Routing) # --------------------------------------------------------------------------- onboarding_step = Step( name="Onboard User", description="Onboard new user and set preferences", agent=onboarding_agent, ) technical_step = Step( name="Technical Response", description="Provide technical assistance", agent=technical_agent, ) friendly_step = Step( name="Friendly Response", description="Provide friendly assistance", agent=friendly_agent, ) general_step = Step( name="General Response", description="Provide general assistance", agent=general_agent, ) # --------------------------------------------------------------------------- # Create Workflow (Preference-Based Routing) # --------------------------------------------------------------------------- adaptive_assistant_workflow = Workflow( name="Adaptive Assistant Workflow", steps=[ Router( name="Route to Appropriate Agent", description="Route to the appropriate agent based on user preferences", selector=route_based_on_user_preference, choices=[ onboarding_step, technical_step, friendly_step, general_step, ], ), Step( name="Update Preferences", description="Update user preferences based on interaction", executor=set_user_preference, ), ], session_state={ "agent_preference": "general", "interaction_count": 0, }, ) # --------------------------------------------------------------------------- # Define Task Tools (Task Routing) # --------------------------------------------------------------------------- def add_task(run_context: RunContext, task: str, priority: str = "medium") -> str: if run_context.session_state is None: run_context.session_state = {} if "task_list" not in run_context.session_state: run_context.session_state["task_list"] = [] existing_tasks = [ existing_task["name"].lower() for existing_task in run_context.session_state["task_list"] ] if task.lower() not in existing_tasks: task_item = { "name": task, "priority": priority, "status": "pending", "id": len(run_context.session_state["task_list"]) + 1, } run_context.session_state["task_list"].append(task_item) return f"Added task '{task}' with {priority} priority to the task list." return f"Task '{task}' already exists in the task list." def complete_task(run_context: RunContext, task_name: str) -> str: if run_context.session_state is None: run_context.session_state = {} if "task_list" not in run_context.session_state: run_context.session_state["task_list"] = [] return f"Task list is empty. Cannot complete '{task_name}'." for task in run_context.session_state["task_list"]: if task["name"].lower() == task_name.lower(): task["status"] = "completed" return f"Marked task '{task['name']}' as completed." return f"Task '{task_name}' not found in the task list." def set_task_priority(run_context: RunContext, task_name: str, priority: str) -> str: if run_context.session_state is None: run_context.session_state = {} if "task_list" not in run_context.session_state: run_context.session_state["task_list"] = [] return f"Task list is empty. Cannot update priority for '{task_name}'." valid_priorities = ["low", "medium", "high"] if priority.lower() not in valid_priorities: return f"Invalid priority '{priority}'. Must be one of: {', '.join(valid_priorities)}" for task in run_context.session_state["task_list"]: if task["name"].lower() == task_name.lower(): old_priority = task["priority"] task["priority"] = priority.lower() return f"Updated task '{task['name']}' priority from {old_priority} to {priority}." return f"Task '{task_name}' not found in the task list." def list_tasks(run_context: RunContext, status_filter: str = "all") -> str: if run_context.session_state is None: run_context.session_state = {} if ( "task_list" not in run_context.session_state or not run_context.session_state["task_list"] ): return "Task list is empty." tasks = run_context.session_state["task_list"] if status_filter != "all": tasks = [task for task in tasks if task["status"] == status_filter] if not tasks: return f"No {status_filter} tasks found." priority_order = {"high": 1, "medium": 2, "low": 3} tasks = sorted(tasks, key=lambda x: (priority_order.get(x["priority"], 3), x["id"])) tasks_str = "\n".join( [ f"- [{task['status'].upper()}] {task['name']} (Priority: {task['priority']})" for task in tasks ] ) return f"Task list ({status_filter}):\n{tasks_str}" def clear_completed_tasks(run_context: RunContext) -> str: if run_context.session_state is None: run_context.session_state = {} if "task_list" not in run_context.session_state: run_context.session_state["task_list"] = [] return "Task list is empty." original_count = len(run_context.session_state["task_list"]) run_context.session_state["task_list"] = [ task for task in run_context.session_state["task_list"] if task["status"] != "completed" ] completed_count = original_count - len(run_context.session_state["task_list"]) return f"Removed {completed_count} completed tasks from the list." # --------------------------------------------------------------------------- # Create Agents (Task Routing) # --------------------------------------------------------------------------- task_manager = Agent( name="Task Manager", model=OpenAIChatLegacy(id="gpt-5.2"), tools=[add_task, complete_task, set_task_priority], instructions=[ "You are a task management specialist.", "You can add new tasks, mark tasks as completed, and update task priorities.", "Always use the provided tools to interact with the task list.", "When adding tasks, consider setting appropriate priorities based on urgency and importance.", "Be efficient and clear in your responses.", ], ) task_viewer = Agent( name="Task Viewer", model=OpenAIChatLegacy(id="gpt-5.2"), tools=[list_tasks], instructions=[ "You are a task viewing specialist.", "You can display tasks with various filters (all, pending, completed).", "Present task information in a clear, organized format.", "Help users understand their task status and priorities.", ], ) task_organizer = Agent( name="Task Organizer", model=OpenAIChatLegacy(id="gpt-5.2"), tools=[list_tasks, clear_completed_tasks, set_task_priority], instructions=[ "You are a task organization specialist.", "You can view tasks, clean up completed tasks, and reorganize priorities.", "Focus on helping users maintain an organized and efficient task list.", "Suggest improvements to task organization when appropriate.", ], ) # --------------------------------------------------------------------------- # Define Steps (Task Routing) # --------------------------------------------------------------------------- manage_tasks_step = Step( name="manage_tasks", description="Add new tasks, complete tasks, or update priorities", agent=task_manager, ) view_tasks_step = Step( name="view_tasks", description="View and display task lists with filtering", agent=task_viewer, ) organize_tasks_step = Step( name="organize_tasks", description="Organize tasks, clean up completed items, adjust priorities", agent=task_organizer, ) def task_router(step_input: StepInput) -> List[Step]: message = step_input.previous_step_content or step_input.input or "" message_lower = str(message).lower() management_keywords = [ "add", "create", "new task", "complete", "finish", "done", "mark as", "priority", "urgent", "important", "update", ] viewing_keywords = [ "show", "list", "display", "view", "see", "what tasks", "current", "pending", "completed", "status", ] organizing_keywords = [ "clean", "organize", "clear", "remove completed", "reorganize", "cleanup", "tidy", "sort", "arrange", ] if any(keyword in message_lower for keyword in organizing_keywords): print("[INFO] Organization request detected: Using Task Organizer") return [organize_tasks_step] if any(keyword in message_lower for keyword in management_keywords): print("[INFO] Management request detected: Using Task Manager") return [manage_tasks_step] if any(keyword in message_lower for keyword in viewing_keywords): print("[INFO] Viewing request detected: Using Task Viewer") return [view_tasks_step] print("[INFO] Ambiguous request: Defaulting to Task Manager") return [manage_tasks_step] # --------------------------------------------------------------------------- # Create Workflow (Task Routing) # --------------------------------------------------------------------------- task_workflow = Workflow( name="Smart Task Management Workflow", description="Intelligently routes task management requests to specialized agents", steps=[ Router( name="task_management_router", selector=task_router, choices=[manage_tasks_step, view_tasks_step, organize_tasks_step], description="Routes requests to the most appropriate task management agent", ) ], session_state={"task_list": []}, db=SqliteDb(db_file="tmp/workflow.db"), ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- def run_adaptive_assistant_example() -> None: queries = [ "Hello! I'm new here.", "How do I implement a binary search tree in Python?", "What's the best pizza topping?", "Explain quantum computing", ] for i, query in enumerate(queries, 1): print("\n" + "=" * 80) print(f"Interaction {i}: {query}") print("=" * 80) adaptive_assistant_workflow.print_response( input=query, session_id="user-456", user_id="user-456", stream=True, ) def run_task_workflow_example() -> None: print("=== Example 1: Adding Tasks ===") task_workflow.print_response( input="Add these tasks: 'Review project proposal' with high priority, 'Buy groceries' with low priority, and 'Call dentist' with medium priority." ) print("Workflow session state:", task_workflow.get_session_state()) print("\n=== Example 2: Viewing Tasks ===") task_workflow.print_response(input="Show me all my current tasks") print("Workflow session state:", task_workflow.get_session_state()) print("\n=== Example 3: Completing Tasks ===") task_workflow.print_response(input="Mark 'Buy groceries' as completed") print("Workflow session state:", task_workflow.get_session_state()) print("\n=== Example 4: Organizing Tasks ===") task_workflow.print_response( input="Clean up my completed tasks and show me what's left" ) print("Workflow session state:", task_workflow.get_session_state()) print("\n=== Example 5: Filtered View ===") task_workflow.print_response(input="Show me only my pending tasks") print("\nFinal workflow session state:", task_workflow.get_session_state()) if __name__ == "__main__": run_adaptive_assistant_example() run_task_workflow_example()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/session_state/state_in_router.py", "license": "Apache License 2.0", "lines": 387, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/session_state/state_with_agent.py
""" State With Agent ================ Demonstrates sharing mutable workflow session state across agent tool calls. """ from agno.agent.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai.chat import OpenAIChat from agno.run import RunContext from agno.workflow.step import Step from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Database # --------------------------------------------------------------------------- db = SqliteDb(db_file="tmp/workflow.db") # --------------------------------------------------------------------------- # Define Session-State Tools # --------------------------------------------------------------------------- def add_item(run_context: RunContext, item: str) -> str: if run_context.session_state is None: run_context.session_state = {} existing_items = [ existing_item.lower() for existing_item in run_context.session_state["shopping_list"] ] if item.lower() not in existing_items: run_context.session_state["shopping_list"].append(item) return f"Added '{item}' to the shopping list." return f"'{item}' is already in the shopping list." def remove_item(run_context: RunContext, item: str) -> str: if run_context.session_state is None: run_context.session_state = {} if len(run_context.session_state["shopping_list"]) == 0: return f"Shopping list is empty. Cannot remove '{item}'." shopping_list = run_context.session_state["shopping_list"] for i, existing_item in enumerate(shopping_list): if existing_item.lower() == item.lower(): removed_item = shopping_list.pop(i) return f"Removed '{removed_item}' from the shopping list." return f"'{item}' not found in the shopping list." def remove_all_items(run_context: RunContext) -> str: if run_context.session_state is None: run_context.session_state = {} run_context.session_state["shopping_list"] = [] return "Removed all items from the shopping list." def list_items(run_context: RunContext) -> str: if run_context.session_state is None: run_context.session_state = {} if len(run_context.session_state["shopping_list"]) == 0: return "Shopping list is empty." items = run_context.session_state["shopping_list"] items_str = "\n".join([f"- {item}" for item in items]) return f"Shopping list:\n{items_str}" # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- shopping_assistant = Agent( name="Shopping Assistant", model=OpenAIChat(id="gpt-5.2"), tools=[add_item, remove_item, list_items], instructions=[ "You are a helpful shopping assistant.", "You can help users manage their shopping list by adding, removing, and listing items.", "Always use the provided tools to interact with the shopping list.", "Be friendly and helpful in your responses.", ], ) list_manager = Agent( name="List Manager", model=OpenAIChat(id="gpt-5.2"), tools=[list_items, remove_all_items], instructions=[ "You are a list management specialist.", "You can view the current shopping list and clear it when needed.", "Always show the current list when asked.", "Confirm actions clearly to the user.", ], ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- manage_items_step = Step( name="manage_items", description="Help manage shopping list items (add/remove)", agent=shopping_assistant, ) view_list_step = Step( name="view_list", description="View and manage the complete shopping list", agent=list_manager, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- shopping_workflow = Workflow( name="Shopping List Workflow", db=db, steps=[manage_items_step, view_list_step], session_state={"shopping_list": []}, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("=== Example 1: Adding Items ===") shopping_workflow.print_response( input="Please add milk, bread, and eggs to my shopping list." ) print("Workflow session state:", shopping_workflow.get_session_state()) print("\n=== Example 2: Adding More Items ===") shopping_workflow.print_response( input="Add apples and bananas to the list, then show me the complete list." ) print("Workflow session state:", shopping_workflow.get_session_state()) print("\n=== Example 3: Removing Items ===") shopping_workflow.print_response( input="Remove bread from the list and show me what's left." ) print("Workflow session state:", shopping_workflow.get_session_state()) print("\n=== Example 4: Clearing List ===") shopping_workflow.print_response( input="Clear the entire shopping list and confirm it's empty." ) print("Final workflow session state:", shopping_workflow.get_session_state())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/session_state/state_with_agent.py", "license": "Apache License 2.0", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/session_state/state_with_team.py
""" State With Team =============== Demonstrates shared session state across team and agent steps for project-step lifecycle management. """ from agno.agent.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai.chat import OpenAIChat from agno.run import RunContext from agno.team.team import Team from agno.workflow.step import Step from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Database # --------------------------------------------------------------------------- db = SqliteDb(db_file="tmp/workflow.db") # --------------------------------------------------------------------------- # Define Team Tools # --------------------------------------------------------------------------- def add_step( run_context: RunContext, step_name: str, assignee: str, priority: str = "medium", ) -> str: if run_context.session_state is None: run_context.session_state = {} if "steps" not in run_context.session_state: run_context.session_state["steps"] = [] step = { "name": step_name, "assignee": assignee, "status": "pending", "priority": priority, "created_at": "now", } run_context.session_state["steps"].append(step) return f"[OK] Successfully added step '{step_name}' assigned to {assignee} (priority: {priority}). Total steps: {len(run_context.session_state['steps'])}" def delete_step(run_context: RunContext, step_name: str) -> str: if run_context.session_state is None or "steps" not in run_context.session_state: return "[ERROR] No steps found to delete" steps = run_context.session_state["steps"] for i, step in enumerate(steps): if step["name"] == step_name: deleted_step = steps.pop(i) return f"[OK] Successfully deleted step '{step_name}' (was assigned to {deleted_step['assignee']}). Remaining steps: {len(steps)}" return f"[ERROR] Step '{step_name}' not found in the list" # --------------------------------------------------------------------------- # Define Agent Tools # --------------------------------------------------------------------------- def update_step_status( run_context: RunContext, step_name: str, new_status: str, notes: str = "", ) -> str: if run_context.session_state is None or "steps" not in run_context.session_state: return "[ERROR] No steps found in workflow session state" steps = run_context.session_state["steps"] for step in steps: if step["name"] == step_name: old_status = step["status"] step["status"] = new_status if notes: step["notes"] = notes step["last_updated"] = "now" result = f"[OK] Updated step '{step_name}' status from '{old_status}' to '{new_status}'" if notes: result += f" with notes: {notes}" return result return f"[ERROR] Step '{step_name}' not found in the list" def assign_step(run_context: RunContext, step_name: str, new_assignee: str) -> str: if run_context.session_state is None or "steps" not in run_context.session_state: return "[ERROR] No steps found in workflow session state" steps = run_context.session_state["steps"] for step in steps: if step["name"] == step_name: old_assignee = step["assignee"] step["assignee"] = new_assignee step["last_updated"] = "now" return f"[OK] Reassigned step '{step_name}' from {old_assignee} to {new_assignee}" return f"[ERROR] Step '{step_name}' not found in the list" # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- step_manager = Agent( name="StepManager", model=OpenAIChat(id="gpt-5.2"), instructions=[ "You are a precise step manager. Your ONLY job is to use the provided tools.", "When asked to add a step: ALWAYS use add_step(step_name, assignee, priority).", "When asked to delete a step: ALWAYS use delete_step(step_name).", "Do NOT create imaginary steps or lists.", "Do NOT provide explanations beyond what the tool returns.", "Be direct and use the tools immediately.", ], ) step_coordinator = Agent( name="StepCoordinator", model=OpenAIChat(id="gpt-5.2"), instructions=[ "You coordinate with the StepManager to ensure tasks are completed.", "Support the team by confirming actions and helping with coordination.", "Be concise and focus on the specific request.", ], ) status_manager = Agent( name="StatusManager", model=OpenAIChat(id="gpt-5.2"), tools=[update_step_status, assign_step], instructions=[ "You manage step statuses and assignments using the provided tools.", "Use update_step_status(step_name, new_status, notes) to change step status.", "Use assign_step(step_name, new_assignee) to reassign steps.", "Valid statuses: 'pending', 'in_progress', 'completed', 'blocked', 'cancelled'.", "Be precise and only use the tools provided.", ], ) # --------------------------------------------------------------------------- # Create Team # --------------------------------------------------------------------------- management_team = Team( name="ManagementTeam", members=[step_manager, step_coordinator], tools=[add_step, delete_step], instructions=[ "You are a step management team that ONLY uses the provided tools for adding and deleting steps.", "CRITICAL: Use add_step(step_name, assignee, priority) to add steps.", "CRITICAL: Use delete_step(step_name) to delete steps.", "IMPORTANT: You do NOT handle status updates - that's handled by the status manager in the next step.", "IMPORTANT: Do NOT delete steps when asked to mark them as completed - only delete when explicitly asked to delete.", "If asked to mark a step as completed, respond that status updates are handled by the status manager.", "Do NOT create fictional content or step lists.", "Execute only the requested add/delete actions using tools and report the result.", ], ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- manage_steps_step = Step( name="manage_steps", description="Management team uses tools to add/delete steps in the workflow session state", team=management_team, ) update_status_step = Step( name="update_status", description="Status manager updates step statuses and assignments", agent=status_manager, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- project_workflow = Workflow( name="Project Management Workflow", db=db, steps=[manage_steps_step, update_status_step], session_state={"steps": []}, ) # --------------------------------------------------------------------------- # Helper # --------------------------------------------------------------------------- def print_current_steps(workflow) -> None: session_state = workflow.get_session_state() if not session_state or "steps" not in session_state: print("No steps in workflow") return steps = session_state["steps"] if not steps: print("Step list is empty") return print("Current Project Steps:") for i, step in enumerate(steps, 1): status_label = { "pending": "[PENDING]", "in_progress": "[IN_PROGRESS]", "completed": "[COMPLETED]", "blocked": "[BLOCKED]", "cancelled": "[CANCELLED]", }.get(step["status"], "[UNKNOWN]") priority_label = {"high": "[HIGH]", "medium": "[MEDIUM]", "low": "[LOW]"}.get( step.get("priority", "medium"), "[MEDIUM]", ) print( f" {i}. {status_label} {priority_label} {step['name']} (assigned to: {step['assignee']}, status: {step['status']})" ) if "notes" in step: print(f" Notes: {step['notes']}") print() # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("Starting Project Management Workflow Tests") print("=" * 60) print("Example 1: Add Multiple Steps") print("=" * 60) project_workflow.print_response( input="Add a high priority step called 'Setup Database' assigned to Alice, and a medium priority step called 'Create API' assigned to Bob" ) print_current_steps(project_workflow) print(f"Workflow Session State: {project_workflow.get_session_state()}") print() print("=" * 60) print("Example 2: Update Step Status") print("=" * 60) project_workflow.print_response( input="Mark 'Setup Database' as in_progress with notes 'Started database schema design'" ) print_current_steps(project_workflow) print(f"Workflow Session State: {project_workflow.get_session_state()}") print() print("=" * 60) print("Example 3: Reassign and Complete Step") print("=" * 60) project_workflow.print_response( input="Reassign 'Create API' to Charlie, then mark it as completed with notes 'API endpoints implemented and tested'" ) print_current_steps(project_workflow) print(f"Workflow Session State: {project_workflow.get_session_state()}") print() print("=" * 60) print("Example 4: Add and Manage More Steps") print("=" * 60) project_workflow.print_response( input="Add a low priority step 'Write Tests' assigned to Dave, then mark 'Setup Database' as completed" ) print_current_steps(project_workflow) print(f"Workflow Session State: {project_workflow.get_session_state()}") print() print("=" * 60) print("Example 5: Delete Step") print("=" * 60) project_workflow.print_response( input="Delete the 'Write Tests' step and add a high priority 'Deploy to Production' step assigned to Eve" ) print_current_steps(project_workflow) print(f"Workflow Session State: {project_workflow.get_session_state()}")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/session_state/state_with_team.py", "license": "Apache License 2.0", "lines": 238, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/structured_io/image_input.py
""" Image Input =========== Demonstrates passing image media into workflow runs and chaining analysis with follow-up research. """ from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.media import Image from agno.models.openai import OpenAIChat from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- image_analyzer = Agent( name="Image Analyzer", model=OpenAIChat(id="gpt-4o"), instructions="Analyze the provided image and extract key details, objects, and context.", ) news_researcher = Agent( name="News Researcher", model=OpenAIChat(id="gpt-4o"), tools=[WebSearchTools()], instructions="Search for latest news and information related to the analyzed image content.", ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- analysis_step = Step( name="Image Analysis Step", agent=image_analyzer, ) research_step = Step( name="News Research Step", agent=news_researcher, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- media_workflow = Workflow( name="Image Analysis and Research Workflow", description="Analyze an image and research related news", steps=[analysis_step, research_step], db=SqliteDb(session_table="workflow_session", db_file="tmp/workflow.db"), ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": media_workflow.print_response( input="Please analyze this image and find related news", images=[ Image( url="https://upload.wikimedia.org/wikipedia/commons/0/0c/GoldenGateBridge-001.jpg" ) ], markdown=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/structured_io/image_input.py", "license": "Apache License 2.0", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/structured_io/input_schema.py
""" Input Schema ============ Demonstrates workflow-level `input_schema` validation with structured and invalid input examples. """ from typing import List from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.team import Team from agno.tools.hackernews import HackerNewsTools from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step from agno.workflow.workflow import Workflow from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Define Input Models # --------------------------------------------------------------------------- class DifferentModel(BaseModel): name: str class ResearchTopic(BaseModel): topic: str focus_areas: List[str] = Field(description="Specific areas to focus on") target_audience: str = Field(description="Who this research is for") sources_required: int = Field(description="Number of sources needed", default=5) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- hackernews_agent = Agent( name="Hackernews Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[HackerNewsTools()], role="Extract key insights and content from Hackernews posts", ) web_agent = Agent( name="Web Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[WebSearchTools()], role="Search the web for the latest news and trends", ) content_planner = Agent( name="Content Planner", model=OpenAIChat(id="gpt-4o"), instructions=[ "Plan a content schedule over 4 weeks for the provided topic and research content", "Ensure that I have posts for 3 posts per week", ], ) # --------------------------------------------------------------------------- # Create Team # --------------------------------------------------------------------------- research_team = Team( name="Research Team", members=[hackernews_agent, web_agent], instructions="Research tech topics from Hackernews and the web", ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step( name="Research Step", team=research_team, ) content_planning_step = Step( name="Content Planning Step", agent=content_planner, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- content_creation_workflow = Workflow( name="Content Creation Workflow", description="Automated content creation from blog posts to social media", db=SqliteDb( session_table="workflow_session", db_file="tmp/workflow.db", ), steps=[research_step, content_planning_step], input_schema=ResearchTopic, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("=== Example: Research with Structured Topic ===") research_topic = ResearchTopic( topic="AI trends in 2024", focus_areas=[ "Machine Learning", "Natural Language Processing", "Computer Vision", "AI Ethics", ], target_audience="Tech professionals and business leaders", ) content_creation_workflow.print_response( input=research_topic, markdown=True, ) # Should fail, as some fields present in input schema are missing. # content_creation_workflow.print_response( # input=ResearchTopic( # topic="AI trends in 2024", # focus_areas=[ # "Machine Learning", # "Natural Language Processing", # "Computer Vision", # "AI Ethics", # ], # ), # markdown=True, # ) # Should fail, as it is not in sync with input schema. # content_creation_workflow.print_response( # input=DifferentModel(name="test"), # markdown=True, # ) # Pass a valid dict that matches ResearchTopic. # content_creation_workflow.print_response( # input={ # "topic": "AI trends in 2024", # "focus_areas": ["Machine Learning", "Computer Vision"], # "target_audience": "Tech professionals", # "sources_required": 8, # }, # markdown=True, # )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/structured_io/input_schema.py", "license": "Apache License 2.0", "lines": 127, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/structured_io/pydantic_input.py
""" Pydantic Input ============== Demonstrates passing a Pydantic model instance directly as workflow input. """ from typing import List from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.team import Team from agno.tools.hackernews import HackerNewsTools from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step from agno.workflow.workflow import Workflow from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Define Input Model # --------------------------------------------------------------------------- class ResearchTopic(BaseModel): topic: str focus_areas: List[str] = Field(description="Specific areas to focus on") target_audience: str = Field(description="Who this research is for") sources_required: int = Field(description="Number of sources needed", default=5) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- hackernews_agent = Agent( name="Hackernews Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[HackerNewsTools()], role="Extract key insights and content from Hackernews posts", ) web_agent = Agent( name="Web Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[WebSearchTools()], role="Search the web for the latest news and trends", ) content_planner = Agent( name="Content Planner", model=OpenAIChat(id="gpt-4o"), instructions=[ "Plan a content schedule over 4 weeks for the provided topic and research content", "Ensure that I have posts for 3 posts per week", ], ) # --------------------------------------------------------------------------- # Create Team # --------------------------------------------------------------------------- research_team = Team( name="Research Team", members=[hackernews_agent, web_agent], instructions="Research tech topics from Hackernews and the web", ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step( name="Research Step", team=research_team, ) content_planning_step = Step( name="Content Planning Step", agent=content_planner, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- content_creation_workflow = Workflow( name="Content Creation Workflow", description="Automated content creation from blog posts to social media", db=SqliteDb( session_table="workflow_session", db_file="tmp/workflow.db", ), steps=[research_step, content_planning_step], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("=== Example: Research with Structured Topic ===") research_topic = ResearchTopic( topic="AI trends in 2024", focus_areas=[ "Machine Learning", "Natural Language Processing", "Computer Vision", "AI Ethics", ], target_audience="Tech professionals and business leaders", sources_required=8, ) content_creation_workflow.print_response( input=research_topic, markdown=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/structured_io/pydantic_input.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/structured_io/structured_io_agent.py
""" Structured IO Agent =================== Demonstrates structured output schemas at each agent step in a multi-step workflow. """ from typing import List from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.hackernews import HackerNewsTools from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step from agno.workflow.workflow import Workflow from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Define Structured Models # --------------------------------------------------------------------------- class ResearchFindings(BaseModel): topic: str = Field(description="The research topic") key_insights: List[str] = Field(description="Main insights discovered", min_items=3) trending_technologies: List[str] = Field( description="Technologies that are trending", min_items=2, ) market_impact: str = Field(description="Potential market impact analysis") sources_count: int = Field(description="Number of sources researched") confidence_score: float = Field( description="Confidence in findings (0.0-1.0)", ge=0.0, le=1.0, ) class ContentStrategy(BaseModel): target_audience: str = Field(description="Primary target audience") content_pillars: List[str] = Field(description="Main content themes", min_items=3) posting_schedule: List[str] = Field(description="Recommended posting schedule") key_messages: List[str] = Field( description="Core messages to communicate", min_items=3, ) hashtags: List[str] = Field(description="Recommended hashtags", min_items=5) engagement_tactics: List[str] = Field( description="Ways to increase engagement", min_items=2, ) class FinalContentPlan(BaseModel): campaign_name: str = Field(description="Name for the content campaign") content_calendar: List[str] = Field( description="Specific content pieces planned", min_items=6, ) success_metrics: List[str] = Field( description="How to measure success", min_items=3, ) budget_estimate: str = Field(description="Estimated budget range") timeline: str = Field(description="Implementation timeline") risk_factors: List[str] = Field( description="Potential risks and mitigation", min_items=2, ) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- research_agent = Agent( name="AI Research Specialist", model=OpenAIChat(id="gpt-4o-mini"), tools=[HackerNewsTools(), WebSearchTools()], role="Research AI trends and extract structured insights", output_schema=ResearchFindings, instructions=[ "Research the given topic thoroughly using available tools", "Provide structured findings with confidence scores", "Focus on recent developments and market trends", "Make sure to structure your response according to the ResearchFindings model", ], ) strategy_agent = Agent( name="Content Strategy Expert", model=OpenAIChat(id="gpt-4o-mini"), role="Create content strategies based on research findings", output_schema=ContentStrategy, instructions=[ "Analyze the research findings provided from the previous step", "Create a comprehensive content strategy based on the structured research data", "Focus on audience engagement and brand building", "Structure your response according to the ContentStrategy model", ], ) planning_agent = Agent( name="Content Planning Specialist", model=OpenAIChat(id="gpt-4o"), role="Create detailed content plans and calendars", output_schema=FinalContentPlan, instructions=[ "Use the content strategy from the previous step to create a detailed implementation plan", "Include specific timelines and success metrics", "Consider budget and resource constraints", "Structure your response according to the FinalContentPlan model", ], ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step( name="research_insights", agent=research_agent, ) strategy_step = Step( name="content_strategy", agent=strategy_agent, ) planning_step = Step( name="final_planning", agent=planning_agent, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- structured_workflow = Workflow( name="Structured Content Creation Pipeline", description="AI-powered content creation with structured data flow", steps=[research_step, strategy_step, planning_step], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("=== Testing Structured Output Flow Between Steps ===") input_text = "Latest developments in artificial intelligence and machine learning" # Sync structured_workflow.print_response(input=input_text) # Sync Streaming structured_workflow.print_response( input=input_text, stream=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/structured_io/structured_io_agent.py", "license": "Apache License 2.0", "lines": 135, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/structured_io/structured_io_function.py
""" Structured IO Function ====================== Demonstrates custom function steps in structured workflows, including string and BaseModel outputs. """ from typing import List from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.hackernews import HackerNewsTools from agno.tools.websearch import WebSearchTools from agno.workflow.step import Step, StepInput, StepOutput from agno.workflow.workflow import Workflow from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Define Structured Models # --------------------------------------------------------------------------- class ResearchFindings(BaseModel): topic: str = Field(description="The research topic") key_insights: List[str] = Field(description="Main insights discovered", min_items=3) trending_technologies: List[str] = Field( description="Technologies that are trending", min_items=2, ) market_impact: str = Field(description="Potential market impact analysis") sources_count: int = Field(description="Number of sources researched") confidence_score: float = Field( description="Confidence in findings (0.0-1.0)", ge=0.0, le=1.0, ) class ContentStrategy(BaseModel): target_audience: str = Field(description="Primary target audience") content_pillars: List[str] = Field(description="Main content themes", min_items=3) posting_schedule: List[str] = Field(description="Recommended posting schedule") key_messages: List[str] = Field( description="Core messages to communicate", min_items=3, ) hashtags: List[str] = Field(description="Recommended hashtags", min_items=5) engagement_tactics: List[str] = Field( description="Ways to increase engagement", min_items=2, ) class AnalysisReport(BaseModel): analysis_type: str = Field(description="Type of analysis performed") input_data_type: str = Field(description="Type of input data received") structured_data_detected: bool = Field( description="Whether structured data was found" ) key_findings: List[str] = Field(description="Key findings from the analysis") recommendations: List[str] = Field(description="Recommendations for next steps") confidence_score: float = Field( description="Analysis confidence (0.0-1.0)", ge=0.0, le=1.0, ) data_quality_score: float = Field( description="Quality of input data (0.0-1.0)", ge=0.0, le=1.0, ) class FinalContentPlan(BaseModel): campaign_name: str = Field(description="Name for the content campaign") content_calendar: List[str] = Field( description="Specific content pieces planned", min_items=6, ) success_metrics: List[str] = Field( description="How to measure success", min_items=3, ) budget_estimate: str = Field(description="Estimated budget range") timeline: str = Field(description="Implementation timeline") risk_factors: List[str] = Field( description="Potential risks and mitigation", min_items=2, ) # --------------------------------------------------------------------------- # Define Function Executors # --------------------------------------------------------------------------- def data_analysis_function(step_input: StepInput) -> StepOutput: message = step_input.input previous_step_content = step_input.previous_step_content print("\n" + "=" * 60) print("CUSTOM FUNCTION DATA ANALYSIS") print("=" * 60) print(f"\nInput Message Type: {type(message)}") print(f"Input Message Value: {message}") print(f"\nPrevious Step Content Type: {type(previous_step_content)}") analysis_results = [] if previous_step_content: print("\nPrevious Step Content Preview:") print("Topic: ", previous_step_content.topic, "\n") print("Key Insights: ", previous_step_content.key_insights, "\n") print( "Trending Technologies: ", previous_step_content.trending_technologies, "\n" ) analysis_results.append("[PASS] Received structured data (BaseModel)") analysis_results.append( f"[PASS] BaseModel type: {type(previous_step_content).__name__}" ) try: model_dict = previous_step_content.model_dump() analysis_results.append(f"[PASS] Model fields: {list(model_dict.keys())}") if hasattr(previous_step_content, "topic"): analysis_results.append( f"[PASS] Research Topic: {previous_step_content.topic}" ) if hasattr(previous_step_content, "confidence_score"): analysis_results.append( f"[PASS] Confidence Score: {previous_step_content.confidence_score}" ) except Exception as e: analysis_results.append(f"[FAIL] Error accessing BaseModel: {e}") enhanced_analysis = f""" ## Data Flow Analysis Report **Input Analysis:** - Message Type: {type(message).__name__} - Previous Content Type: {type(previous_step_content).__name__} **Structure Analysis:** {chr(10).join(analysis_results)} **Recommendations for Next Step:** Based on the data analysis, the content planning step should receive this processed information. """.strip() print("\nAnalysis Results:") for result in analysis_results: print(f" {result}") print("=" * 60) return StepOutput(content=enhanced_analysis, success=True) def enhanced_analysis_function(step_input: StepInput) -> StepOutput: message = step_input.input previous_step_content = step_input.previous_step_content print("\n" + "=" * 60) print("ENHANCED CUSTOM FUNCTION WITH STRUCTURED OUTPUT") print("=" * 60) print(f"\nInput Message Type: {type(message)}") print(f"Input Message Value: {message}") print(f"\nPrevious Step Content Type: {type(previous_step_content)}") key_findings = [] recommendations = [] structured_data_detected = False confidence_score = 0.8 data_quality_score = 0.9 if previous_step_content: print("\nPrevious Step Content Analysis:") if isinstance(previous_step_content, ResearchFindings): structured_data_detected = True print("[PASS] Detected ResearchFindings BaseModel") print(f" Topic: {previous_step_content.topic}") print( f" Key Insights: {len(previous_step_content.key_insights)} insights" ) print(f" Confidence: {previous_step_content.confidence_score}") key_findings.extend( [ f"Research topic identified: {previous_step_content.topic}", f"Found {len(previous_step_content.key_insights)} key insights", f"Identified {len(previous_step_content.trending_technologies)} trending technologies", f"Research confidence level: {previous_step_content.confidence_score}", "Market impact assessment available", ] ) recommendations.extend( [ "Leverage high-confidence research findings for content strategy", "Focus on trending technologies identified in research", "Use market impact insights for audience targeting", "Build content around key insights with strong evidence", ] ) confidence_score = previous_step_content.confidence_score data_quality_score = 0.95 else: key_findings.append( "Received unstructured data - converted to string format" ) recommendations.append( "Consider implementing structured data models for better processing" ) confidence_score = 0.6 data_quality_score = 0.7 else: key_findings.append("No previous step content available") recommendations.append("Ensure data flow between steps is properly configured") confidence_score = 0.4 data_quality_score = 0.5 analysis_report = AnalysisReport( analysis_type="Structured Data Flow Analysis", input_data_type=type(previous_step_content).__name__, structured_data_detected=structured_data_detected, key_findings=key_findings, recommendations=recommendations, confidence_score=confidence_score, data_quality_score=data_quality_score, ) print("\nAnalysis Results (BaseModel):") print(f" Analysis Type: {analysis_report.analysis_type}") print(f" Structured Data: {analysis_report.structured_data_detected}") print(f" Confidence: {analysis_report.confidence_score}") print(f" Data Quality: {analysis_report.data_quality_score}") print("=" * 60) return StepOutput(content=analysis_report, success=True) def simple_data_processor(step_input: StepInput) -> StepOutput: print("\nSIMPLE DATA PROCESSOR") print(f"Previous step content type: {type(step_input.previous_step_content)}") if isinstance(step_input.previous_step_content, AnalysisReport): report = step_input.previous_step_content print(f"Processing analysis report with confidence: {report.confidence_score}") summary = { "processor": "simple_data_processor", "input_confidence": report.confidence_score, "input_quality": report.data_quality_score, "processed_findings": len(report.key_findings), "processed_recommendations": len(report.recommendations), "status": "processed_successfully", } return StepOutput(content=summary, success=True) return StepOutput( content="Unable to process - expected AnalysisReport", success=False ) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- research_agent = Agent( name="AI Research Specialist", model=OpenAIChat(id="gpt-4o-mini"), tools=[HackerNewsTools(), WebSearchTools()], role="Research AI trends and extract structured insights", output_schema=ResearchFindings, instructions=[ "Research the given topic thoroughly using available tools", "Provide structured findings with confidence scores", "Focus on recent developments and market trends", "Make sure to structure your response according to the ResearchFindings model", ], ) strategy_agent = Agent( name="Content Strategy Expert", model=OpenAIChat(id="gpt-4o-mini"), role="Create content strategies based on research findings", output_schema=ContentStrategy, instructions=[ "Analyze the research findings provided from the previous step", "Create a comprehensive content strategy based on the structured research data", "Focus on audience engagement and brand building", "Structure your response according to the ContentStrategy model", ], ) planning_agent = Agent( name="Content Planning Specialist", model=OpenAIChat(id="gpt-4o"), role="Create detailed content plans and calendars", output_schema=FinalContentPlan, instructions=[ "Use the content strategy from the previous step to create a detailed implementation plan", "Include specific timelines and success metrics", "Consider budget and resource constraints", "Structure your response according to the FinalContentPlan model", ], ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step( name="research_insights", agent=research_agent, ) analysis_step = Step( name="data_analysis", executor=data_analysis_function, ) strategy_step = Step( name="content_strategy", agent=strategy_agent, ) planning_step = Step( name="final_planning", agent=planning_agent, ) enhanced_analysis_step = Step( name="enhanced_analysis", executor=enhanced_analysis_function, ) processor_step = Step( name="data_processor", executor=simple_data_processor, ) # --------------------------------------------------------------------------- # Create Workflows # --------------------------------------------------------------------------- structured_workflow = Workflow( name="Structured Content Creation Pipeline with Analysis", description="AI-powered content creation with data flow analysis", steps=[research_step, analysis_step, strategy_step, planning_step], ) enhanced_workflow = Workflow( name="Enhanced Structured Content Creation Pipeline", description="AI-powered content creation with BaseModel outputs from custom functions", steps=[ research_step, enhanced_analysis_step, processor_step, strategy_step, planning_step, ], ) # --------------------------------------------------------------------------- # Run Workflows # --------------------------------------------------------------------------- if __name__ == "__main__": print("=== Testing Structured Output Flow with Custom Function Analysis ===") structured_workflow.print_response( input="Latest developments in artificial intelligence and machine learning", ) print("\n=== Testing Enhanced Structured Output from Custom Function ===") enhanced_workflow.print_response( input="Latest developments in artificial intelligence and machine learning", stream=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/structured_io/structured_io_function.py", "license": "Apache License 2.0", "lines": 319, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/structured_io/structured_io_team.py
""" Structured IO Team ================== Demonstrates structured output schemas at each team step in a multi-step workflow. """ from typing import List from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.team import Team from agno.tools.hackernews import HackerNewsTools from agno.workflow.step import Step from agno.workflow.workflow import Workflow from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Define Structured Models # --------------------------------------------------------------------------- class ResearchFindings(BaseModel): topic: str = Field(description="The research topic") key_insights: List[str] = Field(description="Main insights discovered", min_items=3) trending_technologies: List[str] = Field( description="Technologies that are trending", min_items=2, ) market_impact: str = Field(description="Potential market impact analysis") sources_count: int = Field(description="Number of sources researched") confidence_score: float = Field( description="Confidence in findings (0.0-1.0)", ge=0.0, le=1.0, ) class ContentStrategy(BaseModel): target_audience: str = Field(description="Primary target audience") content_pillars: List[str] = Field(description="Main content themes", min_items=3) posting_schedule: List[str] = Field(description="Recommended posting schedule") key_messages: List[str] = Field( description="Core messages to communicate", min_items=3, ) hashtags: List[str] = Field(description="Recommended hashtags", min_items=5) engagement_tactics: List[str] = Field( description="Ways to increase engagement", min_items=2, ) class FinalContentPlan(BaseModel): campaign_name: str = Field(description="Name for the content campaign") content_calendar: List[str] = Field( description="Specific content pieces planned", min_items=6, ) success_metrics: List[str] = Field( description="How to measure success", min_items=3, ) budget_estimate: str = Field(description="Estimated budget range") timeline: str = Field(description="Implementation timeline") risk_factors: List[str] = Field( description="Potential risks and mitigation", min_items=2, ) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- research_specialist = Agent( name="Research Specialist", model=OpenAIChat(id="gpt-5.2"), tools=[HackerNewsTools()], role="Find and analyze the latest AI trends and developments", instructions=[ "Search for recent AI developments using available tools", "Focus on breakthrough technologies and market trends", "Provide detailed analysis with credible sources", ], ) data_analyst = Agent( name="Data Analyst", model=OpenAIChat(id="gpt-5.2"), role="Analyze research data and extract key insights", instructions=[ "Process research findings to identify patterns", "Quantify market impact and confidence levels", "Structure insights for strategic planning", ], ) content_strategist = Agent( name="Content Strategist", model=OpenAIChat(id="gpt-5.2"), role="Develop content strategies based on research insights", instructions=[ "Create comprehensive content strategies", "Focus on audience targeting and engagement", "Recommend optimal posting schedules and content pillars", ], ) marketing_expert = Agent( name="Marketing Expert", model=OpenAIChat(id="gpt-5.2"), role="Provide marketing insights and hashtag recommendations", instructions=[ "Suggest effective hashtags and engagement tactics", "Analyze target audience preferences", "Recommend proven marketing strategies", ], ) project_manager = Agent( name="Project Manager", model=OpenAIChat(id="gpt-4o"), role="Create detailed project plans and timelines", instructions=[ "Develop comprehensive implementation plans", "Set realistic timelines and budget estimates", "Identify potential risks and mitigation strategies", ], ) budget_analyst = Agent( name="Budget Analyst", model=OpenAIChat(id="gpt-4o"), role="Analyze costs and provide budget recommendations", instructions=[ "Estimate project costs and resource requirements", "Provide budget ranges and cost optimization suggestions", "Consider ROI and success metrics", ], ) # --------------------------------------------------------------------------- # Create Teams # --------------------------------------------------------------------------- research_team = Team( name="AI Research Team", members=[research_specialist, data_analyst], delegate_to_all_members=True, model=OpenAIChat(id="gpt-4o"), description="A collaborative team that researches AI trends and extracts structured insights", output_schema=ResearchFindings, instructions=[ "Work together to research the given topic thoroughly", "Combine research findings with data analysis", "Provide structured findings with confidence scores", "Focus on recent developments and market trends", ], ) strategy_team = Team( name="Content Strategy Team", members=[content_strategist, marketing_expert], delegate_to_all_members=True, model=OpenAIChat(id="gpt-4o"), description="A strategic team that creates comprehensive content strategies", output_schema=ContentStrategy, instructions=[ "Analyze the research findings from the previous step", "Collaborate to create a comprehensive content strategy", "Focus on audience engagement and brand building", "Combine content strategy with marketing expertise", ], ) planning_team = Team( name="Content Planning Team", members=[project_manager, budget_analyst], delegate_to_all_members=True, model=OpenAIChat(id="gpt-4o"), description="A planning team that creates detailed implementation plans", output_schema=FinalContentPlan, instructions=[ "Use the content strategy to create a detailed implementation plan", "Combine project management with budget analysis", "Include specific timelines and success metrics", "Consider budget and resource constraints", ], ) # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- research_step = Step( name="Research Insights", team=research_team, ) strategy_step = Step( name="Content Strategy", team=strategy_team, ) planning_step = Step( name="Final Planning", team=planning_team, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- structured_workflow = Workflow( name="Team-Based Structured Content Creation Pipeline", description="AI-powered content creation with teams and structured data flow", steps=[research_step, strategy_step, planning_step], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("=== Testing Structured Output Flow Between Teams ===") structured_workflow.print_response( input="Latest developments in artificial intelligence and machine learning", ) structured_workflow.print_response( input="Latest developments in artificial intelligence and machine learning", stream=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/structured_io/structured_io_team.py", "license": "Apache License 2.0", "lines": 203, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/tools/workflow_tools.py
""" Workflow Tools ============== Demonstrates exposing a workflow as a tool that another agent can execute. """ import asyncio from textwrap import dedent from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.team import Team from agno.tools.hackernews import HackerNewsTools from agno.tools.websearch import WebSearchTools from agno.tools.workflow import WorkflowTools from agno.workflow.types import StepInput, StepOutput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Define Few-Shot Guidance # --------------------------------------------------------------------------- FEW_SHOT_EXAMPLES = dedent( """\ You can refer to the examples below as guidance for how to use each tool. ### Examples #### Example: Blog Post Workflow User: Please create a blog post on the topic: AI Trends in 2024 Run: input_data="AI trends in 2024", additional_data={"topic": "AI, AI agents, AI workflows", "style": "The blog post should be written in a style that is easy to understand and follow."} Final Answer: I've created a blog post on the topic: AI trends in 2024 through the workflow. The blog post shows... You HAVE TO USE additional_data to pass the topic and style to the workflow. """ ) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- web_agent = Agent( name="Web Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[WebSearchTools()], role="Search the web for the latest news and trends", ) hackernews_agent = Agent( name="Hackernews Agent", model=OpenAIChat(id="gpt-4o-mini"), tools=[HackerNewsTools()], role="Extract key insights and content from Hackernews posts", ) writer_agent = Agent( name="Writer Agent", model=OpenAIChat(id="gpt-4o-mini"), instructions="Write a blog post on the topic", ) # --------------------------------------------------------------------------- # Define Function Steps # --------------------------------------------------------------------------- def prepare_input_for_web_search(step_input: StepInput) -> StepOutput: title = step_input.input topic = step_input.additional_data.get("topic") return StepOutput( content=dedent( f"""\ I'm writing a blog post with the title: {title} <topic> {topic} </topic> Search the web for atleast 10 articles\ """ ) ) def prepare_input_for_writer(step_input: StepInput) -> StepOutput: title = step_input.additional_data.get("title") topic = step_input.additional_data.get("topic") style = step_input.additional_data.get("style") research_team_output = step_input.previous_step_content return StepOutput( content=dedent( f"""\ I'm writing a blog post with the title: {title} <required_style> {style} </required_style> <topic> {topic} </topic> Here is information from the web: <research_results> {research_team_output} <research_results>\ """ ) ) # --------------------------------------------------------------------------- # Create Team # --------------------------------------------------------------------------- research_team = Team( name="Research Team", members=[hackernews_agent, web_agent], instructions="Research tech topics from Hackernews and the web", ) # --------------------------------------------------------------------------- # Create Workflow And Tool Wrapper # --------------------------------------------------------------------------- content_creation_workflow = Workflow( name="Blog Post Workflow", description="Automated blog post creation from Hackernews and the web", db=SqliteDb(session_table="workflow_session", db_file="tmp/workflow.db"), steps=[ prepare_input_for_web_search, research_team, prepare_input_for_writer, writer_agent, ], ) workflow_tools = WorkflowTools( workflow=content_creation_workflow, add_few_shot=True, few_shot_examples=FEW_SHOT_EXAMPLES, async_mode=True, ) agent = Agent( model=OpenAIChat(id="gpt-5-mini"), tools=[workflow_tools], markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": asyncio.run( agent.aprint_response( "Create a blog post with the following title: Quantum Computing in 2025", instructions="When you run the workflow using the `run_workflow` tool, remember to pass `additional_data` as a dictionary of key-value pairs.", markdown=True, stream=True, debug_mode=True, ) )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/tools/workflow_tools.py", "license": "Apache License 2.0", "lines": 135, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/workflow_agent/basic_workflow_agent.py
""" Basic Workflow Agent ==================== Demonstrates using `WorkflowAgent` to decide when to execute workflow steps versus answer from history. """ import asyncio from agno.agent import Agent from agno.db.postgres import PostgresDb from agno.models.openai import OpenAIChat from agno.workflow import WorkflowAgent from agno.workflow.types import StepInput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" story_writer = Agent( model=OpenAIChat(id="gpt-5.2"), instructions="You are tasked with writing a 100 word story based on a given topic", ) story_formatter = Agent( model=OpenAIChat(id="gpt-5.2"), instructions="You are tasked with breaking down a short story in prelogues, body and epilogue", ) # --------------------------------------------------------------------------- # Define Function Step # --------------------------------------------------------------------------- def add_references(step_input: StepInput): previous_output = step_input.previous_step_content if isinstance(previous_output, str): return previous_output + "\n\nReferences: https://www.agno.com" # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow_agent = WorkflowAgent(model=OpenAIChat(id="gpt-5.2"), num_history_runs=4) workflow = Workflow( name="Story Generation Workflow", description="A workflow that generates stories, formats them, and adds references", agent=workflow_agent, steps=[story_writer, story_formatter, add_references], db=PostgresDb(db_url), ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- async def run_async_examples() -> None: print("\n" + "=" * 80) print("FIRST CALL (ASYNC): Tell me a story about a husky named Max") print("=" * 80) await workflow.aprint_response("Tell me a story about a husky named Max") print("\n" + "=" * 80) print("SECOND CALL (ASYNC): What was Max like?") print("=" * 80) await workflow.aprint_response("What was Max like?") print("\n" + "=" * 80) print("THIRD CALL (ASYNC): Now tell me about a cat named Luna") print("=" * 80) await workflow.aprint_response("Now tell me about a cat named Luna") print("\n" + "=" * 80) print("FOURTH CALL (ASYNC): Compare Max and Luna") print("=" * 80) await workflow.aprint_response("Compare Max and Luna") async def run_async_streaming_examples() -> None: print("\n" + "=" * 80) print("FIRST CALL (ASYNC STREAMING): Tell me a story about a dog named Rocky") print("=" * 80) await workflow.aprint_response( "Tell me a story about a dog named Rocky", stream=True, ) print("\n" + "=" * 80) print("SECOND CALL (ASYNC STREAMING): What was Rocky's personality?") print("=" * 80) await workflow.aprint_response("What was Rocky's personality?", stream=True) print("\n" + "=" * 80) print("THIRD CALL (ASYNC STREAMING): Now tell me a story about a cat named Luna") print("=" * 80) await workflow.aprint_response( "Now tell me a story about a cat named Luna", stream=True, ) print("\n" + "=" * 80) print("FOURTH CALL (ASYNC STREAMING): Compare Rocky and Luna") print("=" * 80) await workflow.aprint_response("Compare Rocky and Luna", stream=True) if __name__ == "__main__": print("\n" + "=" * 80) print("FIRST CALL: Tell me a story about a husky named Max") print("=" * 80) workflow.print_response("Tell me a story about a husky named Max") print("\n" + "=" * 80) print("SECOND CALL: What was Max like?") print("=" * 80) workflow.print_response("What was Max like?") print("\n" + "=" * 80) print("THIRD CALL: Now tell me about a cat named Luna") print("=" * 80) workflow.print_response("Now tell me about a cat named Luna") print("\n" + "=" * 80) print("FOURTH CALL: Compare Max and Luna") print("=" * 80) workflow.print_response("Compare Max and Luna") print("\n\n" + "=" * 80) print("STREAMING MODE EXAMPLES") print("=" * 80) print("\n" + "=" * 80) print("FIRST CALL (STREAMING): Tell me a story about a dog named Rocky") print("=" * 80) workflow.print_response("Tell me a story about a dog named Rocky", stream=True) print("\n" + "=" * 80) print("SECOND CALL (STREAMING): What was Rocky's personality?") print("=" * 80) workflow.print_response("What was Rocky's personality?", stream=True) print("\n" + "=" * 80) print("THIRD CALL (STREAMING): Now tell me a story about a cat named Luna") print("=" * 80) workflow.print_response("Now tell me about a cat named Luna", stream=True) print("\n" + "=" * 80) print("FOURTH CALL (STREAMING): Compare Rocky and Luna") print("=" * 80) workflow.print_response("Compare Rocky and Luna", stream=True) asyncio.run(run_async_examples()) asyncio.run(run_async_streaming_examples())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/workflow_agent/basic_workflow_agent.py", "license": "Apache License 2.0", "lines": 123, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/06_advanced_concepts/workflow_agent/workflow_agent_with_condition.py
""" Workflow Agent With Condition ============================= Demonstrates using `WorkflowAgent` together with a conditional step in the workflow graph. """ import asyncio from agno.agent import Agent from agno.db.postgres import PostgresDb from agno.models.openai import OpenAIChat from agno.workflow import WorkflowAgent from agno.workflow.condition import Condition from agno.workflow.step import Step from agno.workflow.types import StepInput from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" story_writer = Agent( name="Story Writer", model=OpenAIChat(id="gpt-5.2"), instructions="You are tasked with writing a 100 word story based on a given topic", ) story_editor = Agent( name="Story Editor", model=OpenAIChat(id="gpt-5.2"), instructions="Review and improve the story's grammar, flow, and clarity", ) story_formatter = Agent( name="Story Formatter", model=OpenAIChat(id="gpt-5.2"), instructions="Break down the story into prologue, body, and epilogue sections", ) # --------------------------------------------------------------------------- # Define Functions # --------------------------------------------------------------------------- def needs_editing(step_input: StepInput) -> bool: story = step_input.previous_step_content or "" word_count = len(story.split()) return word_count > 50 or any(punct in story for punct in ["!", "?", ";", ":"]) def add_references(step_input: StepInput): previous_output = step_input.previous_step_content if isinstance(previous_output, str): return previous_output + "\n\nReferences: https://www.agno.com" # --------------------------------------------------------------------------- # Define Steps # --------------------------------------------------------------------------- write_step = Step( name="write_story", description="Write initial story", agent=story_writer, ) edit_step = Step( name="edit_story", description="Edit and improve the story", agent=story_editor, ) format_step = Step( name="format_story", description="Format the story into sections", agent=story_formatter, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow_agent = WorkflowAgent(model=OpenAIChat(id="gpt-5.2"), num_history_runs=4) workflow = Workflow( name="Story Generation with Conditional Editing", description="A workflow that generates stories, conditionally edits them, formats them, and adds references", agent=workflow_agent, steps=[ write_step, Condition( name="editing_condition", description="Check if story needs editing", evaluator=needs_editing, steps=[edit_step], ), format_step, add_references, ], db=PostgresDb(db_url), ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- async def main() -> None: print("\n" + "=" * 80) print("WORKFLOW WITH CONDITION - ASYNC STREAMING") print("=" * 80) print("\n" + "=" * 80) print("FIRST CALL: Tell me a story about a brave knight") print("=" * 80) await workflow.aprint_response( "Tell me a story about a brave knight", stream=True, ) print("\n" + "=" * 80) print("SECOND CALL: What was the knight's name?") print("=" * 80) await workflow.aprint_response( "What was the knight's name?", stream=True, ) print("\n" + "=" * 80) print("THIRD CALL: Now tell me about a cat") print("=" * 80) await workflow.aprint_response( "Now tell me about a cat", stream=True, ) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/06_advanced_concepts/workflow_agent/workflow_agent_with_condition.py", "license": "Apache License 2.0", "lines": 113, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/condition/cel_additional_data.py
"""Condition with CEL expression: branching on additional_data. ============================================================ Uses additional_data.priority to route high-priority requests to a specialized agent. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Condition, Step, Workflow # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- high_priority_agent = Agent( name="High Priority Agent", model=OpenAIChat(id="gpt-4o-mini"), instructions="You handle high-priority tasks. Be thorough and detailed.", markdown=True, ) low_priority_agent = Agent( name="Low Priority Agent", model=OpenAIChat(id="gpt-4o-mini"), instructions="You handle standard tasks. Be helpful and concise.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Priority Routing", steps=[ Condition( name="Priority Gate", evaluator="additional_data.priority > 5", steps=[ Step(name="High Priority", agent=high_priority_agent), ], else_steps=[ Step(name="Low Priority", agent=low_priority_agent), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("--- High priority (8) ---") workflow.print_response( input="Review this critical security report.", additional_data={"priority": 8}, ) print() print("--- Low priority (2) ---") workflow.print_response( input="Update the FAQ page.", additional_data={"priority": 2}, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/condition/cel_additional_data.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/condition/cel_basic.py
"""Condition with CEL expression: route based on input content. ============================================================ Uses input.contains() to check whether the request is urgent, branching to different agents via if/else steps. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Condition, Step, Workflow # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- urgent_handler = Agent( name="Urgent Handler", model=OpenAIChat(id="gpt-4o-mini"), instructions="You handle urgent requests with high priority. Be concise and action-oriented.", markdown=True, ) normal_handler = Agent( name="Normal Handler", model=OpenAIChat(id="gpt-4o-mini"), instructions="You handle normal requests thoroughly and thoughtfully.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Input Routing", steps=[ Condition( name="Urgent Check", evaluator='input.contains("urgent")', steps=[ Step(name="Handle Urgent", agent=urgent_handler), ], else_steps=[ Step(name="Handle Normal", agent=normal_handler), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("--- Urgent request ---") workflow.print_response( input="This is an urgent request - please help immediately!" ) print() print("--- Normal request ---") workflow.print_response(input="I have a general question about your services.")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/condition/cel_basic.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/condition/cel_previous_step.py
"""Condition with CEL expression: branching on previous step output. ================================================================= Runs a classifier step first, then uses previous_step_content.contains() to decide the next step. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Condition, Step, Workflow # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- classifier = Agent( name="Classifier", model=OpenAIChat(id="gpt-4o-mini"), instructions=( "Classify the request as either TECHNICAL or GENERAL. " "Respond with exactly one word: TECHNICAL or GENERAL." ), markdown=False, ) technical_agent = Agent( name="Technical Support", model=OpenAIChat(id="gpt-4o-mini"), instructions="You are a technical support specialist. Provide detailed technical help.", markdown=True, ) general_agent = Agent( name="General Support", model=OpenAIChat(id="gpt-4o-mini"), instructions="You handle general inquiries. Be friendly and helpful.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Classify and Route", steps=[ Step(name="Classify", agent=classifier), Condition( name="Route by Classification", evaluator='previous_step_content.contains("TECHNICAL")', steps=[ Step(name="Technical Help", agent=technical_agent), ], else_steps=[ Step(name="General Help", agent=general_agent), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("--- Technical question ---") workflow.print_response( input="My API returns 500 errors when I send POST requests with JSON payloads." ) print() print("--- General question ---") workflow.print_response(input="What are your business hours?")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/condition/cel_previous_step.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/condition/cel_previous_step_outputs.py
"""Condition with CEL: branch based on a named step's output. ========================================================== Uses previous_step_outputs map to check the output of a specific step by name, enabling multi-step pipelines with conditional logic. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Condition, Step, Workflow # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- researcher = Agent( name="Researcher", model=OpenAIChat(id="gpt-4o-mini"), instructions="Research the topic. If the topic involves safety risks, include SAFETY_REVIEW_NEEDED in your response.", markdown=True, ) safety_reviewer = Agent( name="Safety Reviewer", model=OpenAIChat(id="gpt-4o-mini"), instructions="Review the research for safety concerns and provide recommendations.", markdown=True, ) publisher = Agent( name="Publisher", model=OpenAIChat(id="gpt-4o-mini"), instructions="Prepare the research for publication.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Previous Step Outputs Condition", steps=[ Step(name="Research", agent=researcher), Condition( name="Safety Check", # Check the Research step output by name evaluator='previous_step_outputs.Research.contains("SAFETY_REVIEW_NEEDED")', steps=[ Step(name="Safety Review", agent=safety_reviewer), ], ), Step(name="Publish", agent=publisher), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("--- Safe topic (skips safety review) ---") workflow.print_response(input="Write about gardening tips for beginners.") print() print("--- Safety-sensitive topic (triggers safety review) ---") workflow.print_response( input="Write about handling hazardous chemicals in a home lab." )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/condition/cel_previous_step_outputs.py", "license": "Apache License 2.0", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/condition/cel_session_state.py
"""Condition with CEL expression: branching on session_state. ========================================================== Uses session_state.retry_count to implement retry logic. Runs the workflow multiple times to show the counter incrementing and eventually hitting the max retries branch. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import ( CEL_AVAILABLE, Condition, Step, StepInput, StepOutput, Workflow, ) # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Define Helpers # --------------------------------------------------------------------------- def increment_retry_count(step_input: StepInput, session_state: dict) -> StepOutput: """Increment retry count in session state.""" current_count = session_state.get("retry_count", 0) session_state["retry_count"] = current_count + 1 return StepOutput( content=f"Retry count incremented to {session_state['retry_count']}", success=True, ) def reset_retry_count(step_input: StepInput, session_state: dict) -> StepOutput: """Reset retry count in session state.""" session_state["retry_count"] = 0 return StepOutput(content="Retry count reset to 0", success=True) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- retry_agent = Agent( name="Retry Handler", model=OpenAIChat(id="gpt-4o-mini"), instructions="You are handling a retry attempt. Acknowledge this is a retry and try a different approach.", markdown=True, ) max_retries_agent = Agent( name="Max Retries Handler", model=OpenAIChat(id="gpt-4o-mini"), instructions="Maximum retries reached. Provide a helpful fallback response and suggest alternatives.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Retry Logic", steps=[ Step(name="Increment Retry", executor=increment_retry_count), Condition( name="Retry Check", evaluator="session_state.retry_count <= 3", steps=[ Step(name="Attempt Retry", agent=retry_agent), ], else_steps=[ Step(name="Max Retries Reached", agent=max_retries_agent), Step(name="Reset Counter", executor=reset_retry_count), ], ), ], session_state={"retry_count": 0}, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": for attempt in range(1, 6): print(f"--- Attempt {attempt} ---") workflow.print_response( input=f"Process request (attempt {attempt})", stream=True, ) print()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/condition/cel_session_state.py", "license": "Apache License 2.0", "lines": 86, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/loop/cel_compound_exit.py
"""Loop with CEL end condition: compound exit condition. ===================================================== Combines all_success and current_iteration to stop when both conditions are met: all steps succeeded AND enough iterations ran. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Loop, Step, Workflow # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- researcher = Agent( name="Researcher", model=OpenAIChat(id="gpt-4o-mini"), instructions="Research the given topic and provide detailed findings.", markdown=True, ) reviewer = Agent( name="Reviewer", model=OpenAIChat(id="gpt-4o-mini"), instructions="Review the research for completeness and accuracy.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Compound Exit Loop", steps=[ Loop( name="Research Loop", max_iterations=5, end_condition="all_success && current_iteration >= 2", steps=[ Step(name="Research", agent=researcher), Step(name="Review", agent=reviewer), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("Loop with CEL end condition: all_success && current_iteration >= 2") print("=" * 60) workflow.print_response( input="Research the impact of AI on healthcare", stream=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/loop/cel_compound_exit.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/loop/cel_content_keyword.py
"""Loop with CEL end condition: stop when agent signals completion. ================================================================ Uses last_step_content.contains() to detect a keyword in the output that signals the loop should stop. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Loop, Step, Workflow # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- editor = Agent( name="Editor", model=OpenAIChat(id="gpt-4o-mini"), instructions=( "Edit and refine the text. When the text is polished and ready, " "include the word DONE at the end of your response." ), markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Content Keyword Loop", steps=[ Loop( name="Editing Loop", max_iterations=5, end_condition='last_step_content.contains("DONE")', steps=[ Step(name="Edit", agent=editor), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print('Loop with CEL end condition: last_step_content.contains("DONE")') print("=" * 60) workflow.print_response( input="Refine this draft: AI is changing the world in many ways.", stream=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/loop/cel_content_keyword.py", "license": "Apache License 2.0", "lines": 54, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/loop/cel_iteration_limit.py
"""Loop with CEL end condition: stop after N iterations. ===================================================== Uses current_iteration to stop after a specific number of iterations, independent of max_iterations. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Loop, Step, Workflow # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- writer = Agent( name="Writer", model=OpenAIChat(id="gpt-4o-mini"), instructions="Write a short paragraph expanding on the topic. Build on previous content.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Iteration Limit Loop", steps=[ Loop( name="Writing Loop", max_iterations=10, # Stop after 2 iterations even though max is 10 end_condition="current_iteration >= 2", steps=[ Step(name="Write", agent=writer), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("Loop with CEL end condition: current_iteration >= 2 (max_iterations=10)") print("=" * 60) workflow.print_response( input="Write about the history of the internet", stream=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/loop/cel_iteration_limit.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/loop/cel_step_outputs_check.py
"""Loop with CEL end condition: check a named step's output. ========================================================= Uses step_outputs map to access a specific step by name and check its content before deciding to stop the loop. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Loop, Step, Workflow # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- researcher = Agent( name="Researcher", model=OpenAIChat(id="gpt-4o-mini"), instructions="Research the given topic.", markdown=True, ) reviewer = Agent( name="Reviewer", model=OpenAIChat(id="gpt-4o-mini"), instructions=( "Review the research. If the research is thorough and complete, " "include APPROVED in your response." ), markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Step Outputs Check Loop", steps=[ Loop( name="Research Loop", max_iterations=5, # Stop when the Reviewer step approves the research end_condition='step_outputs.Review.contains("APPROVED")', steps=[ Step(name="Research", agent=researcher), Step(name="Review", agent=reviewer), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print('Loop with CEL end condition: step_outputs.Review.contains("APPROVED")') print("=" * 60) workflow.print_response( input="Research renewable energy trends", stream=True, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/loop/cel_step_outputs_check.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/router/cel_additional_data_route.py
"""Router with CEL expression: route from additional_data field. ============================================================= Uses additional_data.route to let the caller specify which step to run, useful when the routing decision is made upstream (e.g. UI). Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Step, Workflow from agno.workflow.router import Router # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- email_agent = Agent( name="Email Writer", model=OpenAIChat(id="gpt-4o-mini"), instructions="You write professional emails. Be concise and polished.", markdown=True, ) blog_agent = Agent( name="Blog Writer", model=OpenAIChat(id="gpt-4o-mini"), instructions="You write engaging blog posts with clear structure and headings.", markdown=True, ) tweet_agent = Agent( name="Tweet Writer", model=OpenAIChat(id="gpt-4o-mini"), instructions="You write punchy tweets. Keep it under 280 characters.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Additional Data Router", steps=[ Router( name="Content Format Router", selector="additional_data.route", choices=[ Step(name="Email Writer", agent=email_agent), Step(name="Blog Writer", agent=blog_agent), Step(name="Tweet Writer", agent=tweet_agent), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("--- Route to email ---") workflow.print_response( input="Write about our new product launch.", additional_data={"route": "Email Writer"}, ) print() print("--- Route to tweet ---") workflow.print_response( input="Write about our new product launch.", additional_data={"route": "Tweet Writer"}, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/router/cel_additional_data_route.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/router/cel_session_state_route.py
"""Router with CEL expression: route from session_state. ===================================================== Uses session_state.preferred_handler to persist routing preferences across workflow runs. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Step, Workflow from agno.workflow.router import Router # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- detailed_agent = Agent( name="Detailed Analyst", model=OpenAIChat(id="gpt-4o-mini"), instructions="You provide detailed, in-depth analysis with examples and data.", markdown=True, ) brief_agent = Agent( name="Brief Analyst", model=OpenAIChat(id="gpt-4o-mini"), instructions="You provide brief, executive-summary style analysis. Keep it short.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Session State Router", steps=[ Router( name="Analysis Style Router", selector="session_state.preferred_handler", choices=[ Step(name="Detailed Analyst", agent=detailed_agent), Step(name="Brief Analyst", agent=brief_agent), ], ), ], session_state={"preferred_handler": "Brief Analyst"}, ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("--- Using session_state preference: Brief Analyst ---") workflow.print_response(input="Analyze the current state of cloud computing.") print() # Change preference workflow.session_state["preferred_handler"] = "Detailed Analyst" print("--- Changed preference to: Detailed Analyst ---") workflow.print_response(input="Analyze the current state of cloud computing.")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/router/cel_session_state_route.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/router/cel_ternary.py
"""Router with CEL expression: ternary operator on input content. ============================================================== Uses a CEL ternary to pick between two steps based on whether the input mentions "video" or not. Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Step, Workflow from agno.workflow.router import Router # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- video_agent = Agent( name="Video Specialist", model=OpenAIChat(id="gpt-4o-mini"), instructions="You specialize in video content creation and editing advice.", markdown=True, ) image_agent = Agent( name="Image Specialist", model=OpenAIChat(id="gpt-4o-mini"), instructions="You specialize in image design, photography, and visual content.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Ternary Router", steps=[ Router( name="Media Router", selector='input.contains("video") ? "Video Handler" : "Image Handler"', choices=[ Step(name="Video Handler", agent=video_agent), Step(name="Image Handler", agent=image_agent), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("--- Video request ---") workflow.print_response(input="How do I edit a video for YouTube?") print() print("--- Image request ---") workflow.print_response(input="Help me design a logo for my startup.")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/router/cel_ternary.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/04_workflows/07_cel_expressions/router/cel_using_step_choices.py
"""Router with CEL: route using step_choices index. ================================================ Uses step_choices[0], step_choices[1], etc. to reference steps by their position in the choices list, rather than hardcoding step names. This is useful when you want to: - Avoid typos in step names - Make the CEL expression more maintainable - Reference steps dynamically based on index Requirements: pip install cel-python """ from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.workflow import CEL_AVAILABLE, Step, Workflow from agno.workflow.router import Router # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- if not CEL_AVAILABLE: print("CEL is not available. Install with: pip install cel-python") exit(1) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- quick_analyzer = Agent( name="Quick Analyzer", model=OpenAIChat(id="gpt-4o-mini"), instructions="Provide a brief, concise analysis of the topic.", markdown=True, ) detailed_analyzer = Agent( name="Detailed Analyzer", model=OpenAIChat(id="gpt-4o-mini"), instructions="Provide a comprehensive, in-depth analysis of the topic.", markdown=True, ) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- workflow = Workflow( name="CEL Step Choices Router", steps=[ Router( name="Analysis Router", # step_choices[0] = "Quick Analysis" (first choice) # step_choices[1] = "Detailed Analysis" (second choice) selector='input.contains("quick") || input.contains("brief") ? step_choices[0] : step_choices[1]', choices=[ Step(name="Quick Analysis", agent=quick_analyzer), Step(name="Detailed Analysis", agent=detailed_analyzer), ], ), ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": # This will route to step_choices[0] ("Quick Analysis") print("=== Quick analysis request ===") workflow.print_response( input="Give me a quick overview of quantum computing.", stream=True ) print("\n" + "=" * 50 + "\n") # This will route to step_choices[1] ("Detailed Analysis") print("=== Detailed analysis request ===") workflow.print_response(input="Explain quantum computing in detail.", stream=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/04_workflows/07_cel_expressions/router/cel_using_step_choices.py", "license": "Apache License 2.0", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/customize/update_from_lifespan.py
""" Update From Lifespan ==================== Demonstrates update from lifespan. """ from contextlib import asynccontextmanager from agno.agent.agent import Agent from agno.db.postgres.postgres import PostgresDb from agno.os import AgentOS from agno.tools.mcp import MCPTools # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- db = PostgresDb(id="basic-db", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai") # First agent. We will add this to the AgentOS on initialization. agent1 = Agent( name="First Agent", markdown=True, ) # Second agent. We will add this to the AgentOS in the lifespan function. agent2 = Agent( id="second-agent", name="Second Agent", tools=[MCPTools(transport="streamable-http", url="https://docs.agno.com/mcp")], markdown=True, db=db, ) # Lifespan function receiving the AgentOS instance as parameter. @asynccontextmanager async def lifespan(app, agent_os): # Add the new Agent agent_os.agents.append(agent2) # Resync the AgentOS agent_os.resync(app=app) yield # Setup our AgentOS with the lifespan function and the first agent. agent_os = AgentOS( lifespan=lifespan, agents=[agent1], enable_mcp_server=True, ) # Get our app. app = agent_os.get_app() # Serve the app. # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="update_from_lifespan:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/customize/update_from_lifespan.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/dynamo.py
"""Example showing how to use AgentOS with a DynamoDB database Set the following environment variables to connect to your DynamoDb instance: - AWS_REGION - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY Or pass those parameters when initializing the DynamoDb instance. Run `uv pip install boto3` to install dependencies. """ from agno.agent import Agent from agno.db.dynamo import DynamoDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- # Setup the DynamoDB database db = DynamoDb() # Setup a basic agent and a basic team basic_agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) basic_team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=db, members=[basic_agent], debug_mode=True, ) # Evals evaluation = AccuracyEval( db=db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=basic_agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # evaluation.run(print_results=True) agent_os = AgentOS( description="Example OS setup", agents=[basic_agent], teams=[basic_team], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="dynamo:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/dynamo.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/firestore.py
"""Example showing how to use AgentOS with a Firestore database""" from agno.agent import Agent from agno.db.firestore import FirestoreDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- PROJECT_ID = "agno-os-test" # Setup the Firestore database db = FirestoreDb( project_id=PROJECT_ID, session_collection="sessions", eval_collection="eval_runs", memory_collection="user_memories", metrics_collection="metrics", knowledge_collection="knowledge", ) # Setup a basic agent and a basic team basic_agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) basic_team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=db, update_memory_on_run=True, members=[basic_agent], debug_mode=True, ) # Evals evaluation = AccuracyEval( db=db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=basic_agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # evaluation.run(print_results=True) agent_os = AgentOS( description="Example app for basic agent with Firestore database capabilities", id="firestore-app", agents=[basic_agent], teams=[basic_team], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": basic_agent.run("Please remember I really like French food") agent_os.serve(app="firestore:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/firestore.py", "license": "Apache License 2.0", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/gcs_json.py
""" Example showing how to use AgentOS with JSON files hosted in GCS as database. GCS JSON Database Setup: - Uses JSON files stored in Google Cloud Storage as a lightweight database - Only requires a GCS bucket name - authentication follows the standard GCP patterns: * Local development: `gcloud auth application-default login` * Production: Set GOOGLE_APPLICATION_CREDENTIALS env var to service account key path * GCP instances: Uses instance metadata automatically - Optional prefix parameter for organizing files (defaults to empty string) - Automatically creates JSON files in the bucket as needed Prerequisites: 1. Create a GCS bucket 2. Ensure proper GCS permissions 3. Install google-cloud-storage: `uv pip install google-cloud-storage` """ from agno.agent import Agent from agno.db.gcs_json import GcsJsonDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- # Setup the GCS JSON database db = GcsJsonDb(bucket_name="agno_tests") # Setup a basic agent and a basic team agent = Agent( name="JSON Demo Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) team = Team( id="basic-team", name="JSON Demo Team", model=OpenAIChat(id="gpt-4o"), db=db, members=[agent], debug_mode=True, ) # Evaluation example evaluation = AccuracyEval( db=db, name="JSON Demo Evaluation", model=OpenAIChat(id="gpt-4o"), agent=agent, input="What is 2 + 2?", expected_output="4", num_iterations=1, ) # evaluation.run(print_results=True) # Create the AgentOS instance agent_os = AgentOS( id="json-demo-app", description="Example app using JSON file database for simple deployments and demos", agents=[agent], teams=[team], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="gcs_json:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/gcs_json.py", "license": "Apache License 2.0", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/json_db.py
"""Example showing how to use AgentOS with JSON files as database""" from agno.agent import Agent from agno.db.json import JsonDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- # Setup the JSON database db = JsonDb(db_path="./agno_json_data") # Setup a basic agent and a basic team agent = Agent( name="JSON Demo Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) team = Team( id="basic-team", name="JSON Demo Team", model=OpenAIChat(id="gpt-4o"), db=db, members=[agent], debug_mode=True, ) # Evaluation example evaluation = AccuracyEval( db=db, name="JSON Demo Evaluation", model=OpenAIChat(id="gpt-4o"), agent=agent, input="What is 2 + 2?", expected_output="4", num_iterations=1, ) # evaluation.run(print_results=True) # Create the AgentOS instance agent_os = AgentOS( id="json-demo-app", description="Example app using JSON file database for simple deployments and demos", agents=[agent], teams=[team], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="json_db:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/json_db.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/mongo.py
""" Mongo Database Backend ====================== Demonstrates AgentOS with MongoDB storage using both sync and async setups. """ from agno.agent import Agent from agno.db.mongo import AsyncMongoDb, MongoDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- sync_db = MongoDb(db_url="mongodb://localhost:27017") async_db = AsyncMongoDb( db_url="mongodb://localhost:27017", session_collection="sessionss222", ) # --------------------------------------------------------------------------- # Create Sync Agent, Team, Eval, And AgentOS # --------------------------------------------------------------------------- sync_agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=sync_db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) sync_team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=sync_db, members=[sync_agent], ) sync_evaluation = AccuracyEval( db=sync_db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=sync_agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # sync_evaluation.run(print_results=True) sync_agent_os = AgentOS( description="Example OS setup", agents=[sync_agent], teams=[sync_team], ) # --------------------------------------------------------------------------- # Create Async Agent, Team, Eval, And AgentOS # --------------------------------------------------------------------------- async_agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=async_db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) async_team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=async_db, members=[async_agent], ) async_evaluation = AccuracyEval( db=async_db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=async_agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # async_evaluation.run(print_results=True) async_agent_os = AgentOS( description="Example OS setup", agents=[async_agent], teams=[async_team], ) # --------------------------------------------------------------------------- # Create AgentOS App # --------------------------------------------------------------------------- # Default to the sync setup. Switch to async_agent_os to run the async variant. agent_os = sync_agent_os app = agent_os.get_app() # --------------------------------------------------------------------------- # Run # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="mongo:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/mongo.py", "license": "Apache License 2.0", "lines": 104, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/mysql.py
""" MySQL Database Backend ====================== Demonstrates AgentOS with MySQL storage using both sync and async setups. """ from agno.agent import Agent from agno.db.mysql import AsyncMySQLDb, MySQLDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- sync_db = MySQLDb( id="mysql-demo", db_url="mysql+pymysql://ai:ai@localhost:3306/ai", session_table="sessions", eval_table="eval_runs", memory_table="user_memories", metrics_table="metrics", ) async_db = AsyncMySQLDb( id="mysql-demo", db_url="mysql+asyncmy://ai:ai@localhost:3306/ai", session_table="sessions", eval_table="eval_runs", memory_table="user_memories", metrics_table="metrics", ) # --------------------------------------------------------------------------- # Create Sync Agent, Team, Eval, And AgentOS # --------------------------------------------------------------------------- sync_agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=sync_db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) sync_team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=sync_db, members=[sync_agent], ) sync_evaluation = AccuracyEval( db=sync_db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=sync_agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # sync_evaluation.run(print_results=True) sync_agent_os = AgentOS( description="Example OS setup", agents=[sync_agent], teams=[sync_team], ) # --------------------------------------------------------------------------- # Create Async Agent, Team, And AgentOS # --------------------------------------------------------------------------- async_agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=async_db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) async_team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=async_db, members=[async_agent], ) async_agent_os = AgentOS( description="Example OS setup", agents=[async_agent], teams=[async_team], ) # --------------------------------------------------------------------------- # Create AgentOS App # --------------------------------------------------------------------------- # Default to the sync setup. Switch to async_agent_os to run the async variant. agent_os = sync_agent_os app = agent_os.get_app() # --------------------------------------------------------------------------- # Run # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="mysql:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/mysql.py", "license": "Apache License 2.0", "lines": 105, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/neon.py
"""Example showing how to use AgentOS with Neon as our database provider""" from os import getenv from agno.agent import Agent from agno.db.postgres import PostgresDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- NEON_DB_URL = getenv("NEON_DB_URL") db = PostgresDb(db_url=NEON_DB_URL) # Setup a basic agent and a basic team agent = Agent( name="Basic Agent", id="basic-agent", update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), update_memory_on_run=True, members=[agent], debug_mode=True, ) # Evals evaluation = AccuracyEval( db=db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # evaluation.run(print_results=True) agent_os = AgentOS( description="Example OS setup", agents=[agent], teams=[team], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="neon:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/neon.py", "license": "Apache License 2.0", "lines": 54, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/postgres.py
""" Postgres Database Backend ========================= Demonstrates AgentOS with PostgreSQL storage using both sync and async setups. """ from agno.agent import Agent from agno.db.postgres import AsyncPostgresDb, PostgresDb from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team from agno.workflow.step import Step from agno.workflow.workflow import Workflow # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- sync_db = PostgresDb( db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", ) async_db = AsyncPostgresDb(db_url="postgresql+psycopg_async://ai:ai@localhost:5532/ai") # --------------------------------------------------------------------------- # Create Sync Agent, Team, And AgentOS # --------------------------------------------------------------------------- sync_agent = Agent( db=sync_db, name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), add_history_to_context=True, num_history_runs=3, ) sync_team = Team( db=sync_db, id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), members=[sync_agent], add_history_to_context=True, num_history_runs=3, ) sync_agent_os = AgentOS( description="Example OS setup", agents=[sync_agent], teams=[sync_team], ) # --------------------------------------------------------------------------- # Create Async Agent, Team, Workflow, And AgentOS # --------------------------------------------------------------------------- async_agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=async_db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) async_team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=async_db, update_memory_on_run=True, members=[async_agent], ) async_workflow = Workflow( id="basic-workflow", name="Basic Workflow", description="Just a simple workflow", db=async_db, steps=[ Step( name="step1", description="Just a simple step", agent=async_agent, ) ], ) async_agent_os = AgentOS( description="Example OS setup", agents=[async_agent], teams=[async_team], workflows=[async_workflow], ) # --------------------------------------------------------------------------- # Create AgentOS App # --------------------------------------------------------------------------- # Default to the sync setup. Switch to async_agent_os to run the async variant. agent_os = sync_agent_os app = agent_os.get_app() # --------------------------------------------------------------------------- # Run # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="postgres:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/postgres.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/redis_db.py
"""Example showing how to use AgentOS with Redis as database""" from agno.agent import Agent from agno.db.redis import RedisDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- # Setup the Redis database db = RedisDb( db_url="redis://localhost:6379", session_table="sessions_new", metrics_table="metrics_new", ) # Setup a basic agent and a basic team agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=db, members=[agent], ) # Evals evaluation = AccuracyEval( db=db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # evaluation.run(print_results=True) agent_os = AgentOS( description="Example OS setup", agents=[agent], teams=[team], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="redis_db:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/redis_db.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/singlestore.py
"""Example showing how to use AgentOS with SingleStore as our database provider""" from agno.agent import Agent from agno.db.singlestore import SingleStoreDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- SINGLE_STORE_DB_URL = "mysql+pymysql://root:ai@localhost:3306/ai" # Setup the SingleStore database db = SingleStoreDb( db_url=SINGLE_STORE_DB_URL, session_table="sessions", eval_table="eval_runs", memory_table="user_memories", metrics_table="metrics", ) # Setup a basic agent and a basic team agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=db, members=[agent], debug_mode=True, ) # Evals evaluation = AccuracyEval( db=db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # evaluation.run(print_results=True) agent_os = AgentOS( description="Example OS setup", agents=[agent], teams=[team], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": agent.run("Remember my favorite color is dark green") agent_os.serve(app="singlestore:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/singlestore.py", "license": "Apache License 2.0", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/sqlite.py
"""Example showing how to use AgentOS with a SQLite database""" from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- # Setup the SQLite database db = SqliteDb( db_file="agno.db", session_table="sessions", eval_table="eval_runs", memory_table="user_memories", metrics_table="metrics", ) # Setup a basic agent and a basic team basic_agent = Agent( name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), db=db, update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) team_agent = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), db=db, members=[basic_agent], debug_mode=True, ) # Evals evaluation = AccuracyEval( db=db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=basic_agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # evaluation.run(print_results=True) agent_os = AgentOS( description="Example OS setup", agents=[basic_agent], teams=[team_agent], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="sqlite:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/sqlite.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/supabase.py
"""Example showing how to use AgentOS with Supabase as our database provider""" from os import getenv from agno.agent import Agent from agno.db.postgres import PostgresDb from agno.eval.accuracy import AccuracyEval from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- SUPABASE_PROJECT = getenv("SUPABASE_PROJECT") SUPABASE_PASSWORD = getenv("SUPABASE_PASSWORD") SUPABASE_DB_URL = ( f"postgresql://postgres:{SUPABASE_PASSWORD}@db.{SUPABASE_PROJECT}:5432/postgres" ) # Setup the Postgres database db = PostgresDb(db_url=SUPABASE_DB_URL) # Setup a basic agent and a basic team agent = Agent( name="Basic Agent", id="basic-agent", update_memory_on_run=True, enable_session_summaries=True, add_history_to_context=True, num_history_runs=3, add_datetime_to_context=True, markdown=True, ) team = Team( id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), update_memory_on_run=True, members=[agent], debug_mode=True, ) # Evals evaluation = AccuracyEval( db=db, name="Calculator Evaluation", model=OpenAIChat(id="gpt-4o"), agent=agent, input="Should I post my password online? Answer yes or no.", expected_output="No", num_iterations=1, ) # evaluation.run(print_results=True) agent_os = AgentOS( description="Example OS setup", agents=[agent], teams=[team], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": agent.run("What is the weather in Tokyo?") agent_os.serve(app="supabase:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/supabase.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/dbs/surreal.py
"""Example showing how to use AgentOS with SurrealDB as database""" from agno.agent import Agent from agno.db.surrealdb import SurrealDb from agno.knowledge.knowledge import Knowledge from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team.team import Team from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- # Setup the SurrealDB database SURREALDB_URL = "ws://localhost:8000" SURREALDB_USER = "root" SURREALDB_PASSWORD = "root" SURREALDB_NAMESPACE = "agno" SURREALDB_DATABASE = "agent_os_demo" creds = {"username": SURREALDB_USER, "password": SURREALDB_PASSWORD} db = SurrealDb(None, SURREALDB_URL, creds, SURREALDB_NAMESPACE, SURREALDB_DATABASE) db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" vector_db = PgVector(table_name="agent_os_knowledge", db_url=db_url) knowledge = Knowledge( contents_db=db, vector_db=vector_db, name="Agent OS Knowledge", description="Knowledge for Agent OS demo", ) # Agent Setup agent = Agent( db=db, name="Basic Agent", id="basic-agent", model=OpenAIChat(id="gpt-4o"), add_history_to_context=True, num_history_runs=3, knowledge=knowledge, ) # Team Setup team = Team( db=db, id="basic-team", name="Team Agent", model=OpenAIChat(id="gpt-4o"), members=[agent], add_history_to_context=True, num_history_runs=3, ) # AgentOS Setup agent_os = AgentOS( description="Example OS setup", agents=[agent], teams=[team], ) # Get the app app = agent_os.get_app() # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": # Serve the app agent_os.serve(app="surreal:app", reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/dbs/surreal.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/schemas/agent_schemas.py
""" Agent Input And Output Schemas ============================== Demonstrates AgentOS agents that use input and output schemas. """ from typing import List from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.tools.hackernews import HackerNewsTools from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- input_schema_db = SqliteDb( session_table="agent_session", db_file="tmp/agent.db", ) output_schema_db = SqliteDb( session_table="movie_agent_sessions", db_file="tmp/agent_output_schema.db", ) class ResearchTopic(BaseModel): """Structured research topic with specific requirements.""" topic: str focus_areas: List[str] = Field(description="Specific areas to focus on") target_audience: str = Field(description="Who this research is for") sources_required: int = Field(description="Number of sources needed", default=5) class MovieScript(BaseModel): """Structured movie script output.""" title: str = Field(..., description="Movie title") genre: str = Field(..., description="Movie genre") logline: str = Field(..., description="One-sentence summary") main_characters: List[str] = Field(..., description="Main character names") # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- hackernews_agent = Agent( name="Hackernews Agent", model=OpenAIChat(id="gpt-5.2"), tools=[HackerNewsTools()], role="Extract key insights and content from Hackernews posts", input_schema=ResearchTopic, db=input_schema_db, ) movie_agent = Agent( name="Movie Script Agent", id="movie-agent", model=OpenAIChat(id="gpt-5.2"), description="Creates structured outputs - default MovieScript format, but can be overridden", output_schema=MovieScript, markdown=False, db=output_schema_db, ) # --------------------------------------------------------------------------- # Create AgentOS # --------------------------------------------------------------------------- agent_os = AgentOS( id="agent-schemas-demo", agents=[hackernews_agent, movie_agent], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="agent_schemas:app", port=7777, reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/schemas/agent_schemas.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/05_agent_os/schemas/team_schemas.py
""" Team Input And Output Schemas ============================= Demonstrates AgentOS teams that use input and output schemas. """ from typing import List from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.os import AgentOS from agno.team import Team from agno.tools.hackernews import HackerNewsTools from agno.tools.websearch import WebSearchTools from pydantic import BaseModel, Field # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- input_schema_db = SqliteDb( session_table="team_session", db_file="tmp/team.db", ) output_schema_db = SqliteDb( session_table="research_team_sessions", db_file="tmp/team_output_schema.db", ) class ResearchProject(BaseModel): """Structured research project with validation requirements.""" project_name: str = Field(description="Name of the research project") research_topics: List[str] = Field( description="List of topics to research", min_length=1 ) target_audience: str = Field(description="Intended audience for the research") depth_level: str = Field( description="Research depth level", pattern="^(basic|intermediate|advanced)$" ) max_sources: int = Field(description="Maximum number of sources to use", default=10) include_recent_only: bool = Field( description="Whether to focus only on recent sources", default=True ) class ResearchReport(BaseModel): """Structured research report output.""" topic: str = Field(..., description="Research topic") summary: str = Field(..., description="Executive summary") key_findings: List[str] = Field(..., description="Key findings") recommendations: List[str] = Field(..., description="Action recommendations") # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- hackernews_agent = Agent( name="HackerNews Researcher", model=OpenAIChat(id="o3-mini"), tools=[HackerNewsTools()], role="Research trending topics and discussions on HackerNews", instructions=[ "Search for relevant discussions and articles", "Focus on high-quality posts with good engagement", "Extract key insights and technical details", ], db=input_schema_db, ) web_researcher = Agent( name="Web Researcher", model=OpenAIChat(id="o3-mini"), tools=[WebSearchTools()], role="Conduct comprehensive web research", instructions=[ "Search for authoritative sources and documentation", "Find recent articles and blog posts", "Gather diverse perspectives on the topics", ], ) researcher = Agent( name="Researcher", model=OpenAIChat(id="gpt-4o-mini"), tools=[WebSearchTools()], role="Conduct thorough research on assigned topics", ) analyst = Agent( name="Analyst", model=OpenAIChat(id="gpt-4o-mini"), role="Analyze research findings and provide recommendations", ) # --------------------------------------------------------------------------- # Create Teams # --------------------------------------------------------------------------- research_team_with_input_schema = Team( name="Research Team with Input Validation", model=OpenAIChat(id="o3-mini"), members=[hackernews_agent, web_researcher], delegate_to_all_members=True, input_schema=ResearchProject, instructions=[ "Conduct thorough research based on the validated input", "Coordinate between team members to avoid duplicate work", "Ensure research depth matches the specified level", "Respect the maximum sources limit", "Focus on recent sources if requested", ], ) research_team_with_output_schema = Team( name="Research Team", id="research-team", model=OpenAIChat(id="gpt-4o-mini"), members=[researcher, analyst], output_schema=ResearchReport, markdown=False, db=output_schema_db, ) # --------------------------------------------------------------------------- # Create AgentOS # --------------------------------------------------------------------------- agent_os = AgentOS( id="team-schemas-demo", teams=[research_team_with_input_schema, research_team_with_output_schema], ) app = agent_os.get_app() # --------------------------------------------------------------------------- # Run # --------------------------------------------------------------------------- if __name__ == "__main__": agent_os.serve(app="team_schemas:app", port=7777, reload=True)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/05_agent_os/schemas/team_schemas.py", "license": "Apache License 2.0", "lines": 121, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/01_from_path.py
""" From Path ========= Demonstrates loading knowledge from a local file path using sync and async inserts. """ import asyncio from agno.agent import Agent from agno.db.postgres.postgres import PostgresDb from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- contents_db = PostgresDb( db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", knowledge_table="knowledge_contents", ) vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_sync_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, contents_db=contents_db, ) def create_async_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, contents_db=contents_db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_agent(knowledge: Knowledge) -> Agent: return Agent( name="My Agent", description="Agno 2.0 Agent Implementation", knowledge=knowledge, search_knowledge=True, debug_mode=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_sync_knowledge() knowledge.insert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) agent = create_agent(knowledge) agent.print_response( "What skills does Jordan Mitchell have?", markdown=True, ) async def run_async() -> None: knowledge = create_async_knowledge() await knowledge.ainsert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) agent = create_agent(knowledge) agent.print_response( "What skills does Jordan Mitchell have?", markdown=True, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/01_from_path.py", "license": "Apache License 2.0", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/02_from_url.py
""" From URL ======== Demonstrates loading knowledge from a URL using sync and async inserts. """ import asyncio from agno.agent import Agent from agno.db.postgres.postgres import PostgresDb from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- contents_db = PostgresDb( db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", knowledge_table="knowledge_contents", ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", contents_db=contents_db, vector_db=PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ), ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_agent(knowledge: Knowledge) -> Agent: return Agent( name="My Agent", description="Agno 2.0 Agent Implementation", knowledge=knowledge, search_knowledge=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="Recipes", url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", metadata={"user_tag": "Recipes from website"}, ) agent = create_agent(knowledge) agent.print_response( "What can you tell me about Thai recipes?", markdown=True, ) knowledge.remove_vectors_by_name("Recipes") async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="Recipes", url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", metadata={"user_tag": "Recipes from website"}, ) agent = create_agent(knowledge) agent.print_response( "What can you tell me about Thai recipes?", markdown=True, ) knowledge.remove_vectors_by_name("Recipes") if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/02_from_url.py", "license": "Apache License 2.0", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/03_from_topic.py
""" From Topic ========== Demonstrates loading topics from Wikipedia and Arxiv using sync and async operations. """ import asyncio from agno.agent import Agent from agno.db.postgres import PostgresDb from agno.knowledge.knowledge import Knowledge from agno.knowledge.reader.arxiv_reader import ArxivReader from agno.knowledge.reader.wikipedia_reader import WikipediaReader from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) contents_db = PostgresDb( db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", knowledge_table="knowledge_contents", ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, contents_db=contents_db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_agent(knowledge: Knowledge) -> Agent: return Agent( name="My Agent", description="Agno 2.0 Agent Implementation", knowledge=knowledge, search_knowledge=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( metadata={"user_tag": "Wikipedia content"}, topics=["Manchester United"], reader=WikipediaReader(), ) knowledge.insert( metadata={"user_tag": "Arxiv content"}, topics=["Carbon Dioxide", "Oxygen"], reader=ArxivReader(), ) knowledge.insert_many( topics=["Carbon Dioxide", "Nitrogen"], reader=ArxivReader(), skip_if_exists=True, ) agent = create_agent(knowledge) agent.print_response( "What can you tell me about Manchester United?", markdown=True, ) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( metadata={"user_tag": "Wikipedia content"}, topics=["Manchester United"], reader=WikipediaReader(), ) await knowledge.ainsert( metadata={"user_tag": "Arxiv content"}, topics=["Carbon Dioxide", "Oxygen"], reader=ArxivReader(), ) await knowledge.ainsert_many( topics=["Carbon Dioxide", "Nitrogen"], reader=ArxivReader(), skip_if_exists=True, ) agent = create_agent(knowledge) agent.print_response( "What can you tell me about Manchester United?", markdown=True, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/03_from_topic.py", "license": "Apache License 2.0", "lines": 92, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/04_from_multiple.py
""" From Multiple Sources ===================== Demonstrates loading knowledge from multiple paths and URLs using sync and async operations. """ import asyncio from agno.agent import Agent from agno.knowledge.embedder.openai import OpenAIEmbedder from agno.knowledge.knowledge import Knowledge from agno.models.openai import OpenAIChat from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- def create_sync_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ), ) def create_async_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", embedder=OpenAIEmbedder(), ), ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_sync_agent(knowledge: Knowledge) -> Agent: return Agent(knowledge=knowledge, search_knowledge=True) def create_async_agent(knowledge: Knowledge) -> Agent: return Agent( model=OpenAIChat(id="gpt-4o-mini"), knowledge=knowledge, search_knowledge=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_sync_knowledge() knowledge.insert_many( [ { "name": "CV's", "path": "cookbook/07_knowledge/testing_resources/cv_1.pdf", "metadata": {"user_tag": "Engineering candidates"}, }, { "name": "Docs", "url": "https://docs.agno.com/introduction", "metadata": {"user_tag": "Documents"}, }, ] ) knowledge.insert_many( urls=[ "https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", "https://docs.agno.com/introduction", "https://docs.agno.com/knowledge/overview.md", ], ) agent = create_sync_agent(knowledge) agent.print_response("What can you tell me about Agno?", markdown=True) async def run_async() -> None: knowledge = create_async_knowledge() await knowledge.ainsert_many( [ { "name": "CV's", "path": "cookbook/07_knowledge/testing_resources/cv_1.pdf", "metadata": {"user_tag": "Engineering candidates"}, }, { "name": "Docs", "url": "https://docs.agno.com/introduction", "metadata": {"user_tag": "Documents"}, }, ] ) await knowledge.ainsert_many( urls=[ "https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", "https://docs.agno.com/introduction", "https://docs.agno.com/knowledge/overview.md", ], ) agent = create_async_agent(knowledge) agent.print_response("What can you tell me about my documents?", markdown=True) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/04_from_multiple.py", "license": "Apache License 2.0", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/05_from_youtube.py
""" From YouTube ============ Demonstrates loading knowledge from a YouTube URL using sync and async inserts. """ import asyncio from agno.agent import Agent from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_agent(knowledge: Knowledge) -> Agent: return Agent( name="My Agent", description="Agno 2.0 Agent Implementation", knowledge=knowledge, search_knowledge=True, debug_mode=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="Agents from Scratch", url="https://www.youtube.com/watch?v=nLkBNnnA8Ac", metadata={"user_tag": "Youtube video"}, ) agent = create_agent(knowledge) agent.print_response( "What can you tell me about the building agents?", markdown=True, ) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="Agents from Scratch", url="https://www.youtube.com/watch?v=nLkBNnnA8Ac", metadata={"user_tag": "Youtube video"}, ) agent = create_agent(knowledge) agent.print_response( "What can you tell me about the building agents?", markdown=True, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/05_from_youtube.py", "license": "Apache License 2.0", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/06_from_s3.py
""" From S3 ======= Demonstrates loading knowledge from S3 remote content using sync and async inserts. """ import asyncio from agno.agent import Agent from agno.db.postgres.postgres import PostgresDb from agno.knowledge.knowledge import Knowledge from agno.knowledge.remote_content.remote_content import S3Content from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- contents_db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai") vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", contents_db=contents_db, vector_db=vector_db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_agent(knowledge: Knowledge) -> Agent: return Agent( name="My Agent", description="Agno 2.0 Agent Implementation", knowledge=knowledge, search_knowledge=True, debug_mode=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="S3 PDF", remote_content=S3Content( bucket_name="agno-public", key="recipes/ThaiRecipes.pdf" ), metadata={"remote_content": "S3"}, ) agent = create_agent(knowledge) agent.print_response( "What is the best way to make a Thai curry?", markdown=True, ) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="S3 PDF", remote_content=S3Content( bucket_name="agno-public", key="recipes/ThaiRecipes.pdf" ), metadata={"remote_content": "S3"}, ) agent = create_agent(knowledge) agent.print_response( "What is the best way to make a Thai curry?", markdown=True, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/06_from_s3.py", "license": "Apache License 2.0", "lines": 73, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/07_from_gcs.py
""" From GCS ======== Demonstrates loading knowledge from GCS remote content using sync and async inserts. """ import asyncio from agno.agent import Agent from agno.db.postgres.postgres import PostgresDb from agno.knowledge.knowledge import Knowledge from agno.knowledge.remote_content.remote_content import GCSContent from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- contents_db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai") vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", contents_db=contents_db, vector_db=vector_db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_agent(knowledge: Knowledge) -> Agent: return Agent( name="My Agent", description="Agno 2.0 Agent Implementation", knowledge=knowledge, search_knowledge=True, debug_mode=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="GCS PDF", remote_content=GCSContent( bucket_name="thai-recepies", blob_name="ThaiRecipes.pdf" ), metadata={"remote_content": "GCS"}, ) agent = create_agent(knowledge) agent.print_response( "What is the best way to make a Thai curry?", markdown=True, ) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="GCS PDF", remote_content=GCSContent( bucket_name="thai-recepies", blob_name="ThaiRecipes.pdf" ), metadata={"remote_content": "GCS"}, ) agent = create_agent(knowledge) agent.print_response( "What is the best way to make a Thai curry?", markdown=True, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/07_from_gcs.py", "license": "Apache License 2.0", "lines": 73, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/08_include_exclude_files.py
""" Include And Exclude Files ========================= Demonstrates include and exclude filters when loading directory content into knowledge. """ import asyncio from agno.agent import Agent from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_agent(knowledge: Knowledge) -> Agent: return Agent( name="My Agent", description="Agno 2.0 Agent Implementation", knowledge=knowledge, search_knowledge=True, debug_mode=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="CV", path="cookbook/07_knowledge/testing_resources", metadata={"user_tag": "Engineering Candidates"}, include=["*.pdf"], exclude=["*cv_5*"], ) agent = create_agent(knowledge) agent.print_response( "Who is the best candidate for the role of a software engineer?", markdown=True, ) agent.print_response( "Do you think Alex Rivera is a good candidate?", markdown=True, ) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="CV", path="cookbook/07_knowledge/testing_resources", metadata={"user_tag": "Engineering Candidates"}, include=["*.pdf"], exclude=["*cv_5*"], ) agent = create_agent(knowledge) agent.print_response( "Who is the best candidate for the role of a software engineer?", markdown=True, ) agent.print_response( "Do you think Alex Rivera is a good candidate?", markdown=True, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/08_include_exclude_files.py", "license": "Apache License 2.0", "lines": 77, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/09_remove_content.py
""" Remove Content ============== Demonstrates removing knowledge content by id and clearing all content, with sync and async APIs. """ import asyncio from agno.db.postgres.postgres import PostgresDb from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) contents_db = PostgresDb( db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", knowledge_table="knowledge_contents", ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", contents_db=contents_db, vector_db=vector_db, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) contents, _ = knowledge.get_content() for content in contents: print(content.id) print(" ") knowledge.remove_content_by_id(content.id) knowledge.remove_all_content() async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) contents, _ = await knowledge.aget_content() for content in contents: print(content.id) print(" ") await knowledge.aremove_content_by_id(content.id) await knowledge.aremove_all_content() if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/09_remove_content.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/10_remove_vectors.py
""" Remove Vectors ============== Demonstrates removing vectors by metadata and by name using sync and async insert flows. """ import asyncio from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) knowledge.remove_vectors_by_metadata({"user_tag": "Engineering Candidates"}) knowledge.insert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) knowledge.remove_vectors_by_name("CV") async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) knowledge.remove_vectors_by_metadata({"user_tag": "Engineering Candidates"}) await knowledge.ainsert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) knowledge.remove_vectors_by_name("CV") if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/10_remove_vectors.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/11_skip_if_exists.py
""" Skip If Exists ============== Demonstrates skip-if-exists behavior for repeated knowledge inserts with sync and async APIs. """ import asyncio from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, skip_if_exists=True, ) knowledge.insert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, skip_if_exists=False, ) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, skip_if_exists=True, ) await knowledge.ainsert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, skip_if_exists=False, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/11_skip_if_exists.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/12_skip_if_exists_contentsdb.py
""" Skip If Exists With Contents DB =============================== Demonstrates adding existing vector content into a contents database using skip-if-exists. """ import asyncio from agno.db.postgres.postgres import PostgresDb from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="CV", url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", metadata={"user_tag": "Engineering Candidates"}, skip_if_exists=True, ) contents_db = PostgresDb( db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", knowledge_table="knowledge_contents", ) knowledge.contents_db = contents_db knowledge.insert( name="CV", url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", metadata={"user_tag": "Engineering Candidates"}, skip_if_exists=True, ) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="CV", url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", metadata={"user_tag": "Engineering Candidates"}, skip_if_exists=True, ) contents_db = PostgresDb( db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", knowledge_table="knowledge_contents", ) knowledge.contents_db = contents_db await knowledge.ainsert( name="CV", url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", metadata={"user_tag": "Engineering Candidates"}, skip_if_exists=True, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/12_skip_if_exists_contentsdb.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/13_specify_reader.py
""" Specify Reader ============== Demonstrates setting a specific reader during knowledge insertion with sync and async APIs. """ import asyncio from agno.agent import Agent from agno.knowledge.knowledge import Knowledge from agno.knowledge.reader.pdf_reader import PDFReader from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_agent(knowledge: Knowledge) -> Agent: return Agent(knowledge=knowledge, search_knowledge=True) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, reader=PDFReader(), ) agent = create_agent(knowledge) agent.print_response("What can you tell me about my documents?", markdown=True) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, reader=PDFReader(), ) agent = create_agent(knowledge) agent.print_response( "What documents are in the knowledge base?", markdown=True, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/13_specify_reader.py", "license": "Apache License 2.0", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/14_text_content.py
""" Text Content ============ Demonstrates adding direct text content to knowledge using sync and async APIs. """ import asyncio from agno.db.postgres.postgres import PostgresDb from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- contents_db = PostgresDb( db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", knowledge_table="knowledge_contents", ) vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=vector_db, contents_db=contents_db, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="Text Content", text_content="Cats and dogs are pets.", metadata={"user_tag": "Animals"}, ) knowledge.insert_many( name="Text Content", text_contents=["Cats and dogs are pets.", "Birds and fish are not pets."], metadata={"user_tag": "Animals"}, ) knowledge.insert_many( [ { "text_content": "Cats and dogs are pets.", "metadata": {"user_tag": "Animals"}, }, { "text_content": "Birds and fish are not pets.", "metadata": {"user_tag": "Animals"}, }, ], ) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="Text Content", text_content="Cats and dogs are pets.", metadata={"user_tag": "Animals"}, ) await knowledge.ainsert_many( name="Text Content", text_contents=["Cats and dogs are pets.", "Birds and fish are not pets."], metadata={"user_tag": "Animals"}, ) await knowledge.ainsert_many( [ { "text_content": "Cats and dogs are pets.", "metadata": {"user_tag": "Animals"}, }, { "text_content": "Birds and fish are not pets.", "metadata": {"user_tag": "Animals"}, }, ], ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/14_text_content.py", "license": "Apache License 2.0", "lines": 83, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/15_batching.py
""" Batching ======== Demonstrates knowledge insertion with batch embeddings using sync and async APIs. """ import asyncio from agno.agent import Agent from agno.knowledge.embedder.openai import OpenAIEmbedder from agno.knowledge.knowledge import Knowledge from agno.vectordb.lancedb import LanceDb # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- def create_vector_db() -> LanceDb: return LanceDb( uri="tmp/lancedb", table_name="vectors", embedder=OpenAIEmbedder( batch_size=1000, dimensions=1536, enable_batch=True, ), ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- def create_knowledge() -> Knowledge: return Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", vector_db=create_vector_db(), ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- def create_agent(knowledge: Knowledge) -> Agent: return Agent( name="My Agent", description="Agno 2.0 Agent Implementation", knowledge=knowledge, search_knowledge=True, debug_mode=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def run_sync() -> None: knowledge = create_knowledge() knowledge.insert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) agent = create_agent(knowledge) agent.print_response( "What skills does Jordan Mitchell have?", markdown=True, ) async def run_async() -> None: knowledge = create_knowledge() await knowledge.ainsert( name="CV", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"user_tag": "Engineering Candidates"}, ) agent = create_agent(knowledge) agent.print_response( "What skills does Jordan Mitchell have?", markdown=True, ) if __name__ == "__main__": run_sync() asyncio.run(run_async())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/15_batching.py", "license": "Apache License 2.0", "lines": 73, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/07_knowledge/01_quickstart/16_knowledge_instructions.py
""" Knowledge Instructions ====================== Demonstrates disabling automatic search-knowledge instructions on an agent. """ from agno.agent import Agent from agno.db.postgres.postgres import PostgresDb from agno.knowledge.knowledge import Knowledge from agno.vectordb.pgvector import PgVector # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- contents_db = PostgresDb( db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", knowledge_table="knowledge_contents", ) vector_db = PgVector( table_name="vectors", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai" ) # --------------------------------------------------------------------------- # Create Knowledge Base # --------------------------------------------------------------------------- knowledge = Knowledge( name="Basic SDK Knowledge Base", description="Agno 2.0 Knowledge Implementation", contents_db=contents_db, vector_db=vector_db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- agent = Agent( name="My Agent", description="Agno 2.0 Agent Implementation", knowledge=knowledge, search_knowledge=True, add_search_knowledge_instructions=False, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- def main() -> None: knowledge.insert( name="Recipes", url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", metadata={"user_tag": "Recipes from website"}, ) agent.print_response("What can you tell me about Thai recipes?") if __name__ == "__main__": main()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/07_knowledge/01_quickstart/16_knowledge_instructions.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/08_learning/09_decision_logs/01_basic_decision_log.py
""" Decision Logs: Basic Usage ========================== This example demonstrates how to use DecisionLogStore to record and retrieve agent decisions. DecisionLogStore is useful for: - Auditing agent behavior - Debugging unexpected outcomes - Learning from past decisions - Building feedback loops Run: .venvs/demo/bin/python cookbook/08_learning/09_decision_logs/01_basic_decision_log.py """ from agno.agent import Agent from agno.db.postgres import PostgresDb from agno.learn import DecisionLogConfig, LearningMachine, LearningMode from agno.models.openai import OpenAIChat # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- # Database connection db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai") # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- # Create an agent with decision logging # AGENTIC mode: Agent explicitly logs decisions via the log_decision tool agent = Agent( id="decision-logger", name="Decision Logger", model=OpenAIChat(id="gpt-4o"), db=db, learning=LearningMachine( decision_log=DecisionLogConfig( mode=LearningMode.AGENTIC, enable_agent_tools=True, agent_can_save=True, agent_can_search=True, ), ), instructions=[ "You are a helpful assistant that logs important decisions.", "When you make a significant choice (like selecting a tool, choosing a response style, or deciding to ask for clarification), use the log_decision tool to record it.", "Include your reasoning and any alternatives you considered.", ], markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # Test: Ask the agent to make a decision print("=== Test 1: Agent logs a decision ===\n") agent.print_response( "I need help choosing between Python and JavaScript for a web scraping project. What would you recommend?", session_id="session-001", ) # View logged decisions print("\n=== Decisions Logged ===\n") decision_store = agent.learning_machine.decision_log_store if decision_store: decision_store.print(agent_id="decision-logger", limit=5)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/08_learning/09_decision_logs/01_basic_decision_log.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/08_learning/09_decision_logs/02_decision_log_always.py
""" Decision Logs: ALWAYS Mode (Automatic Logging) =============================================== This example demonstrates automatic decision logging where tool calls are automatically recorded as decisions. In ALWAYS mode, DecisionLogStore extracts decisions from: - Tool calls (which tool was used) - Other significant choices the agent makes Run: .venvs/demo/bin/python cookbook/08_learning/09_decision_logs/02_decision_log_always.py """ from agno.agent import Agent from agno.db.postgres import PostgresDb from agno.learn import DecisionLogConfig, LearningMachine, LearningMode from agno.models.openai import OpenAIChat from agno.tools.duckduckgo import DuckDuckGoTools # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- # Database connection db = PostgresDb(db_url="postgresql+psycopg://ai:ai@localhost:5532/ai") # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- # Create an agent with automatic decision logging # ALWAYS mode: Tool calls are automatically logged as decisions agent = Agent( id="auto-decision-logger", name="Auto Decision Logger", model=OpenAIChat(id="gpt-4o"), db=db, learning=LearningMachine( decision_log=DecisionLogConfig( mode=LearningMode.ALWAYS, ), ), tools=[DuckDuckGoTools()], instructions=[ "You are a helpful research assistant.", "Use web search to find current information when needed.", ], markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": # Test: Agent uses a tool (will be logged automatically) print("=== Test: Agent uses web search ===\n") agent.print_response( "What are the latest developments in AI agents?", session_id="session-002", ) # View auto-logged decisions print("\n=== Auto-Logged Decisions ===\n") decision_store = agent.learning_machine.decision_log_store if decision_store: decision_store.print(agent_id="auto-decision-logger", limit=10)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/08_learning/09_decision_logs/02_decision_log_always.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/10_reasoning/models/deepseek/plan_itinerary.py
""" Plan Itinerary ============== Demonstrates this reasoning cookbook example. """ from agno.agent import Agent from agno.models.deepseek import DeepSeek from agno.models.openai import OpenAIChat # --------------------------------------------------------------------------- # Create Example # --------------------------------------------------------------------------- def run_example() -> None: # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- task = "Plan an itinerary from Los Angeles to Las Vegas" reasoning_agent = Agent( model=OpenAIChat(id="gpt-4o"), reasoning_model=DeepSeek(id="deepseek-reasoner"), markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": reasoning_agent.print_response(task, stream=True) # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- if __name__ == "__main__": run_example()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/10_reasoning/models/deepseek/plan_itinerary.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/01_agent_with_memory.py
""" Agent With Persistent Memory ============================ This example shows how to use persistent memory with an Agent. After each run, user memories are created or updated. """ import asyncio from uuid import uuid4 from agno.agent.agent import Agent from agno.db.postgres import PostgresDb from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" db = PostgresDb(db_url=db_url) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), db=db, update_memory_on_run=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": db.clear_memories() session_id = str(uuid4()) john_doe_id = "john_doe@example.com" asyncio.run( agent.aprint_response( "My name is John Doe and I like to hike in the mountains on weekends.", stream=True, user_id=john_doe_id, session_id=session_id, ) ) agent.print_response( "What are my hobbies?", stream=True, user_id=john_doe_id, session_id=session_id ) memories = agent.get_user_memories(user_id=john_doe_id) print("John Doe's memories:") pprint(memories) agent.print_response( "Ok i dont like hiking anymore, i like to play soccer instead.", stream=True, user_id=john_doe_id, session_id=session_id, ) memories = agent.get_user_memories(user_id=john_doe_id) print("John Doe's memories:") pprint(memories)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/01_agent_with_memory.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/02_agentic_memory.py
""" Agentic Memory Management ========================= This example shows how to use agentic memory with an Agent. During each run, the Agent can create, update, and delete user memories. """ from agno.agent.agent import Agent from agno.db.postgres import PostgresDb from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" db = PostgresDb(db_url=db_url) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), db=db, enable_agentic_memory=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": john_doe_id = "john_doe@example.com" agent.print_response( "My name is John Doe and I like to hike in the mountains on weekends.", stream=True, user_id=john_doe_id, ) agent.print_response("What are my hobbies?", stream=True, user_id=john_doe_id) memories = agent.get_user_memories(user_id=john_doe_id) print("Memories about John Doe:") pprint(memories) agent.print_response( "Remove all existing memories of me.", stream=True, user_id=john_doe_id, ) memories = agent.get_user_memories(user_id=john_doe_id) print("Memories about John Doe:") pprint(memories) agent.print_response( "My name is John Doe and I like to paint.", stream=True, user_id=john_doe_id ) memories = agent.get_user_memories(user_id=john_doe_id) print("Memories about John Doe:") pprint(memories) agent.print_response( "I don't paint anymore, i draw instead.", stream=True, user_id=john_doe_id ) memories = agent.get_user_memories(user_id=john_doe_id) print("Memories about John Doe:") pprint(memories)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/02_agentic_memory.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/03_agents_share_memory.py
""" Agents Sharing Memory ===================== This example shows two agents sharing the same user memory. """ from agno.agent.agent import Agent from agno.db.postgres import PostgresDb from agno.models.openai import OpenAIChat from agno.tools.websearch import WebSearchTools from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" db = PostgresDb(db_url=db_url) # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- chat_agent = Agent( model=OpenAIChat(id="gpt-4o"), description="You are a helpful assistant that can chat with users", db=db, update_memory_on_run=True, ) research_agent = Agent( model=OpenAIChat(id="gpt-4o"), description="You are a research assistant that can help users with their research questions", tools=[WebSearchTools()], db=db, update_memory_on_run=True, ) # --------------------------------------------------------------------------- # Run Agents # --------------------------------------------------------------------------- if __name__ == "__main__": john_doe_id = "john_doe@example.com" chat_agent.print_response( "My name is John Doe and I like to hike in the mountains on weekends.", stream=True, user_id=john_doe_id, ) chat_agent.print_response("What are my hobbies?", stream=True, user_id=john_doe_id) research_agent.print_response( "I love asking questions about quantum computing. What is the latest news on quantum computing?", stream=True, user_id=john_doe_id, ) memories = research_agent.get_user_memories(user_id=john_doe_id) print("Memories about John Doe:") pprint(memories)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/03_agents_share_memory.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/04_custom_memory_manager.py
""" Custom Memory Manager Configuration =================================== This example shows how to configure a MemoryManager separately from the Agent and apply custom memory capture instructions. """ from agno.agent.agent import Agent from agno.db.postgres import PostgresDb from agno.memory import MemoryManager from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" db = PostgresDb(db_url=db_url) # --------------------------------------------------------------------------- # Create Memory Manager # --------------------------------------------------------------------------- memory_manager = MemoryManager( model=OpenAIChat(id="gpt-4o"), additional_instructions=""" IMPORTANT: Don't store any memories about the user's name. Just say "The User" instead of referencing the user's name. """, db=db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- agent = Agent( model=OpenAIChat(id="gpt-4o"), db=db, memory_manager=memory_manager, update_memory_on_run=True, user_id="john_doe@example.com", ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": john_doe_id = "john_doe@example.com" agent.print_response( "My name is John Doe and I like to swim and play soccer.", stream=True ) agent.print_response("I dont like to swim", stream=True) memories = agent.get_user_memories(user_id=john_doe_id) print("John Doe's memories:") pprint(memories)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/04_custom_memory_manager.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/07_share_memory_and_history_between_agents.py
""" Share Memory and History Between Agents ======================================= This example shows two agents sharing both conversation history and user memory through a common database, user ID, and session ID. """ from uuid import uuid4 from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai.chat import OpenAIChat # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db = SqliteDb(db_file="tmp/agent_sessions.db") # --------------------------------------------------------------------------- # Create Agents # --------------------------------------------------------------------------- agent_1 = Agent( model=OpenAIChat(id="gpt-4o-mini"), instructions="You are really friendly and helpful.", db=db, add_history_to_context=True, update_memory_on_run=True, ) agent_2 = Agent( model=OpenAIChat(id="gpt-4o-mini"), instructions="You are really grumpy and mean.", db=db, add_history_to_context=True, update_memory_on_run=True, ) # --------------------------------------------------------------------------- # Run Agents # --------------------------------------------------------------------------- if __name__ == "__main__": session_id = str(uuid4()) user_id = "john_doe@example.com" agent_1.print_response( "Hi! My name is John Doe.", session_id=session_id, user_id=user_id ) agent_2.print_response("What is my name?", session_id=session_id, user_id=user_id) agent_2.print_response( "I like to hike in the mountains on weekends.", session_id=session_id, user_id=user_id, ) agent_1.print_response( "What are my hobbies?", session_id=session_id, user_id=user_id ) agent_1.print_response( "What have we been discussing? Give me bullet points.", session_id=session_id, user_id=user_id, )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/07_share_memory_and_history_between_agents.py", "license": "Apache License 2.0", "lines": 54, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/08_memory_tools.py
""" Memory Tools With Web Search ============================ This example shows how to use MemoryTools alongside WebSearchTools so an agent can store and use user memory while planning a trip. """ import asyncio from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.models.openai import OpenAIChat from agno.tools.memory import MemoryTools from agno.tools.websearch import WebSearchTools # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db = SqliteDb(db_file="tmp/memory.db") john_doe_id = "john_doe@example.com" memory_tools = MemoryTools( db=db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- agent = Agent( model=OpenAIChat(id="gpt-5-mini"), tools=[memory_tools, WebSearchTools()], instructions=[ "You are a trip planner bot and you are helping the user plan their trip.", "You should use the WebSearchTools to get information about the destination and activities.", "You should use the MemoryTools to store information about the user for future reference.", "Don't ask the user for more information, make up what you don't know.", ], markdown=True, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- async def main() -> None: await agent.aprint_response( "My name is John Doe and I like to hike in the mountains on weekends. " "I like to travel to new places and experience different cultures. " "I am planning to travel to Africa in December. ", stream=True, user_id=john_doe_id, ) await agent.aprint_response( "Make me a travel itinerary for my trip, and propose where I should go, how much I should budget, etc.", stream=True, user_id=john_doe_id, ) if __name__ == "__main__": asyncio.run(main())
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/08_memory_tools.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/memory_manager/01_standalone_memory.py
""" Standalone Memory Manager CRUD ============================== This example shows how to add, get, delete, and replace user memories manually. """ from agno.db.postgres import PostgresDb from agno.memory import MemoryManager, UserMemory from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" # --------------------------------------------------------------------------- # Create Memory Manager # --------------------------------------------------------------------------- memory = MemoryManager(db=PostgresDb(db_url=db_url)) # --------------------------------------------------------------------------- # Run Memory Manager # --------------------------------------------------------------------------- if __name__ == "__main__": memory.add_user_memory( memory=UserMemory(memory="The user's name is John Doe", topics=["name"]), ) print("Memories:") pprint(memory.get_user_memories()) jane_doe_id = "jane_doe@example.com" print(f"\nUser: {jane_doe_id}") memory_id_1 = memory.add_user_memory( memory=UserMemory(memory="The user's name is Jane Doe", topics=["name"]), user_id=jane_doe_id, ) memory_id_2 = memory.add_user_memory( memory=UserMemory(memory="She likes to play tennis", topics=["hobbies"]), user_id=jane_doe_id, ) memories = memory.get_user_memories(user_id=jane_doe_id) print("Memories:") pprint(memories) print("\nDeleting memory") assert memory_id_2 is not None memory.delete_user_memory(user_id=jane_doe_id, memory_id=memory_id_2) print("Memory deleted\n") memories = memory.get_user_memories(user_id=jane_doe_id) print("Memories:") pprint(memories) print("\nReplacing memory") assert memory_id_1 is not None memory.replace_user_memory( memory_id=memory_id_1, memory=UserMemory(memory="The user's name is Jane Mary Doe", topics=["name"]), user_id=jane_doe_id, ) print("Memory replaced") memories = memory.get_user_memories(user_id=jane_doe_id) print("Memories:") pprint(memories)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/memory_manager/01_standalone_memory.py", "license": "Apache License 2.0", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/memory_manager/02_memory_creation.py
""" Create Memories From Text and Message History ============================================= This example shows how to create user memories from direct text and from a message list using MemoryManager. """ from agno.db.postgres import PostgresDb from agno.memory import MemoryManager, UserMemory from agno.models.message import Message from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" memory_db = PostgresDb(db_url=db_url) # --------------------------------------------------------------------------- # Create Memory Manager # --------------------------------------------------------------------------- memory = MemoryManager(model=OpenAIChat(id="gpt-4o"), db=memory_db) # --------------------------------------------------------------------------- # Run Memory Manager # --------------------------------------------------------------------------- if __name__ == "__main__": john_doe_id = "john_doe@example.com" memory.add_user_memory( memory=UserMemory( memory=""" I enjoy hiking in the mountains on weekends, reading science fiction novels before bed, cooking new recipes from different cultures, playing chess with friends, and attending live music concerts whenever possible. Photography has become a recent passion of mine, especially capturing landscapes and street scenes. I also like to meditate in the mornings and practice yoga to stay centered. """ ), user_id=john_doe_id, ) memories = memory.get_user_memories(user_id=john_doe_id) print("John Doe's memories:") pprint(memories) jane_doe_id = "jane_doe@example.com" memory.create_user_memories( messages=[ Message(role="user", content="My name is Jane Doe"), Message(role="assistant", content="That is great!"), Message(role="user", content="I like to play chess"), Message(role="assistant", content="That is great!"), ], user_id=jane_doe_id, ) memories = memory.get_user_memories(user_id=jane_doe_id) print("Jane Doe's memories:") pprint(memories)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/memory_manager/02_memory_creation.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/memory_manager/03_custom_memory_instructions.py
""" Custom Memory Capture Instructions ================================== This example shows how to customize memory capture instructions and compare the results with a default memory manager. """ from agno.db.postgres import PostgresDb from agno.memory import MemoryManager from agno.models.anthropic.claude import Claude from agno.models.message import Message from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" memory_db = PostgresDb(db_url=db_url) # --------------------------------------------------------------------------- # Create Memory Managers # --------------------------------------------------------------------------- memory = MemoryManager( model=OpenAIChat(id="gpt-4o"), memory_capture_instructions="""\ Memories should only include details about the user's academic interests. Only include which subjects they are interested in. Ignore names, hobbies, and personal interests. """, db=memory_db, ) # --------------------------------------------------------------------------- # Run Memory Manager # --------------------------------------------------------------------------- if __name__ == "__main__": john_doe_id = "john_doe@example.com" memory.create_user_memories( message="""\ My name is John Doe. I enjoy hiking in the mountains on weekends, reading science fiction novels before bed, cooking new recipes from different cultures, playing chess with friends. I am interested to learn about the history of the universe and other astronomical topics. """, user_id=john_doe_id, ) memories = memory.get_user_memories(user_id=john_doe_id) print("John Doe's memories:") pprint(memories) memory = MemoryManager(model=Claude(id="claude-sonnet-4-5-20250929"), db=memory_db) jane_doe_id = "jane_doe@example.com" memory.create_user_memories( messages=[ Message(role="user", content="Hi, how are you?"), Message(role="assistant", content="I'm good, thank you!"), Message(role="user", content="What are you capable of?"), Message( role="assistant", content="I can help you with your homework and answer questions about the universe.", ), Message(role="user", content="My name is Jane Doe"), Message(role="user", content="I like to play chess"), Message( role="user", content="Actually, forget that I like to play chess. I more enjoy playing table top games like dungeons and dragons", ), Message( role="user", content="I'm also interested in learning about the history of the universe and other astronomical topics.", ), Message(role="assistant", content="That is great!"), Message( role="user", content="I am really interested in physics. Tell me about quantum mechanics?", ), ], user_id=jane_doe_id, ) memories = memory.get_user_memories(user_id=jane_doe_id) print("Jane Doe's memories:") pprint(memories)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/memory_manager/03_custom_memory_instructions.py", "license": "Apache License 2.0", "lines": 80, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/memory_manager/04_memory_search.py
""" Search User Memories ==================== This example shows how to search user memories using different retrieval methods such as last_n, first_n, and agentic retrieval. """ from agno.db.postgres import PostgresDb from agno.memory import MemoryManager, UserMemory from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai" memory_db = PostgresDb(db_url=db_url) # --------------------------------------------------------------------------- # Create Memory Manager # --------------------------------------------------------------------------- memory = MemoryManager(model=OpenAIChat(id="gpt-4o"), db=memory_db) # --------------------------------------------------------------------------- # Run Memory Search # --------------------------------------------------------------------------- if __name__ == "__main__": john_doe_id = "john_doe@example.com" memory.add_user_memory( memory=UserMemory(memory="The user enjoys hiking in the mountains on weekends"), user_id=john_doe_id, ) memory.add_user_memory( memory=UserMemory( memory="The user enjoys reading science fiction novels before bed" ), user_id=john_doe_id, ) print("John Doe's memories:") pprint(memory.get_user_memories(user_id=john_doe_id)) memories = memory.search_user_memories( user_id=john_doe_id, limit=1, retrieval_method="last_n" ) print("\nJohn Doe's last_n memories:") pprint(memories) memories = memory.search_user_memories( user_id=john_doe_id, limit=1, retrieval_method="first_n" ) print("\nJohn Doe's first_n memories:") pprint(memories) memories = memory.search_user_memories( user_id=john_doe_id, query="What does the user like to do on weekends?", retrieval_method="agentic", ) print("\nJohn Doe's memories similar to the query (agentic):") pprint(memories)
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/memory_manager/04_memory_search.py", "license": "Apache License 2.0", "lines": 53, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/memory_manager/05_db_tools_control.py
""" Control Memory Database Tools ============================= This example demonstrates how to control which memory database operations are available to the AI model using DB tool flags. """ from agno.agent.agent import Agent from agno.db.sqlite import SqliteDb from agno.memory.manager import MemoryManager from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- memory_db = SqliteDb(db_file="tmp/memory_control_demo.db") john_doe_id = "john_doe@example.com" # --------------------------------------------------------------------------- # Create Memory Manager and Agent # --------------------------------------------------------------------------- memory_manager_full = MemoryManager( model=OpenAIChat(id="gpt-4o"), db=memory_db, add_memories=True, update_memories=True, ) agent_full = Agent( model=OpenAIChat(id="gpt-4o"), memory_manager=memory_manager_full, enable_agentic_memory=True, db=memory_db, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": agent_full.print_response( "My name is John Doe and I like to hike in the mountains on weekends. I also enjoy photography.", stream=True, user_id=john_doe_id, ) agent_full.print_response("What are my hobbies?", stream=True, user_id=john_doe_id) agent_full.print_response( "I no longer enjoy photography. Instead, I've taken up rock climbing.", stream=True, user_id=john_doe_id, ) print("\nMemories after update:") memories = memory_manager_full.get_user_memories(user_id=john_doe_id) pprint([m.memory for m in memories] if memories else [])
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/memory_manager/05_db_tools_control.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/11_memory/optimize_memories/01_memory_summarize_strategy.py
""" Optimize Memories With Summarize Strategy ========================================= This example demonstrates memory optimization using the summarize strategy, which combines all memories into one summary for token reduction. """ from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.memory import MemoryManager, SummarizeStrategy from agno.memory.strategies.types import MemoryOptimizationStrategyType from agno.models.openai import OpenAIChat # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_file = "tmp/memory_summarize_strategy.db" db = SqliteDb(db_file=db_file) user_id = "user2" # --------------------------------------------------------------------------- # Create Agent and Memory Manager # --------------------------------------------------------------------------- agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), db=db, update_memory_on_run=True, ) memory_manager = MemoryManager( model=OpenAIChat(id="gpt-4o-mini"), db=db, ) # --------------------------------------------------------------------------- # Run Optimization # --------------------------------------------------------------------------- if __name__ == "__main__": print("Creating memories...") agent.print_response( "I have a wonderful pet dog named Max who is 3 years old. He's a golden retriever and he's such a friendly and energetic dog. " "We got him as a puppy when he was just 8 weeks old. He loves playing fetch in the park and going on long walks. " "Max is really smart too - he knows about 15 different commands and tricks. Taking care of him has been one of the most " "rewarding experiences of my life. He's basically part of the family now.", user_id=user_id, ) agent.print_response( "I currently live in San Francisco, which is an amazing city despite all its challenges. I've been here for about 5 years now. " "I work in the tech industry as a product manager at a mid-sized software company. The tech scene here is incredible - " "there are so many smart people working on interesting problems. The cost of living is definitely high, but the opportunities " "and the community make it worthwhile. I live in the Mission district which has great food and a vibrant culture.", user_id=user_id, ) agent.print_response( "On weekends, I really enjoy hiking in the beautiful areas around the Bay Area. There are so many amazing trails - " "from Mount Tamalpais to Big Basin Redwoods. I usually go hiking with a group of friends and we try to explore new trails every month. " "I also love trying new restaurants. San Francisco has such an incredible food scene with cuisines from all over the world. " "I'm always on the lookout for hidden gems and new places to try. My favorite types of cuisine are Japanese, Thai, and Mexican.", user_id=user_id, ) agent.print_response( "I've been learning to play the piano for about a year and a half now. It's something I always wanted to do but never had time for. " "I finally decided to commit to it and I practice almost every day, usually for 30-45 minutes. " "I'm working through classical pieces right now - I can play some simple Bach and Mozart compositions. " "My goal is to eventually be able to play some jazz piano as well. Having a creative hobby like this has been great for my mental health " "and it's nice to have something completely different from my day job.", user_id=user_id, ) print("\nBefore optimization:") memories_before = agent.get_user_memories(user_id=user_id) print(f" Memory count: {len(memories_before)}") strategy = SummarizeStrategy() tokens_before = strategy.count_tokens(memories_before) print(f" Token count: {tokens_before} tokens") print("\nIndividual memories:") for i, memory in enumerate(memories_before, 1): print(f" {i}. {memory.memory}") print("\nOptimizing memories with 'summarize' strategy...") memory_manager.optimize_memories( user_id=user_id, strategy=MemoryOptimizationStrategyType.SUMMARIZE, apply=True, ) print("\nAfter optimization:") memories_after = agent.get_user_memories(user_id=user_id) print(f" Memory count: {len(memories_after)}") tokens_after = strategy.count_tokens(memories_after) print(f" Token count: {tokens_after} tokens") if tokens_before > 0: reduction_pct = ((tokens_before - tokens_after) / tokens_before) * 100 tokens_saved = tokens_before - tokens_after print(f" Reduction: {reduction_pct:.1f}% ({tokens_saved} tokens saved)") if memories_after: print("\nSummarized memory:") print(f" {memories_after[0].memory}") else: print("\n No memories found after optimization")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/optimize_memories/01_memory_summarize_strategy.py", "license": "Apache License 2.0", "lines": 92, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:cookbook/11_memory/optimize_memories/02_custom_memory_strategy.py
""" Custom Memory Optimization Strategy =================================== This example shows how to create and apply a custom memory optimization strategy by subclassing MemoryOptimizationStrategy. """ from datetime import datetime from typing import List from agno.agent import Agent from agno.db.schemas import UserMemory from agno.db.sqlite import SqliteDb from agno.memory import MemoryManager, MemoryOptimizationStrategy from agno.models.base import Model from agno.models.openai import OpenAIChat # --------------------------------------------------------------------------- # Create Custom Strategy # --------------------------------------------------------------------------- class RecentOnlyStrategy(MemoryOptimizationStrategy): """Keep only the N most recent memories.""" def __init__(self, keep_count: int = 2): self.keep_count = keep_count def optimize( self, memories: List[UserMemory], model: Model, ) -> List[UserMemory]: """Keep only the most recent N memories.""" sorted_memories = sorted( memories, key=lambda m: m.updated_at or m.created_at or datetime.min, reverse=True, ) return sorted_memories[: self.keep_count] async def aoptimize( self, memories: List[UserMemory], model: Model, ) -> List[UserMemory]: """Async version of optimize.""" sorted_memories = sorted( memories, key=lambda m: m.updated_at or m.created_at or datetime.min, reverse=True, ) return sorted_memories[: self.keep_count] # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- db_file = "tmp/custom_memory_strategy.db" db = SqliteDb(db_file=db_file) user_id = "user3" # --------------------------------------------------------------------------- # Create Agent and Memory Manager # --------------------------------------------------------------------------- agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), db=db, update_memory_on_run=True, ) memory_manager = MemoryManager( model=OpenAIChat(id="gpt-4o-mini"), db=db, ) # --------------------------------------------------------------------------- # Run Optimization # --------------------------------------------------------------------------- if __name__ == "__main__": print("Creating memories...") agent.print_response( "I'm currently learning machine learning and it's been an incredible journey so far. I started about 6 months ago with the basics - " "linear regression, decision trees, and simple classification algorithms. Now I'm diving into more advanced topics like deep learning " "and neural networks. I'm using Python with libraries like scikit-learn, TensorFlow, and PyTorch. " "The math can be challenging sometimes, especially the calculus and linear algebra, but I'm working through it step by step.", user_id=user_id, ) agent.print_response( "I recently completed an excellent online course on neural networks from Coursera. The course covered everything from basic perceptrons " "to complex architectures like CNNs and RNNs. The instructor did a great job explaining backpropagation and gradient descent. " "I completed all the programming assignments where we built neural networks from scratch and also used TensorFlow. " "The final project was building an image classifier that achieved 92% accuracy on the test set. I'm really proud of that accomplishment.", user_id=user_id, ) agent.print_response( "My ultimate goal is to build my own AI projects that solve real-world problems. I have several ideas I want to explore - " "maybe a recommendation system, a chatbot for customer service, or perhaps something in computer vision. " "I'm trying to identify problems where AI can make a real difference and where I have the skills to build something meaningful. " "I know I need more experience and practice, but I'm committed to working on personal projects to build my portfolio.", user_id=user_id, ) agent.print_response( "I'm particularly interested in natural language processing applications. The recent advances in large language models are fascinating. " "I've been experimenting with transformer architectures and trying to understand how attention mechanisms work. " "I'd love to work on projects involving text classification, sentiment analysis, or maybe even building conversational AI. " "NLP feels like it's at the cutting edge right now and there are so many interesting problems to solve in this space.", user_id=user_id, ) print("\nBefore optimization:") memories_before = agent.get_user_memories(user_id=user_id) print(f" Memory count: {len(memories_before)}") custom_strategy = RecentOnlyStrategy(keep_count=2) tokens_before = custom_strategy.count_tokens(memories_before) print(f" Token count: {tokens_before} tokens") print("\nAll memories:") for i, memory in enumerate(memories_before, 1): print(f" {i}. {memory.memory}") print("\nOptimizing with custom RecentOnlyStrategy (keep_count=2)...") memory_manager.optimize_memories( user_id=user_id, strategy=custom_strategy, apply=True, ) print("\nAfter optimization:") memories_after = agent.get_user_memories(user_id=user_id) print(f" Memory count: {len(memories_after)}") tokens_after = custom_strategy.count_tokens(memories_after) print(f" Token count: {tokens_after} tokens") if tokens_before > 0: reduction_pct = ((tokens_before - tokens_after) / tokens_before) * 100 tokens_saved = tokens_before - tokens_after print( f" Reduction: {reduction_pct:.1f}% ({tokens_saved} tokens saved by keeping 2 most recent)" ) print("\nRemaining memories (2 most recent):") for i, memory in enumerate(memories_after, 1): print(f" {i}. {memory.memory}")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/11_memory/optimize_memories/02_custom_memory_strategy.py", "license": "Apache License 2.0", "lines": 125, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/92_integrations/observability/workflows/langfuse_via_openinference_workflows.py
""" Langfuse Workflows Via OpenInference ==================================== Demonstrates tracing a multi-step Agno workflow in Langfuse. """ import base64 import os from agno.agent import Agent from agno.tools.websearch import WebSearchTools from agno.workflow.condition import Condition from agno.workflow.step import Step from agno.workflow.types import StepInput from agno.workflow.workflow import Workflow from openinference.instrumentation.agno import AgnoInstrumentor from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- LANGFUSE_AUTH = base64.b64encode( f"{os.getenv('LANGFUSE_PUBLIC_KEY')}:{os.getenv('LANGFUSE_SECRET_KEY')}".encode() ).decode() # os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = ( # "https://us.cloud.langfuse.com/api/public/otel" # US data region # ) os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = ( "https://cloud.langfuse.com/api/public/otel" # EU data region ) # os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "http://localhost:3000/api/public/otel" # Local deployment (>= v3.22.0) os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {LANGFUSE_AUTH}" tracer_provider = TracerProvider() tracer_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter())) # Start instrumenting agno AgnoInstrumentor().instrument(tracer_provider=tracer_provider) # --------------------------------------------------------------------------- # Create Workflow # --------------------------------------------------------------------------- # Basic agents researcher = Agent( name="Researcher", instructions="Research the given topic and provide detailed findings.", tools=[WebSearchTools()], ) summarizer = Agent( name="Summarizer", instructions="Create a clear summary of the research findings.", ) fact_checker = Agent( name="Fact Checker", instructions="Verify facts and check for accuracy in the research.", tools=[WebSearchTools()], ) writer = Agent( name="Writer", instructions="Write a comprehensive article based on all available research and verification.", ) # Condition evaluator def needs_fact_checking(step_input: StepInput) -> bool: """Determine if the research contains claims that need fact-checking.""" return True # Workflow steps research_step = Step( name="research", description="Research the topic", agent=researcher, ) summarize_step = Step( name="summarize", description="Summarize research findings", agent=summarizer, ) fact_check_step = Step( name="fact_check", description="Verify facts and claims", agent=fact_checker, ) write_article = Step( name="write_article", description="Write final article", agent=writer, ) basic_workflow = Workflow( name="Basic Linear Workflow", description="Research -> Summarize -> Condition(Fact Check) -> Write Article", steps=[ research_step, summarize_step, Condition( name="fact_check_condition", description="Check if fact-checking is needed", evaluator=needs_fact_checking, steps=[fact_check_step], ), write_article, ], ) # --------------------------------------------------------------------------- # Run Workflow # --------------------------------------------------------------------------- if __name__ == "__main__": print("Running Basic Linear Workflow Example") print("=" * 50) try: basic_workflow.print_response( input="Recent breakthroughs in quantum computing", stream=True, ) except Exception as e: print(f"Error: {e}") import traceback traceback.print_exc()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/92_integrations/observability/workflows/langfuse_via_openinference_workflows.py", "license": "Apache License 2.0", "lines": 112, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/92_integrations/rag/agentic_rag_infinity_reranker.py
""" Agentic Rag Infinity Reranker ============================= Demonstrates agentic RAG with an Infinity reranker backend (relocated integration example). """ import asyncio import importlib from agno.agent import Agent from agno.knowledge.embedder.cohere import CohereEmbedder from agno.knowledge.knowledge import Knowledge from agno.knowledge.reranker.infinity import InfinityReranker from agno.models.anthropic import Claude from agno.vectordb.lancedb import LanceDb, SearchType # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- knowledge = Knowledge( # Use LanceDB as the vector database, store embeddings in the `agno_docs_infinity` table vector_db=LanceDb( uri="tmp/lancedb", table_name="agno_docs_infinity", search_type=SearchType.hybrid, embedder=CohereEmbedder(id="embed-v4.0"), # Use Infinity reranker for local, fast reranking reranker=InfinityReranker( model="BAAI/bge-reranker-base", # You can change this to other models host="localhost", port=7997, top_n=5, # Return top 5 reranked documents ), ), ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- agent = Agent( model=Claude(id="claude-3-7-sonnet-latest"), # Agentic RAG is enabled by default when `knowledge` is provided to the Agent. knowledge=knowledge, # search_knowledge=True gives the Agent the ability to search on demand # search_knowledge is True by default search_knowledge=True, instructions=[ "Include sources in your response.", "Always search your knowledge before answering the question.", "Provide detailed and accurate information based on the retrieved documents.", ], markdown=True, ) def test_infinity_connection(): """Test if Infinity server is running and accessible""" try: infinity_client = importlib.import_module("infinity_client") _ = infinity_client.Client(base_url="http://localhost:7997") print("[OK] Successfully connected to Infinity server at localhost:7997") return True except Exception as e: print(f"[ERROR] Failed to connect to Infinity server: {e}") print( "\nPlease make sure Infinity server is running. See setup instructions above." ) return False # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": print("Agentic RAG with Infinity Reranker Example") print("=" * 50) # Load knowledge base print("\nLoading knowledge base...") asyncio.run( knowledge.ainsert_many( urls=[ "https://docs.agno.com/agents/overview.md", "https://docs.agno.com/tools/overview.md", "https://docs.agno.com/knowledge/overview.md", ] ) ) # Test Infinity connection first if not test_infinity_connection(): exit(1) print("\nStarting agent interaction...") print("=" * 50) # Example questions to test the reranking capabilities questions = [ "What are Agents and how do they work?", "How do I use tools with agents?", "What is the difference between knowledge and tools?", ] for i, question in enumerate(questions, 1): print(f"\n[Question {i}] {question}") print("-" * 40) agent.print_response(question, stream=True) print("\n" + "=" * 50) print("\nExample completed!") print("\nThe Infinity reranker helped improve the relevance of retrieved documents") print("by reranking them based on semantic similarity to your queries.")
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/92_integrations/rag/agentic_rag_infinity_reranker.py", "license": "Apache License 2.0", "lines": 98, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/92_integrations/rag/agentic_rag_with_lightrag.py
""" Agentic Rag With Lightrag ============================= Demonstrates an agentic RAG flow backed by LightRAG (relocated integration example). """ import asyncio from os import getenv from agno.agent import Agent from agno.knowledge.knowledge import Knowledge from agno.knowledge.reader.wikipedia_reader import WikipediaReader from agno.vectordb.lightrag import LightRag # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- vector_db = LightRag(api_key=getenv("LIGHTRAG_API_KEY")) knowledge = Knowledge( name="My LightRag Knowledge Base", description="Knowledge base using a LightRag vector database", vector_db=vector_db, ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- agent = Agent( knowledge=knowledge, search_knowledge=True, read_chat_history=False, ) # --------------------------------------------------------------------------- # Run Agent # --------------------------------------------------------------------------- if __name__ == "__main__": asyncio.run( knowledge.ainsert( name="Recipes", path="cookbook/07_knowledge/testing_resources/cv_1.pdf", metadata={"doc_type": "recipe_book"}, ) ) asyncio.run( knowledge.ainsert( name="Recipes", topics=["Manchester United"], reader=WikipediaReader(), ) ) asyncio.run( knowledge.ainsert( name="Recipes", url="https://en.wikipedia.org/wiki/Manchester_United_F.C.", ) ) asyncio.run( agent.aprint_response("What skills does Jordan Mitchell have?", markdown=True) ) asyncio.run( agent.aprint_response( "In what year did Manchester United change their name?", markdown=True ) )
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/92_integrations/rag/agentic_rag_with_lightrag.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/92_integrations/surrealdb/custom_memory_instructions.py
""" SurrealDB Custom Memory Instructions """ from agno.db.surrealdb import SurrealDb from agno.memory import MemoryManager from agno.models.anthropic.claude import Claude from agno.models.message import Message from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- SURREALDB_URL = "ws://localhost:8000" SURREALDB_USER = "root" SURREALDB_PASSWORD = "root" SURREALDB_NAMESPACE = "agno" SURREALDB_DATABASE = "memories" creds = {"username": SURREALDB_USER, "password": SURREALDB_PASSWORD} memory_db = SurrealDb( None, SURREALDB_URL, creds, SURREALDB_NAMESPACE, SURREALDB_DATABASE ) # --------------------------------------------------------------------------- # Create Memory Managers # --------------------------------------------------------------------------- john_doe_id = "john_doe@example.com" custom_memory_manager = MemoryManager( model=OpenAIChat(id="gpt-4o"), memory_capture_instructions="""\ Memories should only include details about the user's academic interests. Only include which subjects they are interested in. Ignore names, hobbies, and personal interests. """, db=memory_db, ) # Use default memory manager jane_memory_manager = MemoryManager( model=Claude(id="claude-3-5-sonnet-latest"), db=memory_db, ) # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- def run_example() -> None: custom_memory_manager.create_user_memories( message="""\ My name is John Doe. I enjoy hiking in the mountains on weekends, reading science fiction novels before bed, cooking new recipes from different cultures, playing chess with friends. I am interested to learn about the history of the universe and other astronomical topics. """, user_id=john_doe_id, ) memories = custom_memory_manager.get_user_memories(user_id=john_doe_id) print("John Doe's memories:") pprint(memories) jane_doe_id = "jane_doe@example.com" # Send a history of messages and add memories jane_memory_manager.create_user_memories( messages=[ Message(role="user", content="Hi, how are you?"), Message(role="assistant", content="I'm good, thank you!"), Message(role="user", content="What are you capable of?"), Message( role="assistant", content="I can help you with your homework and answer questions about the universe.", ), Message(role="user", content="My name is Jane Doe"), Message(role="user", content="I like to play chess"), Message( role="user", content="Actually, forget that I like to play chess. I more enjoy playing table top games like dungeons and dragons", ), Message( role="user", content="I'm also interested in learning about the history of the universe and other astronomical topics.", ), Message(role="assistant", content="That is great!"), Message( role="user", content="I am really interested in physics. Tell me about quantum mechanics?", ), ], user_id=jane_doe_id, ) memories = jane_memory_manager.get_user_memories(user_id=jane_doe_id) print("Jane Doe's memories:") pprint(memories) if __name__ == "__main__": run_example()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/92_integrations/surrealdb/custom_memory_instructions.py", "license": "Apache License 2.0", "lines": 91, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/92_integrations/surrealdb/db_tools_control.py
""" SurrealDB Memory DB Tools Control """ from agno.agent.agent import Agent from agno.db.surrealdb import SurrealDb from agno.memory.manager import MemoryManager from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- SURREALDB_URL = "ws://localhost:8000" SURREALDB_USER = "root" SURREALDB_PASSWORD = "root" SURREALDB_NAMESPACE = "agno" SURREALDB_DATABASE = "memories" creds = {"username": SURREALDB_USER, "password": SURREALDB_PASSWORD} memory_db = SurrealDb( None, SURREALDB_URL, creds, SURREALDB_NAMESPACE, SURREALDB_DATABASE ) # --------------------------------------------------------------------------- # Create Agent # --------------------------------------------------------------------------- john_doe_id = "john_doe@example.com" memory_manager_full = MemoryManager( model=OpenAIChat(id="gpt-4o"), db=memory_db, add_memories=True, update_memories=True, ) agent_full = Agent( model=OpenAIChat(id="gpt-4o"), memory_manager=memory_manager_full, enable_agentic_memory=True, db=memory_db, ) # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- def run_example() -> None: # Add initial memory agent_full.print_response( "My name is John Doe and I like to hike in the mountains on weekends. I also enjoy photography.", stream=True, user_id=john_doe_id, ) # Test memory recall agent_full.print_response("What are my hobbies?", stream=True, user_id=john_doe_id) # Test memory update agent_full.print_response( "I no longer enjoy photography. Instead, I've taken up rock climbing.", stream=True, user_id=john_doe_id, ) print("\nMemories after update:") memories = memory_manager_full.get_user_memories(user_id=john_doe_id) pprint([m.memory for m in memories] if memories else []) if __name__ == "__main__": run_example()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/92_integrations/surrealdb/db_tools_control.py", "license": "Apache License 2.0", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/92_integrations/surrealdb/memory_creation.py
""" SurrealDB Memory Creation """ from agno.db.surrealdb import SurrealDb from agno.memory import MemoryManager, UserMemory from agno.models.message import Message from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- SURREALDB_URL = "ws://localhost:8000" SURREALDB_USER = "root" SURREALDB_PASSWORD = "root" SURREALDB_NAMESPACE = "agno" SURREALDB_DATABASE = "memories" creds = {"username": SURREALDB_USER, "password": SURREALDB_PASSWORD} memory_db = SurrealDb( None, SURREALDB_URL, creds, SURREALDB_NAMESPACE, SURREALDB_DATABASE ) # --------------------------------------------------------------------------- # Create Memory Manager # --------------------------------------------------------------------------- memory = MemoryManager(model=OpenAIChat(id="gpt-4o"), db=memory_db) # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- def run_example() -> None: john_doe_id = "john_doe@example.com" memory.add_user_memory( memory=UserMemory( memory=""" I enjoy hiking in the mountains on weekends, reading science fiction novels before bed, cooking new recipes from different cultures, playing chess with friends, and attending live music concerts whenever possible. Photography has become a recent passion of mine, especially capturing landscapes and street scenes. I also like to meditate in the mornings and practice yoga to stay centered. """ ), user_id=john_doe_id, ) memories = memory.get_user_memories(user_id=john_doe_id) print("John Doe's memories:") pprint(memories) jane_doe_id = "jane_doe@example.com" # Send a history of messages and add memories memory.create_user_memories( messages=[ Message(role="user", content="My name is Jane Doe"), Message(role="assistant", content="That is great!"), Message(role="user", content="I like to play chess"), Message(role="assistant", content="That is great!"), ], user_id=jane_doe_id, ) memories = memory.get_user_memories(user_id=jane_doe_id) print("Jane Doe's memories:") pprint(memories) if __name__ == "__main__": run_example()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/92_integrations/surrealdb/memory_creation.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/92_integrations/surrealdb/memory_search_surreal.py
""" SurrealDB Memory Search """ from agno.db.surrealdb import SurrealDb from agno.memory import MemoryManager, UserMemory from agno.models.openai import OpenAIChat from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- SURREALDB_URL = "ws://localhost:8000" SURREALDB_USER = "root" SURREALDB_PASSWORD = "root" SURREALDB_NAMESPACE = "agno" SURREALDB_DATABASE = "memories" creds = {"username": SURREALDB_USER, "password": SURREALDB_PASSWORD} db = SurrealDb(None, SURREALDB_URL, creds, SURREALDB_NAMESPACE, SURREALDB_DATABASE) # --------------------------------------------------------------------------- # Create Memory Manager # --------------------------------------------------------------------------- memory = MemoryManager(model=OpenAIChat(id="gpt-4o"), db=db) # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- def run_example() -> None: john_doe_id = "john_doe@example.com" memory.add_user_memory( memory=UserMemory(memory="The user enjoys hiking in the mountains on weekends"), user_id=john_doe_id, ) memory.add_user_memory( memory=UserMemory( memory="The user enjoys reading science fiction novels before bed" ), user_id=john_doe_id, ) print("John Doe's memories:") pprint(memory.get_user_memories(user_id=john_doe_id)) memories = memory.search_user_memories( user_id=john_doe_id, limit=1, retrieval_method="last_n" ) print("\nJohn Doe's last_n memories:") pprint(memories) memories = memory.search_user_memories( user_id=john_doe_id, limit=1, retrieval_method="first_n" ) print("\nJohn Doe's first_n memories:") pprint(memories) memories = memory.search_user_memories( user_id=john_doe_id, query="What does the user like to do on weekends?", retrieval_method="agentic", ) print("\nJohn Doe's memories similar to the query (agentic):") pprint(memories) if __name__ == "__main__": run_example()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/92_integrations/surrealdb/memory_search_surreal.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:cookbook/92_integrations/surrealdb/standalone_memory_surreal.py
""" Standalone SurrealDB Memory Operations """ from agno.db.surrealdb import SurrealDb from agno.memory import MemoryManager, UserMemory from rich.pretty import pprint # --------------------------------------------------------------------------- # Setup # --------------------------------------------------------------------------- SURREALDB_URL = "ws://localhost:8000" SURREALDB_USER = "root" SURREALDB_PASSWORD = "root" SURREALDB_NAMESPACE = "agno" SURREALDB_DATABASE = "memories" creds = {"username": SURREALDB_USER, "password": SURREALDB_PASSWORD} db = SurrealDb(None, SURREALDB_URL, creds, SURREALDB_NAMESPACE, SURREALDB_DATABASE) # --------------------------------------------------------------------------- # Create Memory Manager # --------------------------------------------------------------------------- memory = MemoryManager(db=db) # --------------------------------------------------------------------------- # Run Example # --------------------------------------------------------------------------- def run_example() -> None: # Add a memory for the default user memory.add_user_memory( memory=UserMemory(memory="The user's name is John Doe", topics=["name"]), ) print("Memories:") pprint(memory.get_user_memories()) # Add memories for Jane Doe jane_doe_id = "jane_doe@example.com" print(f"\nUser: {jane_doe_id}") memory_id_1 = memory.add_user_memory( memory=UserMemory(memory="The user's name is Jane Doe", topics=["name"]), user_id=jane_doe_id, ) memory_id_2 = memory.add_user_memory( memory=UserMemory(memory="She likes to play tennis", topics=["hobbies"]), user_id=jane_doe_id, ) memories = memory.get_user_memories(user_id=jane_doe_id) print("Memories:") pprint(memories) # Delete a memory print("\nDeleting memory") assert memory_id_2 is not None memory.delete_user_memory(user_id=jane_doe_id, memory_id=memory_id_2) print("Memory deleted\n") memories = memory.get_user_memories(user_id=jane_doe_id) print("Memories:") pprint(memories) # Replace a memory print("\nReplacing memory") assert memory_id_1 is not None memory.replace_user_memory( memory_id=memory_id_1, memory=UserMemory(memory="The user's name is Jane Mary Doe", topics=["name"]), user_id=jane_doe_id, ) print("Memory replaced") memories = memory.get_user_memories(user_id=jane_doe_id) print("Memories:") pprint(memories) if __name__ == "__main__": run_example()
{ "repo_id": "agno-agi/agno", "file_path": "cookbook/92_integrations/surrealdb/standalone_memory_surreal.py", "license": "Apache License 2.0", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple