100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.
feat: Add OpenAI Agents SDK Crash Course
Shubhamsabooedf042f10b8d
diff --git a/README.md b/README.mdindex 779aadd2..bfa8581a 100644--- a/README.md+++ b/README.md@@ -49,7 +49,7 @@ A curated collection of **Awesome LLM apps built with RAG, AI Agents, Multi-agen<tr><td align="center"><a href="https://getunblocked.com/unblocked-mcp/?utm_source=oss&utm_medium=sponsorship&utm_campaign=awesome-llm-apps" target="_blank" rel="noopener" title="Unblocked">- <img src="docs/banner/sponsors/unblocked.png" alt="Unblocked" width="450">+ <img src="docs/banner/sponsors/unblocked.png" alt="Unblocked" width="6000"></a><br><a href="https://getunblocked.com/unblocked-mcp/?utm_source=oss&utm_medium=sponsorship&utm_campaign=awesome-llm-apps" target="_blank" rel="noopener" style="text-decoration: none; color: #333; font-weight: bold; font-size: 18px;">@@ -58,7 +58,7 @@ A curated collection of **Awesome LLM apps built with RAG, AI Agents, Multi-agen</td><td align="center"><a href="https://sponsorunwindai.com/" title="Sponsor Awesome LLM Apps Repo">- <img src="docs/banner/sponsor_awesome_llm_apps.png" alt="Sponsor Awesome LLM Apps Repo" width="450">+ <img src="docs/banner/sponsor_awesome_llm_apps.png" alt="Sponsor Awesome LLM Apps Repo" width="6000"></a><br><a href="https://sponsorunwindai.com/" style="text-decoration: none; color: #333; font-weight: bold; font-size: 18px;">@@ -180,6 +180,7 @@ A curated collection of **Awesome LLM apps built with RAG, AI Agents, Multi-agen* [π§ Llama 3.2 Fine-tuning](advanced_llm_apps/llm_finetuning_tutorials/llama3.2_finetuning/)+### π§βπ« AI Agent Framework Crash Course- [Google ADK Crash Course](ai_agent_framework_crash_course/google_adk_crash_course/)@@ -189,6 +190,13 @@ A curated collection of **Awesome LLM apps built with RAG, AI Agents, Multi-agen- Memory; callbacks; Plugins- Simple multiβagent; Multiβagent patterns+- [OpenAI Agents SDK Crash Course](ai_agent_framework_crash_course/openai_sdk_crash_course/)+ - Starter agent; function calling; structured outputs+ - Tools: builtβin, function, thirdβparty integrations+ - Memory; callbacks; evaluation+ - Multiβagent patterns; agent handoffs+ - Swarm orchestration; routing logic+## π Getting Started1. **Clone the repository**diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/README.mdnew file mode 100644index 00000000..61cf5dfe--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/README.md@@ -0,0 +1,105 @@+# Default Tracing++Demonstrates the built-in automatic tracing system that captures all agent workflow events without any setup required.++## π― What This Demonstrates++- **Automatic Tracing**: Built-in workflow monitoring (enabled by default)+- **Trace IDs**: Unique identifiers for each agent run+- **OpenAI Dashboard**: Free trace visualization platform+- **Tracing Configuration**: Enabling and disabling trace capture++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import main++ # Test default tracing (automatic)+ asyncio.run(main())+ ```++## π‘ Key Concepts++- **Zero Setup Required**: Tracing works automatically out of the box+- **Unique Run IDs**: Each `Runner.run()` gets a unique trace identifier+- **Automatic Capture**: LLM calls, tool executions, performance metrics+- **Free Dashboard**: View traces at platform.openai.com/traces++## π§ͺ Automatic Capture++### What Gets Traced Automatically+- **LLM Generations**: Input prompts, model responses, token usage+- **Tool Calls**: Function executions, parameters, results+- **Handoffs**: Agent-to-agent delegations+- **Performance**: Execution time, latency metrics+- **Errors**: Exceptions and failure modes++### Trace Information+```python+result = await Runner.run(agent, "Hello")+print(f"Trace ID: {result.run_id}")+# Each run gets a unique identifier for dashboard lookup+```++### Separate Traces+- Each `Runner.run()` call = One trace+- Multiple runs = Multiple separate traces+- Independent workflow tracking++## π» Tracing Examples++### Basic Automatic Tracing+```python+# Tracing happens automatically - no setup required!+result = await Runner.run(agent, "Explain machine learning")+print(f"View trace: https://platform.openai.com/traces/{result.run_id}")+```++### Tracing Configuration+```python+# Disable tracing for specific runs+result = await Runner.run(+ agent,+ "Private conversation",+ run_config=RunConfig(tracing_disabled=True)+)+```++### Multiple Traces+```python+# Each run creates a separate trace+result1 = await Runner.run(agent, "Question 1") # Trace 1+result2 = await Runner.run(agent, "Question 2") # Trace 2+```++## π Dashboard Features++### OpenAI Traces Dashboard+- **Workflow Timeline**: Visual execution flow+- **Performance Metrics**: Response times, token usage+- **Error Tracking**: Exception details and stack traces+- **Content Inspection**: Input/output content review++### Free Access+- No additional setup required+- Accessible with OpenAI API key+- Real-time trace availability+- Historical trace retention++## π Next Steps++- [Custom Tracing](../10_2_custom_tracing/README.md) - Advanced tracing patterns+- [Tutorial 11: Production Patterns](../../11_production_patterns/README.md) - Real-world deploymentdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/__init__.pynew file mode 100644index 00000000..f9b475d0--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/__init__.py@@ -0,0 +1 @@+# Default Tracing module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/agent.pynew file mode 100644index 00000000..8d2cfd8f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/agent.py@@ -0,0 +1,132 @@+from agents import Agent, Runner+import asyncio++# Create agent for tracing demonstrations+root_agent = Agent(+ name="Tracing Demo Agent",+ instructions="""+ You are a helpful assistant demonstrating tracing capabilities.++ Respond concisely but perform actions that generate interesting trace data.+ """+)++# Example 1: Basic automatic tracing+async def basic_automatic_tracing():+ """Demonstrates default tracing that happens automatically"""++ print("=== Basic Automatic Tracing ===")+ print("Tracing is enabled by default - no setup required!")+ print("View traces at: https://platform.openai.com/traces")++ # Single agent run - creates one trace automatically+ result = await Runner.run(+ root_agent,+ "Explain what tracing means in software development."+ )++ print(f"Response: {result.final_output}")+ print(f"Trace ID: {result.run_id}") # Each run gets a unique ID+ print("Check the OpenAI Traces dashboard to see this execution!")++ return result++# Example 2: Multiple runs create separate traces+async def multiple_separate_traces():+ """Shows how separate runs create individual traces"""++ print("\n=== Multiple Separate Traces ===")+ print("Each Runner.run() call creates a separate trace")++ # First trace+ result1 = await Runner.run(+ root_agent,+ "What are the benefits of monitoring software?"+ )+ print(f"Trace 1 ID: {result1.run_id}")++ # Second trace (separate from first)+ result2 = await Runner.run(+ root_agent,+ "How do you debug performance issues?"+ )+ print(f"Trace 2 ID: {result2.run_id}")++ print("Two separate traces created - each with its own workflow view")++ return result1, result2++# Example 3: Understanding trace structure+async def trace_structure_demo():+ """Demonstrates what gets captured in traces"""++ print("\n=== Trace Structure Demo ===")+ print("Each trace automatically captures:")+ print("β’ LLM generations (input/output)")+ print("β’ Execution time and performance")+ print("β’ Any errors or exceptions")+ print("β’ Metadata and context")++ # Create a run that will generate rich trace data+ result = await Runner.run(+ root_agent,+ "List 3 key components of observability and explain each briefly."+ )++ print(f"Response generated: {len(result.final_output)} characters")+ print(f"Trace contains rich data for run: {result.run_id}")++ # Show what type of information is captured+ print("\nIn the trace dashboard, you'll see:")+ print("1. Workflow timeline with duration")+ print("2. LLM generation details (model, tokens, etc.)")+ print("3. Input/output content and metadata")+ print("4. Performance metrics and execution flow")++ return result++# Example 4: Tracing configuration options+async def tracing_configuration():+ """Shows how to configure tracing behavior"""++ print("\n=== Tracing Configuration ===")++ # Example of disabling tracing for specific run+ from agents.run import RunConfig++ print("Running with tracing disabled...")+ result_no_trace = await Runner.run(+ root_agent,+ "This run won't be traced.",+ run_config=RunConfig(tracing_disabled=True)+ )++ print(f"Run completed without tracing: {result_no_trace.run_id}")+ print("(This run won't appear in traces dashboard)")++ print("\nRunning with normal tracing...")+ result_with_trace = await Runner.run(+ root_agent,+ "This run will be traced normally."+ )++ print(f"Run completed with tracing: {result_with_trace.run_id}")+ print("(This run will appear in traces dashboard)")++ return result_no_trace, result_with_trace++# Main execution+async def main():+ print("π OpenAI Agents SDK - Tracing Basics")+ print("=" * 50)++ await basic_automatic_tracing()+ await multiple_separate_traces()+ await trace_structure_demo()+ await tracing_configuration()++ print("\nβ Tracing tutorial complete!")+ print("Visit https://platform.openai.com/traces to explore your traces")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/README.mdnew file mode 100644index 00000000..cf33fcd6--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/README.md@@ -0,0 +1,141 @@+# Custom Tracing++Demonstrates advanced tracing patterns including custom traces, spans, and workflow organization for complex multi-agent systems.++## π― What This Demonstrates++- **Custom Traces**: Grouping multiple agent runs in single workflows+- **Custom Spans**: Adding business logic monitoring points+- **Hierarchical Tracking**: Nested spans for complex operations+- **Trace Metadata**: Organizing traces with groups and metadata++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import main++ # Test custom tracing patterns+ asyncio.run(main())+ ```++## π‘ Key Concepts++- **trace() Context Manager**: Creating custom workflow groupings+- **custom_span()**: Adding business logic monitoring+- **Trace Metadata**: Workflow naming and organization+- **Hierarchical Structure**: Nested spans for complex operations++## π§ͺ Custom Tracing Patterns++### Multi-Step Workflow Traces+```python+with trace("Research and Analysis Workflow") as workflow_trace:+ # Step 1: Research+ research_result = await Runner.run(research_agent, "Research AI in healthcare")++ # Step 2: Analysis+ analysis_result = await Runner.run(analysis_agent, f"Analyze: {research_result.final_output}")++ # Step 3: Summary+ summary_result = await Runner.run(analysis_agent, f"Summarize: {analysis_result.final_output}")+```++### Custom Business Logic Spans+```python+with trace("Document Processing Workflow") as doc_trace:++ with custom_span("Data Preparation") as prep_span:+ # Your business logic here+ data = prepare_data()+ prep_span.add_event("Data loaded", {"records": 100})+ prep_span.add_event("Data validated", {"errors": 0})++ with custom_span("AI Processing") as ai_span:+ result = await Runner.run(agent, "Process the data")+ ai_span.add_event("Processing complete", {+ "output_length": len(result.final_output)+ })+```++### Hierarchical Spans+```python+with trace("E-commerce Order Processing") as order_trace:++ with custom_span("Order Validation") as validation_span:++ # Nested span for inventory check+ with custom_span("Inventory Check") as inventory_span:+ inventory_span.add_event("Stock verified", {"available": True})++ # Nested span for payment validation+ with custom_span("Payment Validation") as payment_span:+ payment_span.add_event("Payment authorized", {"amount": 99.99})+```++## π» Advanced Features++### Trace Metadata and Grouping+```python+conversation_id = "conv_12345"++# First interaction in conversation+with trace(+ "Customer Support - Initial Inquiry",+ group_id=conversation_id,+ metadata={"customer_id": "cust_789", "priority": "high"}+) as trace1:+ result1 = await Runner.run(support_agent, "How do I reset my password?")++# Follow-up interaction in same conversation+with trace(+ "Customer Support - Follow-up",+ group_id=conversation_id,+ metadata={"customer_id": "cust_789", "interaction": 2}+) as trace2:+ result2 = await Runner.run(support_agent, f"Based on this context: {result1.final_output}")+```++### Event Tracking+```python+with custom_span("Business Process") as span:+ span.add_event("Process started", {"timestamp": datetime.now()})+ # Business logic here+ span.add_event("Milestone reached", {"progress": "50%"})+ # More business logic+ span.add_event("Process completed", {"status": "success"})+```++## π Benefits of Custom Tracing++### Workflow Organization+- **Group Related Operations**: Multiple agent runs in single trace+- **Business Logic Visibility**: Monitor custom processes alongside AI+- **Performance Analysis**: Track end-to-end workflow performance++### Production Monitoring+- **Error Correlation**: Link failures across multiple components+- **Performance Optimization**: Identify bottlenecks in complex workflows+- **User Journey Tracking**: Follow conversations across interactions++### Debugging and Analysis+- **Complex Workflow Understanding**: Visualize multi-step processes+- **Context Preservation**: Maintain relationship between related operations+- **Metadata Organization**: Filter and search traces by business criteria++## π Next Steps++- [Default Tracing](../10_1_default_tracing/README.md) - Basic tracing fundamentals+- [Tutorial 11: Production Patterns](../../11_production_patterns/README.md) - Real-world deploymentdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/__init__.pynew file mode 100644index 00000000..f7a8d743--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/__init__.py@@ -0,0 +1 @@+# Custom Tracing module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/agent.pynew file mode 100644index 00000000..6d8b698c--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/agent.py@@ -0,0 +1,188 @@+from agents import Agent, Runner, trace, custom_span+import asyncio++# Create agents for custom tracing demonstrations+research_agent = Agent(+ name="Research Agent",+ instructions="You are a research assistant. Provide concise, factual information."+)++analysis_agent = Agent(+ name="Analysis Agent",+ instructions="You analyze information and provide insights."+)++# Example 1: Custom trace for multi-step workflow+async def multi_step_workflow_trace():+ """Demonstrates grouping multiple agent runs in a single trace"""++ print("=== Multi-Step Workflow Trace ===")++ # Create custom trace that groups multiple operations+ with trace("Research and Analysis Workflow") as workflow_trace:+ print("Starting research phase...")++ # Step 1: Research+ research_result = await Runner.run(+ research_agent,+ "What are the key benefits of artificial intelligence in healthcare?"+ )+ print(f"Research complete: {len(research_result.final_output)} characters")++ # Step 2: Analysis+ analysis_result = await Runner.run(+ analysis_agent,+ f"Analyze this research and identify the top 3 benefits: {research_result.final_output}"+ )+ print(f"Analysis complete: {len(analysis_result.final_output)} characters")++ # Step 3: Summary+ summary_result = await Runner.run(+ analysis_agent,+ f"Create a brief executive summary of these findings: {analysis_result.final_output}"+ )+ print(f"Summary complete: {len(summary_result.final_output)} characters")++ print(f"Workflow trace created: {workflow_trace.trace_id}")+ print("All three agent runs are grouped in a single trace!")++ return research_result, analysis_result, summary_result++# Example 2: Custom spans for business logic+async def custom_spans_demo():+ """Shows how to add custom spans for monitoring business logic"""++ print("\n=== Custom Spans Demo ===")++ with trace("Document Processing Workflow") as doc_trace:++ # Custom span for data preparation+ with custom_span("Data Preparation") as prep_span:+ print("Preparing data...")+ # Simulate data processing+ await asyncio.sleep(0.1)+ prep_span.add_event("Data loaded", {"records": 100})+ prep_span.add_event("Data validated", {"errors": 0})++ # Custom span for agent processing+ with custom_span("AI Processing") as ai_span:+ print("Processing with AI...")+ result = await Runner.run(+ research_agent,+ "Summarize the importance of data quality in AI systems."+ )+ ai_span.add_event("Processing complete", {+ "output_length": len(result.final_output),+ "model_used": "gpt-4o"+ })++ # Custom span for post-processing+ with custom_span("Post Processing") as post_span:+ print("Post-processing results...")+ await asyncio.sleep(0.1)+ post_span.add_event("Results formatted", {"format": "text"})+ post_span.add_event("Quality check passed", {"score": 0.95})++ print(f"Document processing trace: {doc_trace.trace_id}")+ print("Custom spans provide detailed workflow visibility!")++ return result++# Example 3: Hierarchical spans+async def hierarchical_spans():+ """Demonstrates nested spans for complex workflows"""++ print("\n=== Hierarchical Spans ===")++ with trace("E-commerce Order Processing") as order_trace:++ with custom_span("Order Validation") as validation_span:+ print("Validating order...")++ # Nested span for inventory check+ with custom_span("Inventory Check") as inventory_span:+ await asyncio.sleep(0.05)+ inventory_span.add_event("Stock verified", {"available": True})++ # Nested span for payment validation+ with custom_span("Payment Validation") as payment_span:+ await asyncio.sleep(0.05)+ payment_span.add_event("Payment authorized", {"amount": 99.99})++ validation_span.add_event("Order validated", {"order_id": "ORD-12345"})++ with custom_span("AI Recommendation Generation") as rec_span:+ print("Generating recommendations...")+ result = await Runner.run(+ research_agent,+ "What are good complementary products for a wireless headset purchase?"+ )+ rec_span.add_event("Recommendations generated", {+ "count": 3,+ "confidence": 0.89+ })++ with custom_span("Order Completion") as completion_span:+ print("Completing order...")+ completion_span.add_event("Shipping scheduled", {"tracking": "TRK-789"})+ completion_span.add_event("Email sent", {"type": "confirmation"})++ print(f"E-commerce order trace: {order_trace.trace_id}")+ print("Hierarchical spans show detailed operation breakdown!")++ return result++# Example 4: Trace metadata and grouping+async def trace_metadata_demo():+ """Shows how to use trace metadata and grouping"""++ print("\n=== Trace Metadata and Grouping ===")++ # Create multiple traces with shared group ID+ conversation_id = "conv_12345"++ # First interaction in conversation+ with trace(+ "Customer Support - Initial Inquiry",+ group_id=conversation_id,+ metadata={"customer_id": "cust_789", "priority": "high"}+ ) as trace1:+ result1 = await Runner.run(+ research_agent,+ "How do I reset my password?"+ )+ trace1.add_event("Initial inquiry processed", {"category": "password_reset"})++ # Follow-up interaction in same conversation+ with trace(+ "Customer Support - Follow-up",+ group_id=conversation_id,+ metadata={"customer_id": "cust_789", "interaction": 2}+ ) as trace2:+ result2 = await Runner.run(+ analysis_agent,+ f"Based on this password reset request, what additional security measures should we recommend? Context: {result1.final_output}"+ )+ trace2.add_event("Follow-up completed", {"recommendations_provided": True})++ print(f"Conversation traces: {trace1.trace_id}, {trace2.trace_id}")+ print(f"Grouped under conversation: {conversation_id}")+ print("Metadata helps organize and filter traces in dashboard!")++ return result1, result2++# Main execution+async def main():+ print("π¨ OpenAI Agents SDK - Custom Tracing")+ print("=" * 50)++ await multi_step_workflow_trace()+ await custom_spans_demo()+ await hierarchical_spans()+ await trace_metadata_demo()++ print("\nβ Custom tracing tutorial complete!")+ print("Check the OpenAI Traces dashboard to see your custom workflow visualizations")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_2_custom_tracing/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/README.mdnew file mode 100644index 00000000..3cf22080--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/README.md@@ -0,0 +1,209 @@+# π Tutorial 8: Tracing & Observability++Master monitoring and debugging with built-in tracing! This tutorial teaches you how to use the OpenAI Agents SDK's comprehensive tracing system to visualize, debug, and monitor your agent workflows during development and production.++## π― What You'll Learn++- **Built-in Tracing**: Automatic capture of LLM generations, tool calls, handoffs+- **Traces & Spans**: Understanding workflow structure and execution flow+- **Custom Tracing**: Creating custom traces and spans for complex workflows+- **Production Monitoring**: Debugging and performance optimization++## π§ Core Concept: What Is Tracing?++Tracing provides **comprehensive workflow monitoring** that automatically captures every event during agent execution:++- **LLM Generations**: Model calls, inputs, outputs, and performance+- **Tool Calls**: Function executions, parameters, and results+- **Handoffs**: Agent-to-agent delegations and context transfer+- **Guardrails**: Input/output validation events+- **Custom Events**: Your own monitoring points++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β TRACING ARCHITECTURE β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β AGENT WORKFLOW β+β β β+β βΌ β+β βββββββββββββββ AUTOMATIC CAPTURE β+β β TRACE ββββββββββββββββββββββββββββββββββββββββββββ β+β β (Workflow) β β β+β βββββββββββββββ β β+β β β β+β βΌ β β+β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β+β β SPAN β β SPAN β β SPAN β β β+β β (LLM Call) β β (Tool Call) β β (Handoff) β β β+β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β+β β β β β β+β βΌ βΌ βΌ β β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β+β β OPENAI TRACES DASHBOARD β β β+β β β’ Execution Visualization β β β+β β β’ Performance Metrics β β β+β β β’ Debug Information β β β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Tutorial Overview++This tutorial demonstrates **three key tracing patterns**:++### **1. Default Tracing** (`default_tracing.py`)+- Built-in automatic tracing (enabled by default)+- Understanding traces and spans structure+- Basic workflow monitoring++### **2. Custom Tracing** (`custom_tracing.py`)+- Creating custom traces for multi-step workflows+- Adding custom spans for monitoring points+- Grouping multiple agent runs in single trace++### **3. Advanced Observability** (`advanced_observability.py`)+- Sensitive data handling and configuration+- Custom trace processors for external systems+- Production monitoring patterns++## π Project Structure++```+8_tracing_observability/+βββ README.md # This file - concept explanation+βββ requirements.txt # Dependencies+βββ default_tracing.py # Built-in tracing basics (35 lines)+βββ custom_tracing.py # Custom traces and spans (45 lines)+βββ advanced_observability.py # Production tracing patterns (40 lines)+βββ app.py # Streamlit tracing dashboard (optional)+βββ env.example # Environment variables template+```++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How built-in tracing captures agent workflow events+- β Difference between traces (workflows) and spans (operations)+- β Creating custom traces for complex multi-step workflows+- β Monitoring and debugging agent performance in production+- β Integrating with external observability systems++## π Getting Started++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Install dependencies**:+ ```bash+ pip install -r requirements.txt+ ```++2. **Set up environment variables**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Test default tracing**:+ ```bash+ python default_tracing.py+ ```++4. **Try custom tracing**:+ ```bash+ python custom_tracing.py+ ```++5. **Explore advanced patterns**:+ ```bash+ python advanced_observability.py+ ```++## π§ͺ Sample Use Cases++### Default Tracing+- Monitor basic agent workflows automatically+- Debug tool call failures and LLM generation issues+- Track performance metrics for optimization++### Custom Tracing+- Group related agent runs in complex workflows+- Add custom monitoring points in business logic+- Create hierarchical span structures for debugging++### Advanced Observability+- Configure sensitive data handling for compliance+- Export traces to external monitoring systems+- Set up production alerting and dashboards++## π§ Key Tracing Patterns++### 1. **Default Tracing (Automatic)**+```python+from agents import Agent, Runner++agent = Agent(name="Assistant")+# Tracing happens automatically - no setup required!+result = await Runner.run(agent, "Hello")+# View traces at: https://platform.openai.com/traces+```++### 2. **Custom Trace Creation**+```python+from agents import Agent, Runner, trace++with trace("Multi-step Workflow") as my_trace:+ result1 = await Runner.run(agent, "Step 1")+ result2 = await Runner.run(agent, "Step 2")+ # Both runs are part of the same trace+```++### 3. **Custom Spans**+```python+from agents import custom_span++with custom_span("Data Processing") as span:+ # Your custom logic here+ data = process_data()+ span.add_event("Processing complete", {"records": len(data)})+```++## π‘ Tracing Design Best Practices++1. **Meaningful Names**: Use descriptive trace and span names+2. **Logical Grouping**: Group related operations in single traces+3. **Custom Events**: Add key business events as custom spans+4. **Sensitive Data**: Configure data handling for compliance+5. **Performance Monitoring**: Track execution time and resource usage++## π¨ Important Notes++- **Enabled by Default**: Tracing is automatically enabled+- **Zero Data Retention**: Tracing unavailable for ZDR policy organizations+- **Free Dashboard**: View traces at OpenAI Traces dashboard+- **Disable if Needed**: Set `OPENAI_AGENTS_DISABLE_TRACING=1` to disable++## π Next Steps++After completing this tutorial, you'll be ready for:+- **[Tutorial 9: Handoffs & Delegation](../9_handoffs_delegation/README.md)** - Agent handoffs and task delegation+- **[Tutorial 10: Multi-Agent Orchestration](../10_multi_agent_orchestration/README.md)** - Complex multi-agent workflows+- **[Tutorial 11: Production Patterns](../11_production_patterns/README.md)** - Real-world deployment strategies++## π¨ Troubleshooting++- **No Traces Visible**: Check OpenAI API key and internet connectivity+- **Missing Spans**: Ensure operations are within trace context+- **Performance Issues**: Configure sensitive data filtering+- **ZDR Policy**: Tracing unavailable - disable or use custom processors++## π‘ Pro Tips++- **Start Simple**: Use default tracing first, add custom traces as needed+- **Strategic Naming**: Use consistent naming conventions for traces/spans+- **Monitor Performance**: Track execution time trends over time+- **External Integration**: Consider custom processors for your monitoring stack+- **Development vs Production**: Different tracing strategies for each environmentdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/custom_tracing.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/custom_tracing.pynew file mode 100644index 00000000..6d8b698c--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/custom_tracing.py@@ -0,0 +1,188 @@+from agents import Agent, Runner, trace, custom_span+import asyncio++# Create agents for custom tracing demonstrations+research_agent = Agent(+ name="Research Agent",+ instructions="You are a research assistant. Provide concise, factual information."+)++analysis_agent = Agent(+ name="Analysis Agent",+ instructions="You analyze information and provide insights."+)++# Example 1: Custom trace for multi-step workflow+async def multi_step_workflow_trace():+ """Demonstrates grouping multiple agent runs in a single trace"""++ print("=== Multi-Step Workflow Trace ===")++ # Create custom trace that groups multiple operations+ with trace("Research and Analysis Workflow") as workflow_trace:+ print("Starting research phase...")++ # Step 1: Research+ research_result = await Runner.run(+ research_agent,+ "What are the key benefits of artificial intelligence in healthcare?"+ )+ print(f"Research complete: {len(research_result.final_output)} characters")++ # Step 2: Analysis+ analysis_result = await Runner.run(+ analysis_agent,+ f"Analyze this research and identify the top 3 benefits: {research_result.final_output}"+ )+ print(f"Analysis complete: {len(analysis_result.final_output)} characters")++ # Step 3: Summary+ summary_result = await Runner.run(+ analysis_agent,+ f"Create a brief executive summary of these findings: {analysis_result.final_output}"+ )+ print(f"Summary complete: {len(summary_result.final_output)} characters")++ print(f"Workflow trace created: {workflow_trace.trace_id}")+ print("All three agent runs are grouped in a single trace!")++ return research_result, analysis_result, summary_result++# Example 2: Custom spans for business logic+async def custom_spans_demo():+ """Shows how to add custom spans for monitoring business logic"""++ print("\n=== Custom Spans Demo ===")++ with trace("Document Processing Workflow") as doc_trace:++ # Custom span for data preparation+ with custom_span("Data Preparation") as prep_span:+ print("Preparing data...")+ # Simulate data processing+ await asyncio.sleep(0.1)+ prep_span.add_event("Data loaded", {"records": 100})+ prep_span.add_event("Data validated", {"errors": 0})++ # Custom span for agent processing+ with custom_span("AI Processing") as ai_span:+ print("Processing with AI...")+ result = await Runner.run(+ research_agent,+ "Summarize the importance of data quality in AI systems."+ )+ ai_span.add_event("Processing complete", {+ "output_length": len(result.final_output),+ "model_used": "gpt-4o"+ })++ # Custom span for post-processing+ with custom_span("Post Processing") as post_span:+ print("Post-processing results...")+ await asyncio.sleep(0.1)+ post_span.add_event("Results formatted", {"format": "text"})+ post_span.add_event("Quality check passed", {"score": 0.95})++ print(f"Document processing trace: {doc_trace.trace_id}")+ print("Custom spans provide detailed workflow visibility!")++ return result++# Example 3: Hierarchical spans+async def hierarchical_spans():+ """Demonstrates nested spans for complex workflows"""++ print("\n=== Hierarchical Spans ===")++ with trace("E-commerce Order Processing") as order_trace:++ with custom_span("Order Validation") as validation_span:+ print("Validating order...")++ # Nested span for inventory check+ with custom_span("Inventory Check") as inventory_span:+ await asyncio.sleep(0.05)+ inventory_span.add_event("Stock verified", {"available": True})++ # Nested span for payment validation+ with custom_span("Payment Validation") as payment_span:+ await asyncio.sleep(0.05)+ payment_span.add_event("Payment authorized", {"amount": 99.99})++ validation_span.add_event("Order validated", {"order_id": "ORD-12345"})++ with custom_span("AI Recommendation Generation") as rec_span:+ print("Generating recommendations...")+ result = await Runner.run(+ research_agent,+ "What are good complementary products for a wireless headset purchase?"+ )+ rec_span.add_event("Recommendations generated", {+ "count": 3,+ "confidence": 0.89+ })++ with custom_span("Order Completion") as completion_span:+ print("Completing order...")+ completion_span.add_event("Shipping scheduled", {"tracking": "TRK-789"})+ completion_span.add_event("Email sent", {"type": "confirmation"})++ print(f"E-commerce order trace: {order_trace.trace_id}")+ print("Hierarchical spans show detailed operation breakdown!")++ return result++# Example 4: Trace metadata and grouping+async def trace_metadata_demo():+ """Shows how to use trace metadata and grouping"""++ print("\n=== Trace Metadata and Grouping ===")++ # Create multiple traces with shared group ID+ conversation_id = "conv_12345"++ # First interaction in conversation+ with trace(+ "Customer Support - Initial Inquiry",+ group_id=conversation_id,+ metadata={"customer_id": "cust_789", "priority": "high"}+ ) as trace1:+ result1 = await Runner.run(+ research_agent,+ "How do I reset my password?"+ )+ trace1.add_event("Initial inquiry processed", {"category": "password_reset"})++ # Follow-up interaction in same conversation+ with trace(+ "Customer Support - Follow-up",+ group_id=conversation_id,+ metadata={"customer_id": "cust_789", "interaction": 2}+ ) as trace2:+ result2 = await Runner.run(+ analysis_agent,+ f"Based on this password reset request, what additional security measures should we recommend? Context: {result1.final_output}"+ )+ trace2.add_event("Follow-up completed", {"recommendations_provided": True})++ print(f"Conversation traces: {trace1.trace_id}, {trace2.trace_id}")+ print(f"Grouped under conversation: {conversation_id}")+ print("Metadata helps organize and filter traces in dashboard!")++ return result1, result2++# Main execution+async def main():+ print("π¨ OpenAI Agents SDK - Custom Tracing")+ print("=" * 50)++ await multi_step_workflow_trace()+ await custom_spans_demo()+ await hierarchical_spans()+ await trace_metadata_demo()++ print("\nβ Custom tracing tutorial complete!")+ print("Check the OpenAI Traces dashboard to see your custom workflow visualizations")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/default_tracing.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/default_tracing.pynew file mode 100644index 00000000..8d2cfd8f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/default_tracing.py@@ -0,0 +1,132 @@+from agents import Agent, Runner+import asyncio++# Create agent for tracing demonstrations+root_agent = Agent(+ name="Tracing Demo Agent",+ instructions="""+ You are a helpful assistant demonstrating tracing capabilities.++ Respond concisely but perform actions that generate interesting trace data.+ """+)++# Example 1: Basic automatic tracing+async def basic_automatic_tracing():+ """Demonstrates default tracing that happens automatically"""++ print("=== Basic Automatic Tracing ===")+ print("Tracing is enabled by default - no setup required!")+ print("View traces at: https://platform.openai.com/traces")++ # Single agent run - creates one trace automatically+ result = await Runner.run(+ root_agent,+ "Explain what tracing means in software development."+ )++ print(f"Response: {result.final_output}")+ print(f"Trace ID: {result.run_id}") # Each run gets a unique ID+ print("Check the OpenAI Traces dashboard to see this execution!")++ return result++# Example 2: Multiple runs create separate traces+async def multiple_separate_traces():+ """Shows how separate runs create individual traces"""++ print("\n=== Multiple Separate Traces ===")+ print("Each Runner.run() call creates a separate trace")++ # First trace+ result1 = await Runner.run(+ root_agent,+ "What are the benefits of monitoring software?"+ )+ print(f"Trace 1 ID: {result1.run_id}")++ # Second trace (separate from first)+ result2 = await Runner.run(+ root_agent,+ "How do you debug performance issues?"+ )+ print(f"Trace 2 ID: {result2.run_id}")++ print("Two separate traces created - each with its own workflow view")++ return result1, result2++# Example 3: Understanding trace structure+async def trace_structure_demo():+ """Demonstrates what gets captured in traces"""++ print("\n=== Trace Structure Demo ===")+ print("Each trace automatically captures:")+ print("β’ LLM generations (input/output)")+ print("β’ Execution time and performance")+ print("β’ Any errors or exceptions")+ print("β’ Metadata and context")++ # Create a run that will generate rich trace data+ result = await Runner.run(+ root_agent,+ "List 3 key components of observability and explain each briefly."+ )++ print(f"Response generated: {len(result.final_output)} characters")+ print(f"Trace contains rich data for run: {result.run_id}")++ # Show what type of information is captured+ print("\nIn the trace dashboard, you'll see:")+ print("1. Workflow timeline with duration")+ print("2. LLM generation details (model, tokens, etc.)")+ print("3. Input/output content and metadata")+ print("4. Performance metrics and execution flow")++ return result++# Example 4: Tracing configuration options+async def tracing_configuration():+ """Shows how to configure tracing behavior"""++ print("\n=== Tracing Configuration ===")++ # Example of disabling tracing for specific run+ from agents.run import RunConfig++ print("Running with tracing disabled...")+ result_no_trace = await Runner.run(+ root_agent,+ "This run won't be traced.",+ run_config=RunConfig(tracing_disabled=True)+ )++ print(f"Run completed without tracing: {result_no_trace.run_id}")+ print("(This run won't appear in traces dashboard)")++ print("\nRunning with normal tracing...")+ result_with_trace = await Runner.run(+ root_agent,+ "This run will be traced normally."+ )++ print(f"Run completed with tracing: {result_with_trace.run_id}")+ print("(This run will appear in traces dashboard)")++ return result_no_trace, result_with_trace++# Main execution+async def main():+ print("π OpenAI Agents SDK - Tracing Basics")+ print("=" * 50)++ await basic_automatic_tracing()+ await multiple_separate_traces()+ await trace_structure_demo()+ await tracing_configuration()++ print("\nβ Tracing tutorial complete!")+ print("Visit https://platform.openai.com/traces to explore your traces")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/requirements.txtnew file mode 100644index 00000000..a88bde1d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/requirements.txt@@ -0,0 +1,3 @@+openai-agents>=1.0.0+streamlit>=1.28.0+python-dotenv>=1.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/README.mdnew file mode 100644index 00000000..d8e452a0--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/README.md@@ -0,0 +1,325 @@+# ποΈ Tutorial 11: Voice Agents++Master voice-enabled AI agents with the OpenAI Agents SDK! This tutorial demonstrates how to build conversational voice agents using speech-to-text, text-to-speech, and intelligent agent workflows for natural voice interactions.++## π― What You'll Learn++- **Voice Pipeline Architecture**: Complete speech β text β speech workflow+- **Static Voice Processing**: Turn-based voice interaction with recorded audio+- **Streaming Voice Processing**: Real-time voice conversation with live audio+- **Multi-Language Support**: Automatic language detection and agent handoffs+- **Voice-Optimized Tools**: Design tools specifically for voice interactions+- **Audio Management**: Recording, playback, and streaming audio utilities++## π§ Core Concept: Voice Agents++Voice agents combine the power of AI language models with speech processing to create natural conversational interfaces. Think of voice agents as **AI assistants you can talk to naturally** that:++- Listen to your speech and convert it to text+- Process your request with intelligent AI agents+- Use tools and make decisions like text-based agents+- Convert responses back to natural speech+- Handle multi-turn conversations seamlessly++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β VOICE AGENT SYSTEM β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β π€ USER SPEECH β+β β β+β βΌ β+β βββββββββββββββ 1. SPEECH-TO-TEXT β+β β AUDIO β β¦ Convert speech to text β+β β PIPELINE β β¦ Handle multiple languages β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 2. AGENT PROCESSING β+β β AGENT β β¦ Multi-agent workflows β+β β ECOSYSTEM β β¦ Tool calling & handoffs β+β βββββββββββββββ β¦ Context management β+β β β+β βΌ β+β βββββββββββββββ 3. TEXT-TO-SPEECH β+β β SPEECH β β¦ Convert response to speech β+β β SYNTHESIS β β¦ Natural voice output β+β βββββββββββββββ β+β β β+β βΌ β+β π AI RESPONSE β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Tutorial Overview++This tutorial demonstrates **three core voice interaction patterns**:++### **1. Static Voice Processing** (`static/`)+- **Turn-based interaction**: Record β Process β Respond+- **Complete audio processing**: Full utterance before processing+- **Simpler implementation**: Easier to understand and debug+- **Best for**: Voice commands, structured interactions++### **2. Streaming Voice Processing** (`streamed/`)+- **Real-time interaction**: Continuous listening and responding+- **Live audio streaming**: Process audio as it arrives+- **Activity detection**: Automatic speech start/stop detection+- **Best for**: Natural conversations, voice assistants++### **3. Realtime Voice Processing** (`realtime/`)+- **Ultra-low latency**: WebSocket-based persistent connections+- **Interruption handling**: Natural conversation interruptions+- **Realtime API**: OpenAI's newest voice technology+- **Best for**: Live conversations, minimal latency requirements++## π Project Structure++```+11_voice/+βββ README.md # This file - voice agents overview+βββ static/ # Static voice processing example+β βββ agent.py # Complete static voice agent+β βββ util.py # Audio recording and playback utilities+β βββ requirements.txt # Dependencies for static example+β βββ env.example # Environment variables+β βββ README.md # Static voice documentation+βββ streamed/ # Streaming voice processing example+β βββ agent.py # Real-time streaming voice agent+β βββ util.py # Streaming audio utilities+β βββ requirements.txt # Dependencies for streaming example+β βββ env.example # Environment variables+β βββ README.md # Streaming voice documentation+βββ realtime/ # Realtime voice processing example+β βββ agent.py # Basic realtime voice agent+β βββ requirements.txt # Dependencies for realtime example+β βββ env.example # Environment variables+β βββ README.md # Realtime voice documentation+βββ __init__.py # Module initialization+```++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How to build complete voice interaction pipelines+- β The difference between static and streaming voice processing+- β How to implement multi-language voice agents with handoffs+- β Best practices for voice-optimized agent design+- β Real-time audio processing and streaming techniques++## π Getting Started++### **Prerequisites**++1. **Install OpenAI Agents SDK with voice support**:+ ```bash+ pip install 'openai-agents[voice]'+ ```++2. **Install audio dependencies**:+ ```bash+ pip install sounddevice numpy soundfile librosa+ ```++3. **Set up environment variables**:+ ```bash+ cp static/env.example static/.env+ cp streamed/env.example streamed/.env+ # Edit .env files and add your OpenAI API key+ ```++### **Quick Start Options**++**Option 1: Static Voice (Recommended for beginners)**+```bash+cd static/+python agent.py+```++**Option 2: Streaming Voice (Advanced)**+```bash+cd streamed/+python agent.py+```++**Option 3: Realtime Voice (Ultra-low latency)**+```bash+cd realtime/+python agent.py+```++## π§ͺ Voice Agent Capabilities++### **Multi-Language Support**+Both examples include:+- **English Agent**: Primary assistant with full tool access+- **Spanish Agent**: Specialized Spanish-speaking assistant+- **French Agent**: Specialized French-speaking assistant+- **Automatic Language Detection**: Seamless handoffs based on detected language++### **Voice-Optimized Tools**+- `get_weather(city)`: Weather information with voice-friendly responses+- `get_time()`: Current time with natural speech output+- `calculate_tip(bill, percentage)`: Tip calculations for voice queries+- `set_reminder(message, minutes)`: Voice-activated reminders (streaming only)+- `get_news_summary()`: Voice-friendly news updates (streaming only)++### **Audio Processing Features**+- **High-Quality Recording**: 24kHz audio capture+- **Real-Time Playback**: Low-latency audio output+- **Activity Detection**: Automatic speech boundary detection (streaming)+- **Error Recovery**: Robust audio pipeline error handling++## π§ Key Voice Agent Patterns++### **1. Basic Voice Pipeline**+```python+from agents.voice import VoicePipeline, SingleAgentVoiceWorkflow++pipeline = VoicePipeline(+ workflow=SingleAgentVoiceWorkflow(agent)+)+```++### **2. Static Audio Processing**+```python+from agents.voice import AudioInput++audio_buffer = record_audio(duration=5.0)+audio_input = AudioInput(buffer=audio_buffer)+result = await pipeline.run(audio_input)+```++### **3. Streaming Audio Processing**+```python+from agents.voice import StreamedAudioInput++streamed_input = StreamedAudioInput()+result = await pipeline.run(streamed_input)++# Push audio chunks in real-time+streamed_input.push_audio(audio_chunk)+```++### **4. Multi-Language Agent Setup**+```python+spanish_agent = Agent(+ name="Spanish",+ handoff_description="A spanish speaking agent.",+ instructions="Speak in Spanish only..."+)++main_agent = Agent(+ name="Assistant",+ handoffs=[spanish_agent, french_agent],+ instructions="If user speaks Spanish, handoff to Spanish agent..."+)+```++## π‘ Voice Agent Best Practices++### **Agent Design for Voice**+1. **Concise Instructions**: Voice interactions work best with brief instructions+2. **Conversational Responses**: Design for natural speech patterns+3. **Clear Tool Descriptions**: Voice-friendly tool naming and descriptions+4. **Language Handling**: Implement clear language detection logic++### **Audio Quality**+1. **Good Hardware**: Use quality microphones and speakers+2. **Noise Reduction**: Minimize background noise during recording+3. **Audio Levels**: Ensure appropriate input/output volume levels+4. **Latency Optimization**: Configure audio buffers for minimal delay++### **Error Handling**+1. **Graceful Failures**: Handle audio device failures gracefully+2. **Network Issues**: Implement retry logic for API calls+3. **User Interruptions**: Allow clean exit from voice sessions+4. **Resource Cleanup**: Properly close audio streams and resources++## π§ͺ Example Voice Interactions++### **English Conversations**+- "Tell me a joke" β Humorous response+- "What's the weather in London?" β Weather tool call+- "What time is it?" β Current time+- "Calculate a 18% tip on a $75 bill" β Tip calculation++### **Language Switching**+- "Hola, ΒΏquΓ© tiempo hace en Madrid?" β Spanish agent response+- "Bonjour, quelle heure est-il?" β French agent response+- Seamless language detection and agent handoffs++### **Multi-Turn Conversations (Streaming)**+- Natural back-and-forth dialogue+- Context preservation across turns+- Tool usage within conversations++## π Static vs Streaming Comparison++| Feature | Static Voice | Streaming Voice |+|---------|-------------|-----------------|+| **Processing** | Turn-based | Real-time |+| **Complexity** | Simpler | More complex |+| **Latency** | Higher | Lower |+| **Use Cases** | Commands, queries | Conversations |+| **Activity Detection** | Manual | Automatic |+| **Resource Usage** | Lower | Higher |+| **User Experience** | Structured | Natural |++## π¨ Requirements & Dependencies++### **Core Dependencies**+- `openai-agents[voice]`: Voice-enabled Agents SDK+- `sounddevice`: Real-time audio I/O+- `numpy`: Audio data processing+- `soundfile`: Audio file operations (optional)+- `librosa`: Audio resampling (optional)++### **System Requirements**+- **Python 3.8+**: Required for async support+- **Audio Hardware**: Microphone and speakers/headphones+- **Processing Power**: Sufficient CPU for real-time audio processing+- **Network**: Stable internet for OpenAI API calls++## π Related Documentation++- **[Voice Quickstart](https://openai.github.io/openai-agents-python/voice/quickstart/)**: Official voice agent setup guide+- **[Voice Pipelines](https://openai.github.io/openai-agents-python/voice/pipeline/)**: Advanced pipeline configuration+- **[Agent Fundamentals](../1_starter_agent/README.md)**: Basic agent concepts+- **[Multi-Agent Systems](../9_multi_agent_orchestration/README.md)**: Agent handoffs and orchestration++## π¨ Troubleshooting++### **Audio Issues**+- **No microphone input**: Check audio device permissions and settings+- **Poor audio quality**: Verify microphone levels and background noise+- **Playback problems**: Test speaker/headphone configuration+- **Latency issues**: Optimize audio buffer sizes++### **Voice Pipeline Issues**+- **Transcription errors**: Ensure clear speech and good audio quality+- **Agent responses**: Verify API keys and network connectivity+- **Language detection**: Test with clear language examples+- **Handoff failures**: Check agent instructions and handoff logic++### **Performance Issues**+- **High CPU usage**: Monitor real-time processing load+- **Memory leaks**: Ensure proper cleanup of audio streams+- **Network timeouts**: Implement retry logic for API calls+- **Resource conflicts**: Check for audio device conflicts++## π‘ Pro Tips++- **Start with Static**: Master static voice processing before attempting streaming+- **Test Audio Setup**: Verify hardware configuration before development+- **Monitor Debug Output**: Use callbacks to understand pipeline behavior+- **Optimize for Voice**: Design agents specifically for conversational interaction+- **Handle Edge Cases**: Plan for network issues, audio failures, and user interruptions++## π Next Steps++After mastering voice agents:+- **Production Deployment**: Scale voice agents for real-world applications+- **Custom Voice Models**: Integrate specialized speech recognition/synthesis+- **Multi-Modal Agents**: Combine voice with vision and text capabilities+- **Enterprise Voice Solutions**: Build robust voice applications for business usediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/__init__.pynew file mode 100644index 00000000..ca432d59--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/__init__.py@@ -0,0 +1 @@+# Voice agents module for OpenAI Agents SDKdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/README.mdnew file mode 100644index 00000000..eb474f69--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/README.md@@ -0,0 +1,334 @@+# β‘ Realtime Voice Agent++A basic realtime voice agent example using OpenAI's Realtime API. This demonstrates the core components for ultra-low latency voice conversations with minimal setup.++## π― What This Demonstrates++- **Core Realtime Components**: RealtimeAgent, RealtimeRunner, and RealtimeSession+- **Basic Voice Conversation**: Ultra-low latency voice interaction+- **Function Tools**: Simple tools callable during voice conversation+- **Agent Handoffs**: Basic handoff to specialized agent+- **Event Handling**: Essential event processing for realtime sessions++## π§ Core Concept: Realtime Voice Processing++Realtime agents provide **ultra-low latency voice conversation** using OpenAI's Realtime API. Unlike traditional voice pipelines, realtime agents maintain persistent WebSocket connections for immediate audio processing. Think of realtime agents as **live conversation partners** that:++- Process audio and respond instantly with minimal latency+- Handle interruptions gracefully during conversation+- Maintain persistent connections for natural dialogue flow+- Support real-time tool execution and agent handoffs+- Apply safety guardrails during live generation++Based on the [official documentation](https://openai.github.io/openai-agents-python/realtime/quickstart/), realtime agents enable natural voice conversations with the lowest possible latency.++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β REALTIME VOICE WORKFLOW β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β π€ LIVE AUDIO INPUT β+β β β+β βΌ β+β βββββββββββββββ 1. WEBSOCKET CONNECTION β+β β PERSISTENT β β¦ Continuous audio streaming β+β β CONNECTION β β¦ Ultra-low latency pipeline β+β βββββββββββββββ β¦ Real-time processing β+β β β+β βΌ β+β βββββββββββββββ 2. INSTANT PROCESSING β+β β REALTIME β β¦ Immediate speech recognition β+β β AGENTS β β¦ Live agent reasoning β+β βββββββββββββββ β¦ Real-time tool execution β+β β β+β βΌ β+β βββββββββββββββ 3. IMMEDIATE RESPONSE β+β β LIVE β β¦ Real-time audio generation β+β β RESPONSE β β¦ Streaming audio output β+β βββββββββββββββ β¦ Interruption handling β+β β β+β βΌ β+β π INSTANT AUDIO OUTPUT β+β β+β βΊ CONTINUOUS CONVERSATION LOOP β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the basic realtime agent**:+ ```bash+ python agent.py+ ```++4. **Start talking**: The agent will respond in real-time. Try:+ - "What's the weather in Paris?"+ - "Book appointment tomorrow at 2pm"++## π§ͺ What This Example Includes++### **Core Realtime Components**+Based on the [official guide](https://openai.github.io/openai-agents-python/realtime/guide/):+- **RealtimeAgent**: Agent with instructions, tools, and handoffs+- **RealtimeRunner**: Manages configuration and returns sessions+- **RealtimeSession**: Single conversation session with event streaming++### **Basic Function Tools**+- `get_weather(city)`: Simple weather information+- `book_appointment(date, time, service)`: Basic appointment booking++### **Simple Agent Handoff**+- **Main Assistant**: General conversation agent+- **Billing Agent**: Specialized billing support (demonstrates handoff pattern)++### **Essential Event Handling**+- **Audio Transcripts**: User and assistant speech transcription+- **Tool Calls**: Function execution notifications+- **Error Events**: Basic error handling++## π― Example Voice Interactions++### **Basic Conversation**+- "What's the weather in Paris?" β Tool call with instant response+- "Book appointment tomorrow at 2pm" β Appointment booking tool++### **Agent Handoff**+- "I need help with billing" β Handoff to billing support agent++## π§ Key Implementation Patterns++Based on the [official guide](https://openai.github.io/openai-agents-python/realtime/guide/):++### **1. Create RealtimeAgent**+```python+from agents.realtime import RealtimeAgent++agent = RealtimeAgent(+ name="Assistant",+ instructions="You are a helpful voice assistant...",+ tools=[get_weather, book_appointment],+ handoffs=[realtime_handoff(billing_agent)]+)+```++### **2. Set up RealtimeRunner**+```python+from agents.realtime import RealtimeRunner++runner = RealtimeRunner(+ starting_agent=agent,+ config={+ "model_settings": {+ "model_name": "gpt-4o-realtime-preview",+ "voice": "alloy",+ "modalities": ["text", "audio"]+ }+ }+)+```++### **3. Start Session and Handle Events**+```python+session = await runner.run()++async with session:+ async for event in session:+ if event.type == "response.audio_transcript.done":+ print(f"Assistant: {event.transcript}")+```++## π‘ Basic Realtime Concepts++From the [official guide](https://openai.github.io/openai-agents-python/realtime/guide/):++1. **Session Flow**: Create agents β Set up runner β Start session β Handle events+2. **Event Handling**: Listen for audio transcripts, tool calls, and errors+3. **Voice Configuration**: Choose from 6 voices (alloy, echo, fable, onyx, nova, shimmer)+4. **Turn Detection**: Server-side voice activity detection for natural conversation++## π Realtime vs Traditional Voice Comparison++| Feature | Traditional Voice | Realtime Voice |+|---------|------------------|----------------|+| **Latency** | 2-5 seconds | <500ms |+| **Connection** | Request/Response | Persistent WebSocket |+| **Interruptions** | Limited | Natural handling |+| **Audio Processing** | Batched | Streaming |+| **Tool Execution** | Turn-based | Real-time |+| **Conversation Flow** | Structured | Natural |+| **API** | REST endpoints | WebSocket events |++## π Advanced Realtime Features++### **Voice Activity Detection (VAD)**+- **Server VAD**: OpenAI's optimized speech detection+- **Configurable Thresholds**: Adjust sensitivity for different environments+- **Silence Detection**: Intelligent turn boundary detection+- **Prefix Padding**: Capture speech start accurately++### **Audio Configuration Options**+- **Voice Selection**: Choose from 6 different voices (alloy, echo, fable, onyx, nova, shimmer)+- **Audio Formats**: Support for PCM16, G.711 ΞΌ-law, and G.711 A-law+- **Transcription Models**: Whisper integration for speech-to-text+- **Multi-Modal Support**: Text and audio modalities++### **Real-Time Guardrails**+Based on the [guide documentation](https://openai.github.io/openai-agents-python/realtime/guide/), realtime guardrails are:+- **Debounced**: Run periodically (not on every word) for performance+- **Configurable**: Adjustable debounce length (default 100 characters)+- **Non-Blocking**: Don't raise exceptions, generate events instead+- **Real-Time**: Can interrupt responses immediately when triggered++### **Session Event Types**+- **Audio Events**: `response.audio.delta`, `response.audio.done`+- **Transcription Events**: `response.audio_transcript.done`, `input_audio_transcription.completed`+- **Tool Events**: `response.function_call_arguments.done`+- **Lifecycle Events**: `session.created`, `session.updated`, `response.done`+- **Error Events**: `error`, `guardrail_tripped`++## π¨ Requirements & Dependencies++### **Core Dependencies**+- `openai-agents>=1.0.0`: OpenAI Agents SDK with realtime support+- `python-dotenv>=1.0.0`: Environment variable management+- Python 3.9 or higher (required for realtime features)++### **API Requirements**+- **OpenAI API Key**: Required for Realtime API access+- **Model Access**: Access to `gpt-4o-realtime-preview` model+- **WebSocket Support**: Stable internet connection for persistent connections++### **System Requirements**+- **Real-Time Capable**: Low-latency network connection+- **Audio Hardware**: Microphone and speakers for voice interaction+- **Processing Power**: Sufficient CPU for real-time audio processing++## π§ Configuration Options++### **Model Settings**+```python+"model_settings": {+ "model_name": "gpt-4o-realtime-preview", # Realtime model+ "voice": "alloy", # Voice selection+ "modalities": ["text", "audio"], # Supported modalities+ "input_audio_format": "pcm16", # Audio input format+ "output_audio_format": "pcm16" # Audio output format+}+```++### **Turn Detection Settings**+```python+"turn_detection": {+ "type": "server_vad", # Voice activity detection+ "threshold": 0.5, # Detection sensitivity (0.0-1.0)+ "prefix_padding_ms": 300, # Audio padding before speech+ "silence_duration_ms": 200 # Silence to detect turn end+}+```++### **Transcription Configuration**+```python+"input_audio_transcription": {+ "model": "whisper-1", # Transcription model+ "language": "en", # Language preference+ "prompt": "Custom prompt..." # Domain-specific terms+}+```++## π‘οΈ Safety and Guardrails++### **Real-Time Safety Features**+- **Debounced Processing**: Guardrails run periodically for performance+- **Immediate Intervention**: Can interrupt unsafe responses in real-time+- **Event-Based Alerts**: Generate `guardrail_tripped` events instead of exceptions+- **Configurable Sensitivity**: Adjust debounce length based on requirements++### **Safety Implementation**+```python+@output_guardrail+def sensitive_data_guardrail(ctx, agent, output: str) -> GuardrailFunctionOutput:+ if contains_sensitive_data(output):+ return GuardrailFunctionOutput(+ tripwire_triggered=True,+ output_info="Blocked sensitive data"+ )+ return GuardrailFunctionOutput(tripwire_triggered=False)+```++## π― Production Considerations++### **Performance Optimization**+- **Connection Management**: Maintain persistent WebSocket connections+- **Error Recovery**: Implement automatic reconnection logic+- **Resource Monitoring**: Track memory and CPU usage during sessions+- **Event Processing**: Optimize event handling for high-throughput scenarios++### **Scalability Patterns**+- **Session Isolation**: Each user gets independent realtime sessions+- **Load Balancing**: Distribute sessions across multiple instances+- **Connection Pooling**: Manage WebSocket connections efficiently+- **Graceful Shutdown**: Handle session cleanup properly++### **Monitoring and Analytics**+- **Event Tracking**: Monitor all realtime events for insights+- **Performance Metrics**: Track latency, throughput, and error rates+- **User Analytics**: Analyze conversation patterns and success rates+- **Safety Metrics**: Monitor guardrail activation and effectiveness++## π¨ Beta Considerations++As noted in the [official documentation](https://openai.github.io/openai-agents-python/realtime/quickstart/), realtime agents are currently in beta. Consider:++- **API Stability**: Expect potential breaking changes as the API evolves+- **Feature Development**: New capabilities may be added regularly+- **Testing Requirements**: Thorough testing recommended before production deployment+- **Feedback Channels**: Provide feedback to help improve the realtime experience++## π‘ Pro Tips++- **Start Simple**: Begin with basic realtime conversation before adding complex features+- **Monitor Events**: Use comprehensive event logging to understand behavior+- **Optimize Guardrails**: Balance safety with real-time performance requirements+- **Test Interruptions**: Ensure natural handling of conversation interruptions+- **Plan for Scale**: Design session management for production workloads++## π Related Documentation++- **[Realtime Quickstart](https://openai.github.io/openai-agents-python/realtime/quickstart/)**: Official getting started guide+- **[Realtime Guide](https://openai.github.io/openai-agents-python/realtime/guide/)**: Comprehensive realtime documentation+- **[Voice Agents](../README.md)**: Overview of all voice agent capabilities+- **[Agent Fundamentals](../../1_starter_agent/README.md)**: Basic agent concepts++## π― Troubleshooting++### **Common Issues**+- **High Latency**: Check network connection and WebSocket stability+- **Audio Quality**: Verify microphone settings and audio formats+- **Event Processing**: Monitor event handling performance and errors+- **Guardrail Performance**: Optimize debounce settings for real-time requirements+- **Model Access**: Ensure access to `gpt-4o-realtime-preview` model++### **Debug Strategies**+- **Event Logging**: Enable comprehensive event debugging+- **Connection Monitoring**: Track WebSocket connection health+- **Performance Profiling**: Monitor CPU and memory usage during sessions+- **Audio Pipeline**: Verify audio input/output processing++## π Next Steps++After mastering realtime voice agents:+- **Production Deployment**: Scale realtime agents for production use+- **Custom Integrations**: Build realtime voice into existing applications+- **Advanced Features**: Explore cutting-edge realtime capabilities+- **Multi-Modal Experiences**: Combine realtime voice with other modalitiesdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/__init__.pynew file mode 100644index 00000000..eed4960d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/__init__.py@@ -0,0 +1 @@+# Realtime voice agent examplediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/agent.pynew file mode 100644index 00000000..bd787796--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/agent.py@@ -0,0 +1,105 @@+import asyncio+from agents import function_tool+from agents.realtime import RealtimeAgent, RealtimeRunner, realtime_handoff++"""+Basic realtime voice agent example using OpenAI's Realtime API.+Run it via: python agent.py++This demonstrates the core realtime components from the official guide:+https://openai.github.io/openai-agents-python/realtime/guide/++Core Components:+1. RealtimeAgent - Agent with instructions, tools, and handoffs+2. RealtimeRunner - Manages configuration and sessions+3. RealtimeSession - Single conversation session+4. Event handling - Process audio, transcripts, and tool calls+"""++# Basic function tool+@function_tool+def get_weather(city: str) -> str:+ """Get current weather for a city."""+ print(f"[debug] get_weather called with city: {city}")+ return f"The weather in {city} is sunny, 72Β°F"++@function_tool+def book_appointment(date: str, time: str, service: str) -> str:+ """Book an appointment."""+ print(f"[debug] book_appointment called: {service} on {date} at {time}")+ return f"Appointment booked for {service} on {date} at {time}"++# Specialized agent for handoffs+billing_agent = RealtimeAgent(+ name="Billing Support",+ instructions="You specialize in billing and payment issues.",+)++# Main realtime agent+agent = RealtimeAgent(+ name="Assistant",+ instructions="You are a helpful voice assistant. Keep responses brief and conversational.",+ tools=[get_weather, book_appointment],+ handoffs=[+ realtime_handoff(billing_agent, tool_description="Transfer to billing support")+ ]+)++async def main():+ """Basic realtime session example"""++ print("ποΈ Basic Realtime Voice Agent")+ print("=" * 40)++ # Set up the runner with basic configuration+ runner = RealtimeRunner(+ starting_agent=agent,+ config={+ "model_settings": {+ "model_name": "gpt-4o-realtime-preview",+ "voice": "alloy",+ "modalities": ["text", "audio"],+ "input_audio_transcription": {+ "model": "whisper-1"+ },+ "turn_detection": {+ "type": "server_vad",+ "threshold": 0.5,+ "silence_duration_ms": 200+ }+ }+ }+ )++ # Start the session+ print("Starting realtime session...")+ session = await runner.run()++ print("Session started! Speak naturally - agent will respond in real-time.")+ print("Try: 'What's the weather in Paris?' or 'Book appointment tomorrow at 2pm'")+ print("Press Ctrl+C to end")+ print("-" * 40)++ # Handle session events+ async with session:+ try:+ async for event in session:+ # Handle key event types+ if event.type == "response.audio_transcript.done":+ print(f"π€ Assistant: {event.transcript}")++ elif event.type == "conversation.item.input_audio_transcription.completed":+ print(f"π€ User: {event.transcript}")++ elif event.type == "response.function_call_arguments.done":+ print(f"π§ Tool called: {event.name}")++ elif event.type == "error":+ print(f"β Error: {event.error}")+ break++ except KeyboardInterrupt:+ print("\nβΉοΈ Session ended")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/requirements.txtnew file mode 100644index 00000000..7ff79ee9--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/realtime/requirements.txt@@ -0,0 +1,2 @@+openai-agents>=1.0.0+python-dotenv>=1.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/README.mdnew file mode 100644index 00000000..096a5ac3--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/README.md@@ -0,0 +1,225 @@+# ποΈ Static Voice Agent++A complete voice interaction example using the OpenAI Agents SDK with pre-recorded audio input. This demonstrates the basic voice pipeline workflow with speech-to-text, agent processing, and text-to-speech capabilities.++## π― What This Demonstrates++- **Static Audio Processing**: Record once, process completely+- **Voice Pipeline**: Complete speech-to-text β agent β text-to-speech workflow+- **Multi-Agent System**: Agent handoffs based on language detection+- **Tool Integration**: Voice-activated tools for weather, time, and calculations+- **Audio Management**: Recording, playback, and audio utility functions++## π§ Core Concept: Static Voice Pipeline++The static voice pipeline processes a complete audio recording in one workflow. Think of it as a **turn-based voice assistant** that:++- Records your complete message first+- Transcribes the entire audio to text+- Processes with AI agents and tools+- Converts the complete response back to speech+- Plays the full audio response++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STATIC VOICE WORKFLOW β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β π€ RECORD AUDIO β+β β β+β βΌ β+β βββββββββββββββ 1. COMPLETE RECORDING β+β β AUDIO β β¦ Record for fixed duration β+β β CAPTURE β β¦ Full audio buffer β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 2. SPEECH-TO-TEXT β+β β TRANSCRIBE β β¦ Convert full audio to text β+β β AUDIO β β¦ Complete transcription β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 3. AGENT PROCESSING β+β β AGENT β β¦ Multi-agent workflow β+β β WORKFLOW β β¦ Tool calls & handoffs β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 4. TEXT-TO-SPEECH β+β β GENERATE β β¦ Convert response to audio β+β β SPEECH β β¦ Stream audio output β+β βββββββββββββββ β+β β β+β βΌ β+β π PLAY RESPONSE β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Quick Start++1. **Install voice dependencies**:+ ```bash+ pip install 'openai-agents[voice]'+ pip install sounddevice numpy soundfile librosa+ ```++2. **Set up environment**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the static voice agent**:+ ```bash+ python agent.py+ ```++## π§ͺ What This Example Includes++### **Multi-Language Support**+- **English Agent**: Primary assistant with all tools+- **Spanish Agent**: Specialized Spanish-speaking agent+- **French Agent**: Specialized French-speaking agent+- **Automatic Language Detection**: Handoffs based on detected language++### **Voice-Activated Tools**+- `get_weather(city)`: Get weather information for any city+- `get_time()`: Get current time+- `calculate_tip(bill, percentage)`: Calculate tips for bills++### **Audio Utilities**+- `AudioPlayer`: Real-time audio playback with sounddevice+- `record_audio()`: Microphone recording with duration control+- `create_silence()`: Generate silence buffers+- `save_audio()` / `load_audio()`: Audio file operations++### **Workflow Callbacks**+- `WorkflowCallbacks`: Monitor transcription, tool calls, and handoffs+- Debug output for pipeline monitoring+- Performance tracking and statistics++## π― Example Interactions++### **English Examples**+- "Tell me a joke" β Agent responds with humor+- "What's the weather in Tokyo?" β Calls weather tool+- "What time is it?" β Calls time tool+- "Calculate a 20% tip on a $50 bill" β Performs calculation++### **Language Handoffs**+- "Hola, ΒΏcΓ³mo estΓ‘s?" β Handoff to Spanish agent+- "Bonjour, comment allez-vous?" β Handoff to French agent+- Agents respond in the detected language++### **Tool Integration**+- Weather queries work in any language+- Time and calculation tools available to all agents+- Tools called automatically based on user requests++## π§ Key Implementation Patterns++### **1. Voice Pipeline Setup**+```python+pipeline = VoicePipeline(+ workflow=SingleAgentVoiceWorkflow(agent, callbacks=WorkflowCallbacks())+)+```++### **2. Audio Input Processing**+```python+audio_buffer = record_audio(duration=5.0)+audio_input = AudioInput(buffer=audio_buffer)+result = await pipeline.run(audio_input)+```++### **3. Audio Output Streaming**+```python+with AudioPlayer() as player:+ async for event in result.stream():+ if event.type == "voice_stream_event_audio":+ player.add_audio(event.data)+```++### **4. Multi-Agent Configuration**+```python+agent = Agent(+ name="Assistant",+ handoffs=[spanish_agent, french_agent],+ tools=[get_weather, get_time, calculate_tip]+)+```++## π‘ Voice Agent Best Practices++1. **Clear Audio Recording**: Ensure good microphone quality and minimal background noise+2. **Concise Instructions**: Voice interactions work best with brief, clear agent instructions+3. **Error Handling**: Implement robust error handling for audio recording failures+4. **Language Detection**: Use prompt engineering for automatic language switching+5. **Tool Design**: Design tools for voice interaction with conversational responses++## π Performance Characteristics++### **Static Pipeline Benefits**+- **Predictable Processing**: Fixed recording duration+- **Complete Context**: Full utterance available for processing+- **Simpler Implementation**: No real-time complexity+- **Better for Complex Queries**: Can process longer, detailed requests++### **Use Cases**+- **Voice Assistants**: Traditional turn-based interaction+- **Voice Commands**: Specific task automation+- **Language Learning**: Practice with multilingual agents+- **Accessibility**: Voice interface for applications++## π¨ Requirements & Dependencies++### **Core Dependencies**+- `openai-agents[voice]`: OpenAI Agents SDK with voice support+- `sounddevice`: Audio recording and playback+- `numpy`: Audio data processing+- `soundfile`: Audio file operations (optional)+- `librosa`: Audio resampling (optional)++### **System Requirements**+- **Microphone**: For audio input+- **Speakers/Headphones**: For audio output+- **Python 3.8+**: Required for async support++## π Related Examples++- **[Streaming Voice](../streamed/README.md)**: Real-time voice interaction+- **[Voice Pipeline Documentation](https://openai.github.io/openai-agents-python/voice/pipeline/)**: Official pipeline docs+- **[Voice Quickstart](https://openai.github.io/openai-agents-python/voice/quickstart/)**: Basic voice setup++## π οΈ Customization Options++### **Extend Audio Utilities**+- Add audio effects and filtering+- Implement custom audio formats+- Add audio visualization++### **Enhance Agent Capabilities**+- Add more specialized language agents+- Implement domain-specific tools+- Add conversation memory++### **Improve Voice Experience**+- Add voice activity detection+- Implement custom wake words+- Add voice emotion detection++## π‘ Pro Tips++- **Test Audio Setup**: Verify microphone and speakers before running+- **Experiment with Duration**: Adjust recording duration based on use case+- **Monitor Debug Output**: Use callbacks to understand pipeline behavior+- **Handle Interruptions**: Implement graceful handling of Ctrl+C+- **Optimize for Voice**: Keep agent responses concise and conversational++## π Next Steps++After mastering static voice agents:+- **[Streaming Voice](../streamed/README.md)**: Implement real-time voice interaction+- **[Advanced Voice Pipelines](https://openai.github.io/openai-agents-python/voice/pipeline/)**: Custom pipeline configurations+- **Production Voice Apps**: Deploy voice agents in real applicationsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/__init__.pynew file mode 100644index 00000000..8a9f5c51--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/__init__.py@@ -0,0 +1 @@+# Static voice agent examplediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/agent.pynew file mode 100644index 00000000..50803dd0--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/agent.py@@ -0,0 +1,215 @@+import asyncio+import random++import numpy as np++from agents import Agent, function_tool+from agents.extensions.handoff_prompt import prompt_with_handoff_instructions+from agents.voice import (+ AudioInput,+ SingleAgentVoiceWorkflow,+ SingleAgentWorkflowCallbacks,+ VoicePipeline,+)++from .util import AudioPlayer, record_audio++"""+This is a simple example that uses a recorded audio buffer. Run it via:+`python -m ai_agent_framework_crash_course.openai_sdk_crash_course.11_voice.static.agent`++1. You can record an audio clip in the terminal.+2. The pipeline automatically transcribes the audio.+3. The agent workflow is a simple one that starts at the Assistant agent.+4. The output of the agent is streamed to the audio player.++Try examples like:+- Tell me a joke (will respond with a joke)+- What's the weather in Tokyo? (will call the `get_weather` tool and then speak)+- Hola, como estas? (will handoff to the spanish agent)+"""+++@function_tool+def get_weather(city: str) -> str:+ """Get the weather for a given city."""+ print(f"[debug] get_weather called with city: {city}")+ choices = ["sunny", "cloudy", "rainy", "snowy"]+ return f"The weather in {city} is {random.choice(choices)}."+++@function_tool+def get_time() -> str:+ """Get the current time."""+ import datetime+ current_time = datetime.datetime.now().strftime("%I:%M %p")+ print(f"[debug] get_time called, current time: {current_time}")+ return f"The current time is {current_time}."+++@function_tool+def calculate_tip(bill_amount: float, tip_percentage: float = 15.0) -> str:+ """Calculate tip amount for a bill."""+ tip_amount = bill_amount * (tip_percentage / 100)+ total_amount = bill_amount + tip_amount+ print(f"[debug] calculate_tip called with bill: ${bill_amount}, tip: {tip_percentage}%")+ return f"For a bill of ${bill_amount:.2f} with {tip_percentage}% tip, the tip is ${tip_amount:.2f} and total is ${total_amount:.2f}."+++spanish_agent = Agent(+ name="Spanish",+ handoff_description="A spanish speaking agent.",+ instructions=prompt_with_handoff_instructions(+ "You're speaking to a human, so be polite and concise. Speak in Spanish only. "+ "Help with weather, time, and calculations as needed."+ ),+ model="gpt-4o-mini",+ tools=[get_weather, get_time, calculate_tip]+)++french_agent = Agent(+ name="French",+ handoff_description="A french speaking agent.",+ instructions=prompt_with_handoff_instructions(+ "You're speaking to a human, so be polite and concise. Speak in French only. "+ "Help with weather, time, and calculations as needed."+ ),+ model="gpt-4o-mini",+ tools=[get_weather, get_time, calculate_tip]+)++agent = Agent(+ name="Assistant",+ instructions=prompt_with_handoff_instructions(+ """You're speaking to a human, so be polite and concise.++ You can help with:+ - Weather information for any city+ - Current time+ - Tip calculations+ - General conversation and jokes++ Language handling:+ - If the user speaks in Spanish, handoff to the Spanish agent+ - If the user speaks in French, handoff to the French agent+ - Otherwise, respond in English++ Keep responses conversational and friendly for voice interaction."""+ ),+ model="gpt-4o-mini",+ handoffs=[spanish_agent, french_agent],+ tools=[get_weather, get_time, calculate_tip],+)+++class WorkflowCallbacks(SingleAgentWorkflowCallbacks):+ """Custom callbacks to monitor the voice workflow."""++ def on_run(self, workflow: SingleAgentVoiceWorkflow, transcription: str) -> None:+ """Called when the workflow runs with a new transcription."""+ print(f"[debug] π― Workflow running with transcription: '{transcription}'")++ def on_tool_call(self, tool_name: str, arguments: dict) -> None:+ """Called when a tool is about to be executed."""+ print(f"[debug] π§ Tool call: {tool_name} with args: {arguments}")++ def on_handoff(self, from_agent: str, to_agent: str) -> None:+ """Called when a handoff occurs between agents."""+ print(f"[debug] π Handoff from {from_agent} to {to_agent}")+++async def main():+ """Main function to run the static voice agent example."""+ print("ποΈ Static Voice Agent Demo")+ print("=" * 50)+ print()++ # Create the voice pipeline with our agent and callbacks+ pipeline = VoicePipeline(+ workflow=SingleAgentVoiceWorkflow(agent, callbacks=WorkflowCallbacks())+ )++ print("This demo will:")+ print("1. π€ Record your voice for a few seconds")+ print("2. π Transcribe your speech to text")+ print("3. π€ Process with AI agent")+ print("4. π Convert response back to speech")+ print()++ # Record audio input+ try:+ audio_buffer = record_audio(duration=5.0)+ print(f"π Recorded {len(audio_buffer)} audio samples")++ # Create audio input for the pipeline+ audio_input = AudioInput(buffer=audio_buffer)++ # Run the voice pipeline+ print("\nπ Processing with voice pipeline...")+ result = await pipeline.run(audio_input)++ # Play the result audio+ print("π Playing AI response...")++ with AudioPlayer() as player:+ audio_chunks_received = 0+ lifecycle_events = 0++ async for event in result.stream():+ if event.type == "voice_stream_event_audio":+ player.add_audio(event.data)+ audio_chunks_received += 1+ if audio_chunks_received % 10 == 0: # Progress indicator+ print(f"π΅ Received {audio_chunks_received} audio chunks...")++ elif event.type == "voice_stream_event_lifecycle":+ lifecycle_events += 1+ print(f"π Lifecycle event: {event.event}")++ elif event.type == "voice_stream_event_error":+ print(f"β Error event: {event.error}")++ # Add 1 second of silence to ensure the audio finishes playing+ print("π Adding silence buffer...")+ player.add_audio(np.zeros(24000 * 1, dtype=np.int16))++ print(f"\nβ Voice interaction complete!")+ print(f"π Statistics:")+ print(f" - Audio chunks played: {audio_chunks_received}")+ print(f" - Lifecycle events: {lifecycle_events}")++ except KeyboardInterrupt:+ print("\nβΉοΈ Demo interrupted by user.")+ except Exception as e:+ print(f"\nβ Demo failed: {e}")+ import traceback+ traceback.print_exc()+++def demo_with_examples():+ """Run multiple example scenarios for demonstration."""+ examples = [+ "Tell me a joke",+ "What's the weather in New York?",+ "What time is it?",+ "Calculate a 20% tip on a $50 bill",+ "Hola, como estas?", # Spanish handoff+ "Bonjour, comment allez-vous?" # French handoff+ ]++ print("π Demo Examples:")+ for i, example in enumerate(examples, 1):+ print(f"{i}. {example}")+ print()+ print("You can try saying any of these examples when recording!")+++if __name__ == "__main__":+ print("π OpenAI Agents SDK - Static Voice Demo")+ print("=" * 60)++ # Show example prompts+ demo_with_examples()++ # Run the main demo+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/requirements.txtnew file mode 100644index 00000000..560a2fba--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/requirements.txt@@ -0,0 +1,6 @@+openai-agents[voice]>=1.0.0+sounddevice>=0.4.0+numpy>=1.21.0+soundfile>=0.12.0+librosa>=0.10.0+python-dotenv>=1.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/util.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/util.pynew file mode 100644index 00000000..b793f504--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/util.py@@ -0,0 +1,170 @@+import threading+import time+from typing import Optional++import numpy as np+import sounddevice as sd+++class AudioPlayer:+ """A simple audio player using sounddevice for real-time audio playback."""++ def __init__(self, sample_rate: int = 24000, channels: int = 1, dtype=np.int16):+ self.sample_rate = sample_rate+ self.channels = channels+ self.dtype = dtype+ self.stream: Optional[sd.OutputStream] = None+ self._stop_event = threading.Event()++ def __enter__(self):+ """Context manager entry - start the audio stream."""+ self.stream = sd.OutputStream(+ samplerate=self.sample_rate,+ channels=self.channels,+ dtype=self.dtype+ )+ self.stream.start()+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Context manager exit - stop and close the audio stream."""+ if self.stream:+ self.stream.stop()+ self.stream.close()++ def add_audio(self, audio_data: np.ndarray):+ """Add audio data to be played immediately."""+ if self.stream and not self._stop_event.is_set():+ try:+ self.stream.write(audio_data)+ except Exception as e:+ print(f"[error] Failed to play audio: {e}")++ def stop(self):+ """Stop the audio player."""+ self._stop_event.set()+++def record_audio(+ duration: float = 5.0,+ sample_rate: int = 24000,+ channels: int = 1,+ dtype=np.int16+) -> np.ndarray:+ """+ Record audio from the microphone for a specified duration.++ Args:+ duration: Recording duration in seconds+ sample_rate: Audio sample rate (Hz)+ channels: Number of audio channels+ dtype: Audio data type++ Returns:+ Recorded audio as numpy array+ """+ print(f"π€ Recording audio for {duration} seconds... Press Ctrl+C to stop early.")+ print("Say something now!")++ try:+ # Record audio+ recording = sd.rec(+ int(duration * sample_rate),+ samplerate=sample_rate,+ channels=channels,+ dtype=dtype+ )++ # Wait for recording to complete+ sd.wait()++ print("β Recording completed!")++ # Convert to 1D array if mono+ if channels == 1:+ recording = recording.flatten()++ return recording.astype(dtype)++ except KeyboardInterrupt:+ print("\nβΉοΈ Recording stopped by user.")+ sd.stop()+ if 'recording' in locals():+ return recording[:int(time.time() * sample_rate)].astype(dtype)+ else:+ # Return empty array if no recording was captured+ return np.zeros(sample_rate, dtype=dtype)++ except Exception as e:+ print(f"β Recording failed: {e}")+ return np.zeros(sample_rate, dtype=dtype)+++def create_silence(duration: float = 1.0, sample_rate: int = 24000, dtype=np.int16) -> np.ndarray:+ """+ Create a buffer of silence for the specified duration.++ Args:+ duration: Duration of silence in seconds+ sample_rate: Audio sample rate (Hz)+ dtype: Audio data type++ Returns:+ Silence buffer as numpy array+ """+ return np.zeros(int(duration * sample_rate), dtype=dtype)+++def save_audio(audio_data: np.ndarray, filename: str, sample_rate: int = 24000):+ """+ Save audio data to a WAV file.++ Args:+ audio_data: Audio data as numpy array+ filename: Output filename (should end with .wav)+ sample_rate: Audio sample rate (Hz)+ """+ try:+ import soundfile as sf+ sf.write(filename, audio_data, sample_rate)+ print(f"β Audio saved to {filename}")+ except ImportError:+ print("β soundfile package required for saving audio. Install with: pip install soundfile")+ except Exception as e:+ print(f"β Failed to save audio: {e}")+++def load_audio(filename: str, sample_rate: int = 24000, dtype=np.int16) -> np.ndarray:+ """+ Load audio data from a WAV file.++ Args:+ filename: Input filename+ sample_rate: Target sample rate (will resample if different)+ dtype: Target data type++ Returns:+ Audio data as numpy array+ """+ try:+ import soundfile as sf+ audio_data, original_sr = sf.read(filename)++ # Resample if necessary+ if original_sr != sample_rate:+ import librosa+ audio_data = librosa.resample(audio_data, orig_sr=original_sr, target_sr=sample_rate)++ # Convert to target dtype+ if dtype == np.int16:+ audio_data = (audio_data * 32767).astype(np.int16)++ return audio_data++ except ImportError:+ print("β soundfile and librosa packages required for loading audio.")+ print("Install with: pip install soundfile librosa")+ return np.zeros(sample_rate, dtype=dtype)+ except Exception as e:+ print(f"β Failed to load audio: {e}")+ return np.zeros(sample_rate, dtype=dtype)diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/README.mdnew file mode 100644index 00000000..e06c0dba--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/README.md@@ -0,0 +1,289 @@+# π Streaming Voice Agent++A real-time voice interaction example using the OpenAI Agents SDK with continuous audio streaming. This demonstrates advanced voice pipeline capabilities with live speech detection, real-time processing, and turn-based conversation management.++## π― What This Demonstrates++- **Real-Time Audio Processing**: Continuous audio input and output streaming+- **Activity Detection**: Automatic detection of speech start/stop+- **Turn Management**: Intelligent conversation turn handling+- **Live Agent Processing**: Real-time agent responses during conversation+- **Interruption Handling**: Lifecycle events for managing conversation flow+- **Streaming Callbacks**: Real-time monitoring and debugging++## π§ Core Concept: Streaming Voice Pipeline++The streaming voice pipeline processes audio continuously in real-time. Think of it as a **live conversation assistant** that:++- Continuously listens for audio input+- Automatically detects when you start and stop speaking+- Processes speech in real-time with AI agents+- Streams responses back as they're generated+- Manages conversation turns automatically++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STREAMING VOICE WORKFLOW β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β π€ CONTINUOUS AUDIO INPUT β+β β β+β βΌ β+β βββββββββββββββ 1. REAL-TIME CAPTURE β+β β STREAMING β β¦ Continuous microphone input β+β β AUDIO β β¦ Chunk-based processing β+β β RECORDER β β¦ Activity detection β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 2. LIVE TRANSCRIPTION β+β β STREAMING β β¦ Real-time speech-to-text β+β βTRANSCRIPTIONβ β¦ Turn boundary detection β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 3. CONCURRENT PROCESSING β+β β PARALLEL β β¦ Agent workflow execution β+β β AGENT EXEC β β¦ Tool calls & handoffs β+β βββββββββββββββ β¦ Multiple turns in session β+β β β+β βΌ β+β βββββββββββββββ 4. STREAMING RESPONSE β+β β LIVE TTS β β¦ Real-time text-to-speech β+β β PLAYBACK β β¦ Chunked audio output β+β βββββββββββββββ β¦ Immediate response playback β+β β β+β βΌ β+β π CONTINUOUS AUDIO OUTPUT β+β β+β βΊ LOOP FOR MULTIPLE TURNS β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Quick Start++1. **Install voice dependencies**:+ ```bash+ pip install 'openai-agents[voice]'+ pip install sounddevice numpy soundfile librosa+ ```++2. **Set up environment**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the streaming voice agent**:+ ```bash+ python agent.py+ ```++4. **Start talking**: The agent will automatically detect when you speak and respond in real-time!++## π§ͺ What This Example Includes++### **Real-Time Audio Management**+- **StreamedAudioRecorder**: Continuous microphone input with threading+- **AudioPlayer**: Real-time audio playback with stream management+- **Activity Detection**: Automatic speech start/stop detection+- **Turn-Based Processing**: Intelligent conversation management++### **Advanced Agent Capabilities**+- **Multi-Language Support**: English, Spanish, and French agents+- **Enhanced Tools**: Weather, time, reminders, and news+- **Real-Time Handoffs**: Language detection during streaming+- **Session Management**: Multi-turn conversation tracking++### **Streaming Tools**+- `get_weather(city)`: Real-time weather information+- `get_time()`: Current time with live updates+- `set_reminder(message, minutes)`: Demo reminder functionality+- `get_news_summary()`: Mock news updates++### **Advanced Monitoring**+- **StreamingWorkflowCallbacks**: Real-time event monitoring+- **VoiceSessionManager**: Session lifecycle management+- **Turn Tracking**: Conversation analytics and statistics+- **Lifecycle Events**: Turn start/end event handling++## π― Example Interactions++### **Natural Conversation Flow**+- Start speaking β Agent automatically detects speech+- Pause β Agent processes and responds immediately+- Continue talking β New turn begins automatically+- Multiple turns in single session++### **Real-Time Tool Usage**+- "What's the weather in New York?" β Immediate weather response+- "What time is it?" β Live time information+- "Set a reminder to call Sarah in 15 minutes" β Reminder confirmation+- "Give me a news summary" β Current news update++### **Live Language Switching**+- Speak in English β English agent responds+- Switch to "ΒΏQuΓ© tiempo hace en Madrid?" β Spanish agent takes over+- Switch to "Quelle heure est-il?" β French agent responds+- Seamless language detection and handoffs++## π§ Key Implementation Patterns++### **1. Streaming Pipeline Setup**+```python+pipeline = VoicePipeline(+ workflow=SingleAgentVoiceWorkflow(agent, callbacks=StreamingWorkflowCallbacks())+)+```++### **2. Continuous Audio Input**+```python+with StreamedAudioRecorder() as recorder:+ streamed_input = StreamedAudioInput()++ while session_active:+ if recorder.has_audio():+ audio_chunk = recorder.get_audio_chunk()+ streamed_input.push_audio(audio_chunk)+```++### **3. Real-Time Audio Output**+```python+with AudioPlayer() as player:+ async for event in result.stream():+ if event.type == "voice_stream_event_audio":+ player.add_audio(event.data)+ elif event.type == "voice_stream_event_lifecycle":+ handle_turn_events(event)+```++### **4. Session Management**+```python+class VoiceSessionManager:+ async def start_session(self):+ # Concurrent input/output processing+ input_task = asyncio.create_task(self._process_audio_input())+ output_task = asyncio.create_task(self._process_audio_output())+ await asyncio.gather(input_task, output_task)+```++## π‘ Streaming Voice Best Practices++1. **Activity Detection**: Let the pipeline handle speech detection automatically+2. **Turn Management**: Use lifecycle events to manage conversation flow+3. **Concurrent Processing**: Handle input and output streams simultaneously+4. **Buffer Management**: Add silence buffers between turns for natural flow+5. **Error Recovery**: Implement robust error handling for streaming failures+6. **Resource Management**: Properly clean up audio streams and resources++## π Performance Characteristics++### **Streaming Pipeline Benefits**+- **Real-Time Interaction**: Immediate response to user speech+- **Natural Conversation**: Continuous, flowing dialogue+- **Activity Detection**: Automatic turn boundary detection+- **Concurrent Processing**: Parallel input/output handling+- **Scalable**: Handles multiple turns efficiently++### **Technical Advantages**+- **Low Latency**: Minimal delay between speech and response+- **Adaptive**: Handles variable speech patterns+- **Robust**: Automatic error recovery and continuation+- **Efficient**: Chunk-based processing for optimal performance++## π Streaming Features++### **Automatic Turn Detection**+- **Speech Activity Detection**: Automatically detects when user starts speaking+- **Silence Detection**: Identifies when user finishes speaking+- **Turn Boundaries**: Intelligent conversation turn management+- **Continuous Listening**: Always ready for next input++### **Real-Time Processing**+- **Live Transcription**: Speech-to-text as you speak+- **Streaming Agent Response**: AI processing during speech+- **Immediate Audio Output**: Text-to-speech as response generates+- **Parallel Operations**: Multiple processes running simultaneously++### **Lifecycle Management**+- **Turn Events**: `turn_started` and `turn_ended` notifications+- **Session Tracking**: Multi-turn conversation analytics+- **State Management**: Proper resource allocation and cleanup+- **Interruption Handling**: Graceful handling of user interruptions++## π¨ Requirements & Dependencies++### **Core Dependencies**+- `openai-agents[voice]`: OpenAI Agents SDK with voice support+- `sounddevice`: Real-time audio I/O+- `numpy`: Audio data processing+- `threading`: Concurrent audio processing+- `asyncio`: Asynchronous pipeline management++### **System Requirements**+- **Real-Time Audio**: Low-latency audio hardware+- **Microphone**: Good quality microphone for speech detection+- **Processing Power**: Sufficient CPU for real-time processing+- **Network**: Stable connection for streaming API calls++## π Related Examples++- **[Static Voice](../static/README.md)**: Turn-based voice interaction+- **[Voice Pipeline Documentation](https://openai.github.io/openai-agents-python/voice/pipeline/)**: Official pipeline docs+- **[Streaming Events](https://openai.github.io/openai-agents-python/voice/quickstart/)**: Voice event handling++## π οΈ Advanced Customization++### **Custom Activity Detection**+- Implement custom speech detection algorithms+- Add voice activity thresholds+- Configure silence detection parameters++### **Enhanced Session Management**+- Add conversation memory across sessions+- Implement user authentication+- Add conversation logging and analytics++### **Real-Time Features**+- Add live transcription display+- Implement real-time sentiment analysis+- Add voice emotion detection++## π¨ Streaming Considerations++### **Interruption Handling**+The SDK currently doesn't support built-in interruptions. Use lifecycle events to:+- Mute microphone during AI responses (`turn_started`)+- Unmute microphone after responses (`turn_ended`)+- Handle user interruptions gracefully++### **Performance Optimization**+- **Buffer Sizes**: Optimize audio chunk sizes for latency vs. quality+- **Concurrent Limits**: Balance processing threads for performance+- **Memory Management**: Clean up audio buffers regularly+- **Network Optimization**: Handle API call failures gracefully++## π‘ Pro Tips++- **Start Simple**: Begin with basic streaming, add features gradually+- **Monitor Lifecycle Events**: Use callbacks to understand turn flow+- **Test Audio Hardware**: Ensure low-latency audio setup+- **Handle Edge Cases**: Plan for network issues and audio failures+- **Optimize for Conversation**: Design agents for natural dialogue flow++## π Next Steps++After mastering streaming voice agents:+- **Production Deployment**: Scale streaming voice for real applications+- **Custom Voice Models**: Integrate specialized speech models+- **Multi-Modal Agents**: Combine voice with vision and text+- **Enterprise Voice Solutions**: Build robust voice applications++## π― Troubleshooting++### **Common Issues**+- **Audio Latency**: Check audio hardware and buffer settings+- **Speech Detection**: Adjust microphone levels and sensitivity+- **Turn Management**: Monitor lifecycle events for debugging+- **Resource Usage**: Monitor CPU and memory during streaming+- **Network Issues**: Implement retry logic for API failuresdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/__init__.pynew file mode 100644index 00000000..62adf15f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/__init__.py@@ -0,0 +1 @@+# Streaming voice agent examplediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/agent.pynew file mode 100644index 00000000..3a0af3e1--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/agent.py@@ -0,0 +1,327 @@+import asyncio+import random+import threading+import time++import numpy as np++from agents import Agent, function_tool+from agents.extensions.handoff_prompt import prompt_with_handoff_instructions+from agents.voice import (+ StreamedAudioInput,+ SingleAgentVoiceWorkflow,+ SingleAgentWorkflowCallbacks,+ VoicePipeline,+)++from .util import AudioPlayer, StreamedAudioRecorder, create_silence++"""+This is a streaming voice example that processes audio in real-time. Run it via:+`python -m ai_agent_framework_crash_course.openai_sdk_crash_course.11_voice.streamed.agent`++1. The pipeline continuously listens for audio input.+2. It automatically detects when you start and stop speaking.+3. The agent workflow processes speech in real-time.+4. The output is streamed back to you as audio.++This example demonstrates:+- Real-time speech detection and processing+- Streaming audio input and output+- Activity detection for turn-based conversation+- Interruption handling and turn management++Try examples like:+- Start speaking and the agent will respond when you finish+- Try multiple turns of conversation+- Test language handoffs with Spanish or French+"""+++@function_tool+def get_weather(city: str) -> str:+ """Get the weather for a given city."""+ print(f"[debug] get_weather called with city: {city}")+ choices = ["sunny", "cloudy", "rainy", "snowy"]+ return f"The weather in {city} is {random.choice(choices)}."+++@function_tool+def get_time() -> str:+ """Get the current time."""+ import datetime+ current_time = datetime.datetime.now().strftime("%I:%M %p")+ print(f"[debug] get_time called, current time: {current_time}")+ return f"The current time is {current_time}."+++@function_tool+def set_reminder(message: str, minutes: int = 5) -> str:+ """Set a simple reminder (demo function)."""+ print(f"[debug] set_reminder called: '{message}' in {minutes} minutes")+ return f"Reminder set: '{message}' in {minutes} minutes. (This is a demo - no actual reminder will be triggered)"+++@function_tool+def get_news_summary() -> str:+ """Get a brief news summary (demo function)."""+ print("[debug] get_news_summary called")+ # Mock news items+ news_items = [+ "Technology stocks continue to rise amid AI developments",+ "Climate change summit reaches new international agreements",+ "Space exploration mission launches successfully",+ "New renewable energy projects announced globally"+ ]+ selected_news = random.choice(news_items)+ return f"Here's a news update: {selected_news}. This is a demo news summary."+++spanish_agent = Agent(+ name="Spanish",+ handoff_description="A spanish speaking agent.",+ instructions=prompt_with_handoff_instructions(+ "You're speaking to a human in real-time, so be polite and concise. Speak in Spanish only. "+ "Help with weather, time, reminders, and news as needed. Keep responses brief for voice interaction."+ ),+ model="gpt-4o-mini",+ tools=[get_weather, get_time, set_reminder, get_news_summary]+)++french_agent = Agent(+ name="French",+ handoff_description="A french speaking agent.",+ instructions=prompt_with_handoff_instructions(+ "You're speaking to a human in real-time, so be polite and concise. Speak in French only. "+ "Help with weather, time, reminders, and news as needed. Keep responses brief for voice interaction."+ ),+ model="gpt-4o-mini",+ tools=[get_weather, get_time, set_reminder, get_news_summary]+)++agent = Agent(+ name="Assistant",+ instructions=prompt_with_handoff_instructions(+ """You're speaking to a human in real-time voice conversation, so be polite and concise.++ You can help with:+ - Weather information for any city+ - Current time+ - Setting reminders (demo)+ - News summaries (demo)+ - General conversation++ Language handling:+ - If the user speaks in Spanish, handoff to the Spanish agent+ - If the user speaks in French, handoff to the French agent+ - Otherwise, respond in English++ Keep responses brief and conversational since this is a voice interface.+ Acknowledge when users switch topics or ask follow-up questions."""+ ),+ model="gpt-4o-mini",+ handoffs=[spanish_agent, french_agent],+ tools=[get_weather, get_time, set_reminder, get_news_summary],+)+++class StreamingWorkflowCallbacks(SingleAgentWorkflowCallbacks):+ """Custom callbacks to monitor the streaming voice workflow."""++ def __init__(self):+ self.turn_count = 0+ self.start_time = time.time()++ def on_run(self, workflow: SingleAgentVoiceWorkflow, transcription: str) -> None:+ """Called when the workflow runs with a new transcription."""+ self.turn_count += 1+ print(f"\n[debug] π― Turn {self.turn_count} - Transcription: '{transcription}'")++ def on_tool_call(self, tool_name: str, arguments: dict) -> None:+ """Called when a tool is about to be executed."""+ print(f"[debug] π§ Tool call: {tool_name} with args: {arguments}")++ def on_handoff(self, from_agent: str, to_agent: str) -> None:+ """Called when a handoff occurs between agents."""+ print(f"[debug] π Handoff from {from_agent} to {to_agent}")++ def on_turn_start(self) -> None:+ """Called when a new turn starts."""+ elapsed = time.time() - self.start_time+ print(f"[debug] βΆοΈ Turn started (session time: {elapsed:.1f}s)")++ def on_turn_end(self) -> None:+ """Called when a turn ends."""+ print(f"[debug] βΉοΈ Turn ended")+++class VoiceSessionManager:+ """Manages the voice session state and audio streams."""++ def __init__(self):+ self.is_running = False+ self.audio_player = None+ self.pipeline = None+ self.callbacks = StreamingWorkflowCallbacks()+ self._stop_event = threading.Event()++ async def start_session(self):+ """Start the voice session."""+ self.is_running = True+ self._stop_event.clear()++ # Create the voice pipeline+ self.pipeline = VoicePipeline(+ workflow=SingleAgentVoiceWorkflow(agent, callbacks=self.callbacks)+ )++ print("ποΈ Voice session started. Start speaking...")+ print("π‘ Tips:")+ print(" - Speak clearly and pause between sentences")+ print(" - Try asking about weather, time, or setting reminders")+ print(" - Say something in Spanish or French to test language handoffs")+ print(" - Press Ctrl+C to end the session")+ print()++ # Start audio recording and processing+ await self._run_streaming_session()++ async def _run_streaming_session(self):+ """Run the main streaming session loop."""+ with StreamedAudioRecorder() as recorder:+ with AudioPlayer() as player:+ self.audio_player = player++ # Create streamed audio input+ streamed_input = StreamedAudioInput()++ # Start the pipeline processing+ result = await self.pipeline.run(streamed_input)++ # Create tasks for audio input and output processing+ input_task = asyncio.create_task(self._process_audio_input(recorder, streamed_input))+ output_task = asyncio.create_task(self._process_audio_output(result))++ try:+ # Run both tasks concurrently+ await asyncio.gather(input_task, output_task)+ except asyncio.CancelledError:+ print("\nπ Session cancelled")+ finally:+ # Cleanup+ streamed_input.finish()+ self.is_running = False++ async def _process_audio_input(self, recorder: StreamedAudioRecorder, streamed_input: StreamedAudioInput):+ """Process incoming audio from the microphone."""+ print("π€ Listening for audio input...")++ while self.is_running and not self._stop_event.is_set():+ if recorder.has_audio():+ audio_chunk = recorder.get_audio_chunk()+ if audio_chunk is not None:+ # Push audio to the pipeline+ streamed_input.push_audio(audio_chunk)++ # Small delay to prevent busy waiting+ await asyncio.sleep(0.01)++ print("βΉοΈ Audio input processing stopped")++ async def _process_audio_output(self, result):+ """Process outgoing audio to the speakers."""+ print("π Ready to play audio responses...")++ audio_chunks_count = 0++ async for event in result.stream():+ if self._stop_event.is_set():+ break++ if event.type == "voice_stream_event_audio":+ if self.audio_player:+ self.audio_player.add_audio(event.data)+ audio_chunks_count += 1++ # Progress indicator for long responses+ if audio_chunks_count % 20 == 0:+ print(f"π΅ Playing response... ({audio_chunks_count} chunks)")++ elif event.type == "voice_stream_event_lifecycle":+ if event.event == "turn_started":+ print("π AI is processing your speech...")+ elif event.event == "turn_ended":+ print("β AI response complete. You can speak again.")+ # Add a small silence buffer between turns+ if self.audio_player:+ self.audio_player.add_audio(create_silence(0.5))++ elif event.type == "voice_stream_event_error":+ print(f"β Voice error: {event.error}")++ print("βΉοΈ Audio output processing stopped")++ def stop_session(self):+ """Stop the voice session."""+ self.is_running = False+ self._stop_event.set()+ print("\nπ Stopping voice session...")+++async def main():+ """Main function to run the streamed voice agent example."""+ print("ποΈ Streaming Voice Agent Demo")+ print("=" * 50)+ print()++ session_manager = VoiceSessionManager()++ try:+ await session_manager.start_session()+ except KeyboardInterrupt:+ print("\nβΉοΈ Demo interrupted by user.")+ session_manager.stop_session()+ except Exception as e:+ print(f"\nβ Demo failed: {e}")+ import traceback+ traceback.print_exc()+ finally:+ print("\nπ Voice session ended. Thanks for trying the demo!")+++def show_streaming_features():+ """Display information about streaming voice features."""+ print("π Streaming Voice Features:")+ print("=" * 40)+ print()+ print("β¨ Real-time Features:")+ print(" β’ Continuous audio input processing")+ print(" β’ Automatic speech activity detection")+ print(" β’ Real-time agent response streaming")+ print(" β’ Turn-based conversation management")+ print()+ print("π§ Advanced Capabilities:")+ print(" β’ Multi-language support with agent handoffs")+ print(" β’ Tool calling during voice conversation")+ print(" β’ Streaming callbacks for monitoring")+ print(" β’ Interruption handling (via lifecycle events)")+ print()+ print("π― Try These Commands:")+ print(" β’ 'What's the weather in Paris?'")+ print(" β’ 'What time is it?'")+ print(" β’ 'Set a reminder to call mom in 10 minutes'")+ print(" β’ 'Give me a news summary'")+ print(" β’ 'Hola, ΒΏcΓ³mo estΓ‘s?' (Spanish)")+ print(" β’ 'Bonjour, comment Γ§a va?' (French)")+ print()+++if __name__ == "__main__":+ print("π OpenAI Agents SDK - Streaming Voice Demo")+ print("=" * 60)++ # Show streaming features+ show_streaming_features()++ # Run the main demo+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/requirements.txtnew file mode 100644index 00000000..560a2fba--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/requirements.txt@@ -0,0 +1,6 @@+openai-agents[voice]>=1.0.0+sounddevice>=0.4.0+numpy>=1.21.0+soundfile>=0.12.0+librosa>=0.10.0+python-dotenv>=1.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/util.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/util.pynew file mode 100644index 00000000..b974e074--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/streamed/util.py@@ -0,0 +1,229 @@+import threading+import time+from typing import Optional++import numpy as np+import sounddevice as sd+++class AudioPlayer:+ """A simple audio player using sounddevice for real-time audio playback."""++ def __init__(self, sample_rate: int = 24000, channels: int = 1, dtype=np.int16):+ self.sample_rate = sample_rate+ self.channels = channels+ self.dtype = dtype+ self.stream: Optional[sd.OutputStream] = None+ self._stop_event = threading.Event()++ def __enter__(self):+ """Context manager entry - start the audio stream."""+ self.stream = sd.OutputStream(+ samplerate=self.sample_rate,+ channels=self.channels,+ dtype=self.dtype+ )+ self.stream.start()+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Context manager exit - stop and close the audio stream."""+ if self.stream:+ self.stream.stop()+ self.stream.close()++ def add_audio(self, audio_data: np.ndarray):+ """Add audio data to be played immediately."""+ if self.stream and not self._stop_event.is_set():+ try:+ self.stream.write(audio_data)+ except Exception as e:+ print(f"[error] Failed to play audio: {e}")++ def stop(self):+ """Stop the audio player."""+ self._stop_event.set()+++class StreamedAudioRecorder:+ """A streaming audio recorder that captures audio in real-time."""++ def __init__(self, sample_rate: int = 24000, channels: int = 1, dtype=np.int16, chunk_size: int = 1024):+ self.sample_rate = sample_rate+ self.channels = channels+ self.dtype = dtype+ self.chunk_size = chunk_size+ self.stream: Optional[sd.InputStream] = None+ self._audio_queue = []+ self._stop_event = threading.Event()+ self._lock = threading.Lock()++ def __enter__(self):+ """Context manager entry - start the audio stream."""+ self.stream = sd.InputStream(+ samplerate=self.sample_rate,+ channels=self.channels,+ dtype=self.dtype,+ blocksize=self.chunk_size,+ callback=self._audio_callback+ )+ self.stream.start()+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ """Context manager exit - stop and close the audio stream."""+ self._stop_event.set()+ if self.stream:+ self.stream.stop()+ self.stream.close()++ def _audio_callback(self, indata, frames, time, status):+ """Callback function for audio input stream."""+ if status:+ print(f"[warning] Audio input status: {status}")++ with self._lock:+ # Convert to the correct format and add to queue+ audio_chunk = indata.copy().flatten().astype(self.dtype)+ self._audio_queue.append(audio_chunk)++ def get_audio_chunk(self) -> Optional[np.ndarray]:+ """Get the next available audio chunk."""+ with self._lock:+ if self._audio_queue:+ return self._audio_queue.pop(0)+ return None++ def has_audio(self) -> bool:+ """Check if there's audio data available."""+ with self._lock:+ return len(self._audio_queue) > 0++ def stop(self):+ """Stop the recorder."""+ self._stop_event.set()+++def record_audio(+ duration: float = 5.0,+ sample_rate: int = 24000,+ channels: int = 1,+ dtype=np.int16+) -> np.ndarray:+ """+ Record audio from the microphone for a specified duration.++ Args:+ duration: Recording duration in seconds+ sample_rate: Audio sample rate (Hz)+ channels: Number of audio channels+ dtype: Audio data type++ Returns:+ Recorded audio as numpy array+ """+ print(f"π€ Recording audio for {duration} seconds... Press Ctrl+C to stop early.")+ print("Say something now!")++ try:+ # Record audio+ recording = sd.rec(+ int(duration * sample_rate),+ samplerate=sample_rate,+ channels=channels,+ dtype=dtype+ )++ # Wait for recording to complete+ sd.wait()++ print("β Recording completed!")++ # Convert to 1D array if mono+ if channels == 1:+ recording = recording.flatten()++ return recording.astype(dtype)++ except KeyboardInterrupt:+ print("\nβΉοΈ Recording stopped by user.")+ sd.stop()+ if 'recording' in locals():+ return recording[:int(time.time() * sample_rate)].astype(dtype)+ else:+ # Return empty array if no recording was captured+ return np.zeros(sample_rate, dtype=dtype)++ except Exception as e:+ print(f"β Recording failed: {e}")+ return np.zeros(sample_rate, dtype=dtype)+++def create_silence(duration: float = 1.0, sample_rate: int = 24000, dtype=np.int16) -> np.ndarray:+ """+ Create a buffer of silence for the specified duration.++ Args:+ duration: Duration of silence in seconds+ sample_rate: Audio sample rate (Hz)+ dtype: Audio data type++ Returns:+ Silence buffer as numpy array+ """+ return np.zeros(int(duration * sample_rate), dtype=dtype)+++def save_audio(audio_data: np.ndarray, filename: str, sample_rate: int = 24000):+ """+ Save audio data to a WAV file.++ Args:+ audio_data: Audio data as numpy array+ filename: Output filename (should end with .wav)+ sample_rate: Audio sample rate (Hz)+ """+ try:+ import soundfile as sf+ sf.write(filename, audio_data, sample_rate)+ print(f"β Audio saved to {filename}")+ except ImportError:+ print("β soundfile package required for saving audio. Install with: pip install soundfile")+ except Exception as e:+ print(f"β Failed to save audio: {e}")+++def load_audio(filename: str, sample_rate: int = 24000, dtype=np.int16) -> np.ndarray:+ """+ Load audio data from a WAV file.++ Args:+ filename: Input filename+ sample_rate: Target sample rate (will resample if different)+ dtype: Target data type++ Returns:+ Audio data as numpy array+ """+ try:+ import soundfile as sf+ audio_data, original_sr = sf.read(filename)++ # Resample if necessary+ if original_sr != sample_rate:+ import librosa+ audio_data = librosa.resample(audio_data, orig_sr=original_sr, target_sr=sample_rate)++ # Convert to target dtype+ if dtype == np.int16:+ audio_data = (audio_data * 32767).astype(np.int16)++ return audio_data++ except ImportError:+ print("β soundfile and librosa packages required for loading audio.")+ print("Install with: pip install soundfile librosa")+ return np.zeros(sample_rate, dtype=dtype)+ except Exception as e:+ print(f"β Failed to load audio: {e}")+ return np.zeros(sample_rate, dtype=dtype)diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/README.mdnew file mode 100644index 00000000..80840dc6--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/README.md@@ -0,0 +1,44 @@+# Personal Assistant Agent++A basic personal assistant agent demonstrating the fundamental concepts of agent creation with the OpenAI Agents SDK.++## π― What This Demonstrates++- **Basic Agent Definition**: Creating a simple agent with name and instructions+- **Model Configuration**: Using the default GPT-4o model+- **Simple Instructions**: Basic conversational capabilities++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++2. **Run the agent**:+ ```python+ from agents import Runner+ from agent import root_agent++ result = Runner.run_sync(root_agent, "Hello, introduce yourself!")+ print(result.final_output)+ ```++## π‘ Key Concepts++- **Agent Definition**: The `Agent()` class with basic parameters+- **Instructions**: Natural language instructions that guide agent behavior+- **Model Selection**: Default model usage (gpt-4o)++## π Next Steps++This agent demonstrates the absolute basics. For more advanced features, see:+- [Execution Demo Agent](../execution_demo_agent/README.md) - Different execution methods+- [Tutorial 2: Structured Output](../../2_structured_output_agent/README.md) - Pydantic schema outputs+- [Tutorial 3: Tool Using Agent](../../3_tool_using_agent/README.md) - Adding tools and functionsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/agent.pynew file mode 100644index 00000000..f8e3aabe--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/agent.py@@ -0,0 +1,43 @@+from agents import Agent, Runner+import asyncio++# Create an agent for demonstrating different execution methods+root_agent = Agent(+ name="Personal Assistant Agent",+ instructions="""+ You are a helpful personal assistant.++ Your role is to:+ 1. Answer questions clearly and concisely+ 2. Provide helpful information and advice+ 3. Be friendly and professional+ 4. Offer practical solutions to problems++ When users ask questions:+ - Give accurate and helpful responses+ - Explain complex topics in simple terms+ - Offer follow-up suggestions when appropriate+ - Maintain a positive and supportive tone++ Keep responses concise but informative.+ """+)++# Example usage patterns+def sync_example():+ """Synchronous execution example"""+ result = Runner.run_sync(root_agent, "Hello, how does sync execution work?")+ return result.final_output++async def async_example():+ """Asynchronous execution example"""+ result = await Runner.run(root_agent, "Hello, how does async execution work?")+ return result.final_output++async def streaming_example():+ """Streaming execution example"""+ response_text = ""+ async for event in Runner.run_streamed(root_agent, "Tell me about streaming execution"):+ if hasattr(event, 'content') and event.content:+ response_text += event.content+ return response_textdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/env.examplenew file mode 100644index 00000000..4eb3531e--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/1_personal_assistant_agent/env.example@@ -0,0 +1,2 @@+# OpenAI API Configuration+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/README.mdnew file mode 100644index 00000000..da070abb--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/README.md@@ -0,0 +1,146 @@+# π― Tutorial 1: Your First OpenAI Agent++Welcome to your first step in the OpenAI Agents SDK journey! This tutorial introduces you to the fundamental concept of creating a simple AI agent using OpenAI's Agents SDK.++## π― What You'll Learn++- **Basic Agent Creation**: How to create your first OpenAI agent+- **OpenAI SDK Workflow**: Understanding the agent lifecycle+- **Simple Text Processing**: Basic input/output handling+- **Agent Configuration**: Essential parameters and settings++## π§ Core Concept: What is an OpenAI Agent?++An OpenAI agent is a **programmable AI assistant** that can:+- Process user inputs (text, voice, etc.)+- Use AI models (like GPT-4o) to understand and respond+- Perform specific tasks based on your instructions+- Return structured or unstructured responses++Think of it as creating a **smart function** that uses AI to handle complex tasks.++## π§ Key Components++### 1. **Agent Class**+The main building block for creating AI agents in OpenAI SDK:+```python+from agents import Agent+```++### 2. **Essential Parameters**+- `name`: Unique identifier for your agent+- `instructions`: How your agent should behave+- `model`: The AI model to use (defaults to "gpt-4o")++### 3. **Basic Workflow**+1. **Input**: User sends a message+2. **Processing**: Agent uses AI model to understand and respond+3. **Output**: Agent returns a response++## π Tutorial Overview++This tutorial includes **two focused agent examples**:++### **1. Personal Assistant Agent** (`personal_assistant_agent/`)+- Basic agent creation and configuration+- Simple instructions and role definition+- Core Agent class usage++### **2. Execution Demo Agent** (`execution_demo_agent/`)+- Demonstrates different execution methods+- Sync, async, and streaming patterns+- Runner class usage examples++## π Project Structure++```+1_starter_agent/+βββ README.md # This file - concept explanation+βββ requirements.txt # Dependencies+βββ personal_assistant_agent/ # Basic agent creation+β βββ __init__.py+β βββ agent.py # Simple agent definition (20 lines)+βββ execution_demo_agent/ # Execution methods demonstration+β βββ __init__.py+β βββ agent.py # Sync, async, streaming examples+βββ app.py # Streamlit web interface (optional)+βββ env.example # Environment variables template+```++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How to create a basic OpenAI agent+- β Essential agent parameters and their purpose+- β How to run agents synchronously and asynchronously+- β Basic OpenAI SDK workflow and lifecycle+- β How to use streaming responses++## π Getting Started++1. **Set up your environment**:+ ```bash+ # Make sure you have your OpenAI API key+ # Get your API key from: https://platform.openai.com/api-keys+ ```++2. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++3. **Install dependencies**:+ ```bash+ # Install required packages+ pip install -r requirements.txt+ ```++4. **Set up environment variables**:+ ```bash+ # Copy the example environment file+ cp .env.example .env++ # Edit .env and add your OpenAI API key+ # OPENAI_API_KEY=sk-your_openai_key_here+ ```++4. **Test the agent**:+ ```bash+ # Run the agent directly+ python agent.py++ # Or run the Streamlit web interface+ streamlit run app.py+ ```++6. **Try different execution methods**:+ - Test synchronous execution: "What's the weather like today?"+ - Test asynchronous execution: "Tell me a story about AI"+ - Test streaming responses: "Explain machine learning in detail"++## π§ͺ Sample Prompts to Try++- **General Questions**: "What's the capital of France?"+- **Creative Tasks**: "Write a short poem about technology"+- **Problem Solving**: "How can I improve my productivity?"+- **Explanations**: "Explain quantum computing in simple terms"++## π Next Steps++After completing this tutorial, you'll be ready for:+- **[Tutorial 2: Structured Output Agent](../2_structured_output_agent/README.md)** - Learn to create type-safe, structured responses+- **[Tutorial 3: Tool Using Agent](../3_tool_using_agent/README.md)** - Add custom tools and functions to your agent+- **[Tutorial 4: Runner Execution Methods](../4_runner_execution/README.md)** - Master different execution patterns++## π‘ Pro Tips++- **Start Simple**: Begin with basic functionality and add complexity gradually+- **Test Often**: Try different prompts to understand agent behavior+- **Read Instructions**: Clear instructions lead to better agent behavior+- **Experiment**: Try different execution methods to see the differences++## π¨ Troubleshooting++- **API Key Issues**: Make sure your `.env` file contains a valid `OPENAI_API_KEY`+- **Import Errors**: Ensure all dependencies are installed with `pip install -r requirements.txt`+- **Rate Limits**: If you hit rate limits, wait a moment before trying againdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/app.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/app.pynew file mode 100644index 00000000..1451d84c--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/app.py@@ -0,0 +1,172 @@+"""+Streamlit Web Interface for Tutorial 1: Your First Agent++This provides an interactive web interface to test the personal assistant agent+with different execution methods.+"""++import os+import asyncio+import streamlit as st+from dotenv import load_dotenv+from agents import Agent, Runner++# Load environment variables+load_dotenv()++# Page configuration+st.set_page_config(+ page_title="Personal Assistant Agent",+ page_icon="π―",+ layout="wide"+)++# Title and description+st.title("π― Personal Assistant Agent")+st.markdown("**Tutorial 1**: Your first OpenAI agent with different execution methods")++# Check API key+if not os.getenv("OPENAI_API_KEY"):+ st.error("β OPENAI_API_KEY not found. Please create a .env file with your OpenAI API key.")+ st.stop()++# Create the agent[email protected]_resource+def create_agent():+ return Agent(+ name="Personal Assistant",+ instructions="""+ You are a helpful personal assistant.++ Your role is to:+ 1. Answer questions clearly and concisely+ 2. Provide helpful information and advice+ 3. Be friendly and professional+ 4. Offer practical solutions to problems++ When users ask questions:+ - Give accurate and helpful responses+ - Explain complex topics in simple terms+ - Offer follow-up suggestions when appropriate+ - Maintain a positive and supportive tone++ Keep responses concise but informative.+ """+ )++agent = create_agent()++# Sidebar with execution method selection+st.sidebar.title("Execution Methods")+execution_method = st.sidebar.selectbox(+ "Choose execution method:",+ ["Synchronous", "Asynchronous", "Streaming"]+)++st.sidebar.markdown("---")+st.sidebar.markdown("### About Execution Methods")++if execution_method == "Synchronous":+ st.sidebar.info("**Synchronous**: Blocks until response is complete. Simple and straightforward.")+elif execution_method == "Asynchronous":+ st.sidebar.info("**Asynchronous**: Non-blocking execution. Good for concurrent operations.")+else:+ st.sidebar.info("**Streaming**: Real-time response streaming. Great for long responses.")++# Main chat interface+st.markdown("### Chat Interface")++# Initialize chat history+if "messages" not in st.session_state:+ st.session_state.messages = []++# Display chat messages+for message in st.session_state.messages:+ with st.chat_message(message["role"]):+ st.markdown(message["content"])++# Chat input+if prompt := st.chat_input("Ask your personal assistant anything..."):+ # Add user message to chat history+ st.session_state.messages.append({"role": "user", "content": prompt})+ with st.chat_message("user"):+ st.markdown(prompt)++ # Generate assistant response+ with st.chat_message("assistant"):+ try:+ if execution_method == "Synchronous":+ with st.spinner("Thinking..."):+ result = Runner.run_sync(agent, prompt)+ response = result.final_output+ st.markdown(response)++ elif execution_method == "Asynchronous":+ with st.spinner("Processing asynchronously..."):+ async def get_async_response():+ result = await Runner.run(agent, prompt)+ return result.final_output++ response = asyncio.run(get_async_response())+ st.markdown(response)++ else: # Streaming+ response_placeholder = st.empty()+ response_text = ""++ async def stream_response():+ full_response = ""+ async for event in Runner.run_streamed(agent, prompt):+ if hasattr(event, 'content') and event.content:+ full_response += event.content+ response_placeholder.markdown(full_response + "β")++ response_placeholder.markdown(full_response)+ return full_response++ response = asyncio.run(stream_response())++ # Add assistant response to chat history+ st.session_state.messages.append({"role": "assistant", "content": response})++ except Exception as e:+ error_msg = f"β Error: {str(e)}"+ st.error(error_msg)+ st.session_state.messages.append({"role": "assistant", "content": error_msg})++# Clear chat button+if st.sidebar.button("Clear Chat History"):+ st.session_state.messages = []+ st.rerun()++# Example prompts+st.sidebar.markdown("---")+st.sidebar.markdown("### Example Prompts")++example_prompts = [+ "What are 3 productivity tips for remote work?",+ "Explain quantum computing in simple terms",+ "Write a short poem about technology",+ "How can I improve my focus and concentration?",+ "What's the difference between AI and machine learning?"+]++for prompt in example_prompts:+ if st.sidebar.button(prompt, key=f"example_{prompt[:20]}"):+ # Add the example prompt to chat+ st.session_state.messages.append({"role": "user", "content": prompt})+ st.rerun()++# Footer with tutorial information+st.markdown("---")+st.markdown("""+### π Tutorial Information++This is **Tutorial 1** of the OpenAI Agents SDK crash course. You're learning:+- β Basic agent creation with the Agent class+- β Different execution methods (sync, async, streaming)+- β Agent configuration with instructions+- β Interactive web interfaces with Streamlit++**Next**: Try [Tutorial 2: Structured Output Agent](../2_structured_output_agent/) to learn about type-safe responses.+""")diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/env.examplenew file mode 100644index 00000000..5b7105d1--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/env.example@@ -0,0 +1,2 @@+# OpenAI API Configuration+OPENAI_API_KEY=sk-your_openai_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/requirements.txtnew file mode 100644index 00000000..a88bde1d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/1_starter_agent/requirements.txt@@ -0,0 +1,3 @@+openai-agents>=1.0.0+streamlit>=1.28.0+python-dotenv>=1.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/README.mdnew file mode 100644index 00000000..c1dcd494--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/README.md@@ -0,0 +1,59 @@+# Support Ticket Agent++A structured output agent demonstrating Pydantic schema-based responses for customer support ticket creation.++## π― What This Demonstrates++- **Structured Output**: Using Pydantic models to define response schemas+- **Enum Types**: Priority levels with controlled values+- **Optional Fields**: Flexible schema with required and optional properties+- **Field Validation**: Input validation and description metadata++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ from agents import Runner+ from agent import root_agent++ result = Runner.run_sync(root_agent, "I can't log into my account and it's urgent!")+ print(result.final_output) # Returns SupportTicket object+ ```++## π‘ Key Concepts++- **Pydantic Models**: Defining structured response schemas+- **Enum Validation**: Priority levels (low, medium, high, critical)+- **Field Descriptions**: Helping the LLM understand field requirements+- **Optional Fields**: Handling optional vs required data++## π§ͺ Example Usage++```python+# The agent will return a SupportTicket object like:+{+ "title": "Account Login Issue",+ "description": "User unable to access account",+ "priority": "high",+ "category": "account_access",+ "steps_to_reproduce": ["Go to login page", "Enter credentials", "Error occurs"],+ "estimated_resolution_time": "2-4 hours"+}+```++## π Next Steps++- [Product Review Agent](../2_2_product_review_agent/README.md) - Complex structured output+- [Email Generator Agent](../2_3_email_generator_agent/README.md) - Simple structured output+- [Tutorial 3: Tool Using Agent](../../3_tool_using_agent/README.md) - Adding tools to agentsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/__init__.pynew file mode 100644index 00000000..4a345b62--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/__init__.py@@ -0,0 +1 @@+# Support Ticket Agent Packagediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/agent.pynew file mode 100644index 00000000..cb97717c--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/agent.py@@ -0,0 +1,42 @@+from typing import List, Optional+from enum import Enum+from agents import Agent+from pydantic import BaseModel, Field++class Priority(str, Enum):+ LOW = "low"+ MEDIUM = "medium"+ HIGH = "high"+ CRITICAL = "critical"++class SupportTicket(BaseModel):+ title: str = Field(description="A concise summary of the issue")+ description: str = Field(description="Detailed description of the problem")+ priority: Priority = Field(description="The ticket priority level")+ category: str = Field(description="The department this ticket belongs to")+ steps_to_reproduce: Optional[List[str]] = Field(+ description="Steps to reproduce the issue (for technical problems)",+ default=None+ )+ estimated_resolution_time: str = Field(+ description="Estimated time to resolve this issue"+ )++root_agent = Agent(+ name="Support Ticket Creator",+ instructions="""+ You are a support ticket creation assistant that converts customer complaints+ into well-structured support tickets.++ Based on customer descriptions, create structured support tickets with:+ - Clear, concise titles+ - Detailed problem descriptions+ - Appropriate priority levels (low/medium/high/critical)+ - Correct categories (technical/billing/account/product/general)+ - Steps to reproduce for technical issues+ - Realistic resolution time estimates++ IMPORTANT: Response must be valid JSON matching the SupportTicket schema.+ """,+ output_type=SupportTicket+)diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/env.examplenew file mode 100644index 00000000..b6071535--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_1_support_ticket_agent/env.example@@ -0,0 +1,8 @@+# OpenAI API Configuration+OPENAI_API_KEY=your_openai_api_key_here++# Optional: Set a different base URL if using a different provider+# OPENAI_BASE_URL=https://api.openai.com/v1++# Optional: Organization ID if using OpenAI organization+# OPENAI_ORG_ID=your_organization_id_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/README.mdnew file mode 100644index 00000000..48d8fb25--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/README.md@@ -0,0 +1,60 @@+# Product Review Agent++A complex structured output agent demonstrating advanced Pydantic schemas for product review analysis.++## π― What This Demonstrates++- **Complex Schemas**: Multi-field Pydantic models with various data types+- **List Fields**: Arrays of strings for pros/cons analysis+- **Boolean Logic**: Recommendation decisions based on review content+- **Sentiment Analysis**: Automated sentiment classification++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ from agents import Runner+ from agent import root_agent++ review_text = "This laptop is amazing! Great performance, long battery life, but a bit heavy."+ result = Runner.run_sync(root_agent, f"Analyze this review: {review_text}")+ print(result.final_output) # Returns ProductReview object+ ```++## π‘ Key Concepts++- **Rating Validation**: Integer constraints (1-5 stars)+- **Sentiment Enum**: Automatic positive/negative/neutral classification+- **List Processing**: Extracting multiple pros and cons+- **Optional Fields**: Handling missing reviewer information++## π§ͺ Example Output++```python+{+ "product_name": "Gaming Laptop XYZ",+ "rating": 4,+ "summary": "Great performance but heavy design",+ "sentiment": "positive",+ "pros": ["Great performance", "Long battery life", "Good display"],+ "cons": ["Heavy weight", "Expensive price"],+ "recommend": true,+ "reviewer_name": "TechEnthusiast123"+}+```++## π Next Steps++- [Support Ticket Agent](../2_1_support_ticket_agent/README.md) - Basic structured output+- [Tutorial 3: Tool Using Agent](../../3_tool_using_agent/README.md) - Adding tools to agentsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/__init__.pynew file mode 100644index 00000000..947d5a9f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/__init__.py@@ -0,0 +1 @@+# Product Review Agent Packagediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/agent.pynew file mode 100644index 00000000..37d74569--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/agent.py@@ -0,0 +1,46 @@+from typing import List, Optional+from enum import Enum+from agents import Agent+from pydantic import BaseModel, Field++class Sentiment(str, Enum):+ VERY_POSITIVE = "very_positive"+ POSITIVE = "positive"+ NEUTRAL = "neutral"+ NEGATIVE = "negative"+ VERY_NEGATIVE = "very_negative"++class ProductReview(BaseModel):+ product_name: Optional[str] = Field(description="Product name if mentioned", default=None)+ rating: int = Field(description="Star rating (1-5)", ge=1, le=5)+ sentiment: Sentiment = Field(description="Overall sentiment of the review")+ main_positives: List[str] = Field(description="Main positive points mentioned", default=[])+ main_negatives: List[str] = Field(description="Main negative points mentioned", default=[])+ would_recommend: Optional[bool] = Field(description="Whether reviewer would recommend", default=None)+ summary: str = Field(description="Brief summary of the review")++root_agent = Agent(+ name="Product Review Analyzer",+ instructions="""+ You are a product review analysis expert that extracts structured data+ from customer product reviews.++ Analyze the review text and extract:+ - Product name if mentioned+ - Star rating (1-5) based on review tone+ - Sentiment classification (very_positive to very_negative)+ - Main positive and negative points+ - Whether they would recommend (if stated or implied)+ - Brief summary++ RATING GUIDELINES:+ - 5 stars: Excellent, highly satisfied, "amazing", "perfect"+ - 4 stars: Good, satisfied, minor issues+ - 3 stars: Okay, mixed feelings, "decent"+ - 2 stars: Poor, unsatisfied, significant issues+ - 1 star: Terrible, very unsatisfied, "worst"++ IMPORTANT: Response must be valid JSON matching the ProductReview schema.+ """,+ output_type=ProductReview+)diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/env.examplenew file mode 100644index 00000000..b6071535--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/2_2_product_review_agent/env.example@@ -0,0 +1,8 @@+# OpenAI API Configuration+OPENAI_API_KEY=your_openai_api_key_here++# Optional: Set a different base URL if using a different provider+# OPENAI_BASE_URL=https://api.openai.com/v1++# Optional: Organization ID if using OpenAI organization+# OPENAI_ORG_ID=your_organization_id_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/README.mdnew file mode 100644index 00000000..498e8971--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/README.md@@ -0,0 +1,187 @@+# π― Tutorial 2: Structured Output Agent++Learn how to create agents that return **type-safe, structured data** using Pydantic models. This tutorial teaches you how to ensure your agents return consistent, validated JSON responses that your applications can reliably process.++## π― What You'll Learn++- **Structured Outputs**: Using Pydantic models to define response schemas+- **Type Safety**: Ensuring consistent data types and validation+- **JSON Schema Generation**: Automatic schema creation from Python classes+- **Output Validation**: Built-in validation and error handling++## π§ Core Concept: Why Structured Outputs?++Traditional AI responses are unstructured text, making them difficult to process programmatically. Structured outputs solve this by:++- **Consistency**: Always return the same data structure+- **Validation**: Automatic type checking and data validation+- **Integration**: Easy to integrate with databases, APIs, and applications+- **Reliability**: Reduce parsing errors and improve application stability++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β UNSTRUCTURED vs STRUCTURED β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β UNSTRUCTURED OUTPUT: β+β "The customer John Doe submitted a high priority β+β billing issue about charges on January 15th..." β+β β+β STRUCTURED OUTPUT: β+β { β+β "customer_name": "John Doe", β+β "issue_type": "billing", β+β "priority": "high", β+β "date_submitted": "2024-01-15", β+β "description": "Incorrect charges on account" β+β } β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Tutorial Overview++This tutorial includes **three focused structured output examples**:++### **1. Support Ticket Agent** (`2_1_support_ticket_agent/`)+- Basic structured output with enums+- Required and optional fields+- Business validation patterns++### **2. Product Review Agent** (`2_2_product_review_agent/`)+- Complex sentiment analysis schema+- List fields and nested validation+- Rating classification logic++### **3. Email Generator Agent** (`2_3_email_generator_agent/`)+- Simple two-field structure+- Enum validation for tone+- Content formatting patterns++## π Project Structure++```+2_structured_output_agent/+βββ README.md # This file - concept explanation+βββ requirements.txt # Dependencies+βββ 2_1_support_ticket_agent/ # Basic structured output+β βββ __init__.py+β βββ agent.py # Support ticket schema (35 lines)+βββ 2_2_product_review_agent/ # Complex structured output+β βββ __init__.py+β βββ agent.py # Product review analysis (45 lines)+βββ 2_3_email_generator_agent/ # Simple structured output+β βββ __init__.py+β βββ agent.py # Email content generation (30 lines)+βββ app.py # Streamlit web interface (optional)+βββ env.example # Environment variables template+```++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How to define Pydantic models for agent outputs+- β Using the `output_type` parameter in agents+- β Complex data structures with nested models+- β Enum validation for controlled vocabularies+- β Optional fields and default values+- β Custom validation methods++## π Getting Started++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Install dependencies**:+ ```bash+ pip install -r requirements.txt+ ```++2. **Set up environment variables**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Test the support ticket agent**:+ ```bash+ python support_ticket_agent.py+ ```++4. **Test the product review agent**:+ ```bash+ python product_review_agent.py+ ```++5. **Run the interactive web interface**:+ ```bash+ streamlit run app.py+ ```++## π§ͺ Sample Use Cases++### Support Ticket Agent+Try these customer complaints:+- "My billing statement shows duplicate charges for last month's subscription"+- "I can't log into my account and need immediate help"+- "The app keeps crashing when I try to upload files"++### Product Review Agent+Try these product reviews:+- "This laptop is amazing! Great battery life and super fast. Would definitely recommend. 5 stars!"+- "The phone camera quality is poor and battery drains quickly. Not worth the price."+- "Decent product but shipping took forever. Customer service was helpful though."++## π§ Key Pydantic Patterns++### 1. **Basic Model with Enums**+```python+class Priority(str, Enum):+ LOW = "low"+ MEDIUM = "medium"+ HIGH = "high"+ CRITICAL = "critical"++class SupportTicket(BaseModel):+ priority: Priority+ category: str+```++### 2. **Optional Fields with Defaults**+```python+class Review(BaseModel):+ rating: int = Field(ge=1, le=5)+ sentiment: str+ recommend: Optional[bool] = None+```++### 3. **Complex Nested Structures**+```python+class ProductReview(BaseModel):+ product_info: ProductInfo+ review_data: ReviewData+ analysis: ReviewAnalysis+```++## π Next Steps++After completing this tutorial, you'll be ready for:+- **[Tutorial 3: Tool Using Agent](../3_tool_using_agent/README.md)** - Add custom tools and functions+- **[Tutorial 4: Runner Execution Methods](../4_runner_execution/README.md)** - Master different execution patterns+- **[Tutorial 5: Context Management](../5_context_management/README.md)** - Manage state across interactions++## π‘ Pro Tips++- **Design Schemas First**: Plan your data structure before implementing+- **Use Descriptive Fields**: Clear field descriptions improve agent accuracy+- **Validate Constraints**: Use Pydantic validators for business rules+- **Handle Optionals**: Plan for missing or uncertain data+- **Test Edge Cases**: Try incomplete or ambiguous inputs++## π¨ Troubleshooting++- **Validation Errors**: Check that your Pydantic model matches expected output+- **Missing Fields**: Ensure all required fields are included in the schema+- **Type Mismatches**: Verify field types match the data being returned+- **Enum Errors**: Make sure enum values match exactly (case-sensitive)diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/env.examplenew file mode 100644index 00000000..4eb3531e--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/env.example@@ -0,0 +1,2 @@+# OpenAI API Configuration+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/product_review_agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/product_review_agent.pynew file mode 100644index 00000000..219886dc--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/product_review_agent.py@@ -0,0 +1,288 @@+"""+OpenAI Agents SDK Tutorial 2: Structured Output Agent - Product Reviews++This module demonstrates extracting structured data from product reviews+using complex nested Pydantic models.+"""++import os+from typing import List, Optional+from enum import Enum+from dotenv import load_dotenv+from pydantic import BaseModel, Field, validator+from agents import Agent, Runner++# Load environment variables+load_dotenv()++class Sentiment(str, Enum):+ """Review sentiment classification"""+ VERY_POSITIVE = "very_positive"+ POSITIVE = "positive"+ NEUTRAL = "neutral"+ NEGATIVE = "negative"+ VERY_NEGATIVE = "very_negative"++class ProductCategory(str, Enum):+ """Product category classification"""+ ELECTRONICS = "electronics"+ CLOTHING = "clothing"+ HOME = "home"+ BOOKS = "books"+ FOOD = "food"+ BEAUTY = "beauty"+ SPORTS = "sports"+ AUTOMOTIVE = "automotive"+ OTHER = "other"++class ProductInfo(BaseModel):+ """Product information extracted from review"""+ name: Optional[str] = Field(description="Product name if mentioned", default=None)+ category: ProductCategory = Field(description="Inferred product category")+ brand: Optional[str] = Field(description="Brand name if mentioned", default=None)+ price_mentioned: Optional[str] = Field(description="Price if mentioned in review", default=None)++class ReviewMetrics(BaseModel):+ """Quantitative review metrics"""+ rating: int = Field(description="Star rating (1-5)", ge=1, le=5)+ sentiment: Sentiment = Field(description="Overall sentiment of the review")+ confidence_score: float = Field(description="Confidence in sentiment analysis (0-1)", ge=0, le=1)+ word_count: int = Field(description="Approximate word count of review", ge=0)++class ReviewAspects(BaseModel):+ """Specific aspects mentioned in the review"""+ quality: Optional[str] = Field(description="Quality assessment if mentioned", default=None)+ value_for_money: Optional[str] = Field(description="Value assessment if mentioned", default=None)+ shipping: Optional[str] = Field(description="Shipping experience if mentioned", default=None)+ customer_service: Optional[str] = Field(description="Customer service experience if mentioned", default=None)+ ease_of_use: Optional[str] = Field(description="Usability assessment if mentioned", default=None)++class ProductReview(BaseModel):+ """Complete structured product review analysis"""+ product_info: ProductInfo+ metrics: ReviewMetrics+ aspects: ReviewAspects++ # Key insights+ main_positives: List[str] = Field(description="Main positive points mentioned", default=[])+ main_negatives: List[str] = Field(description="Main negative points mentioned", default=[])+ would_recommend: Optional[bool] = Field(description="Whether reviewer would recommend", default=None)++ # Summary+ summary: str = Field(description="Brief summary of the review")+ key_phrases: List[str] = Field(description="Important phrases from the review", default=[])++ @validator('key_phrases')+ def limit_key_phrases(cls, v):+ """Limit key phrases to maximum of 5"""+ return v[:5] if len(v) > 5 else v++# Create the product review agent+product_review_agent = Agent(+ name="Product Review Analyzer",+ instructions="""+ You are a product review analysis expert that extracts structured data+ from customer product reviews.++ Analyze the review text and extract:++ PRODUCT INFO:+ - Product name, brand, category, and price if mentioned+ - Infer category from context if not explicitly stated++ REVIEW METRICS:+ - Star rating (1-5) based on review tone+ - Sentiment classification (very_positive to very_negative)+ - Confidence score for sentiment analysis+ - Approximate word count++ REVIEW ASPECTS:+ - Quality, value for money, shipping, customer service, ease of use+ - Only include aspects that are actually mentioned++ KEY INSIGHTS:+ - Main positive and negative points+ - Whether they would recommend (if stated or implied)+ - Brief summary and key phrases++ RATING GUIDELINES:+ - 5 stars: Excellent, highly satisfied, "amazing", "perfect"+ - 4 stars: Good, satisfied, minor issues+ - 3 stars: Okay, mixed feelings, "decent"+ - 2 stars: Poor, unsatisfied, significant issues+ - 1 star: Terrible, very unsatisfied, "worst"++ SENTIMENT GUIDELINES:+ - very_positive: Extremely enthusiastic, highly recommended+ - positive: Generally satisfied, good experience+ - neutral: Mixed or balanced opinion+ - negative: Generally unsatisfied, disappointed+ - very_negative: Extremely dissatisfied, angry++ Always return a valid JSON object matching the ProductReview schema.+ """,+ output_type=ProductReview+)++def demonstrate_review_analysis():+ """Demonstrate the product review agent with various examples"""+ print("π― OpenAI Agents SDK - Tutorial 2: Product Review Agent")+ print("=" * 60)+ print()++ # Test cases with different types of reviews+ test_reviews = [+ {+ "title": "Positive Electronics Review",+ "review": "This MacBook Pro M2 is absolutely incredible! The battery life lasts all day, the screen is gorgeous, and it's lightning fast. Worth every penny of the $2,499 I paid. Apple really knocked it out of the park. The build quality is premium and it handles video editing like a dream. Highly recommend to any creative professional!"+ },+ {+ "title": "Mixed Clothing Review",+ "review": "The Nike running shoes are decent for the price ($120). Comfortable for short runs but the sizing runs a bit small. Quality seems okay but not amazing. Shipping was fast though, arrived in 2 days. Customer service was helpful when I had questions. Would maybe recommend if you size up."+ },+ {+ "title": "Negative Food Review",+ "review": "Terrible experience with this organic coffee subscription. The beans taste stale and bitter, nothing like the description. Customer service ignored my complaints for weeks. Way overpriced at $35/month for this quality. Save your money and buy local. Will not be ordering again."+ },+ {+ "title": "Neutral Home Product Review",+ "review": "The IKEA desk lamp does its job. Easy to assemble and decent lighting for work. Not the brightest but sufficient. Build quality is what you'd expect for $25. The cord could be longer. It's an okay purchase, nothing special but functional."+ }+ ]++ for i, test_case in enumerate(test_reviews, 1):+ print(f"=== Review Analysis {i}: {test_case['title']} ===")+ print("Original Review:")+ print(f'"{test_case["review"]}"')+ print()++ try:+ # Analyze the review+ result = Runner.run_sync(product_review_agent, test_case["review"])+ analysis = result.final_output++ print("π STRUCTURED ANALYSIS:")+ print(f"π·οΈ Product: {analysis.product_info.name or 'Not specified'}")+ print(f"π’ Brand: {analysis.product_info.brand or 'Not specified'}")+ print(f"π± Category: {analysis.product_info.category.value.title()}")+ if analysis.product_info.price_mentioned:+ print(f"π° Price: {analysis.product_info.price_mentioned}")++ print(f"\nβ Rating: {analysis.metrics.rating}/5 stars")+ print(f"π Sentiment: {analysis.metrics.sentiment.value.replace('_', ' ').title()}")+ print(f"π― Confidence: {analysis.metrics.confidence_score:.1%}")+ print(f"π Word Count: ~{analysis.metrics.word_count}")++ if analysis.main_positives:+ print(f"\nβ Positives: {', '.join(analysis.main_positives)}")+ if analysis.main_negatives:+ print(f"β Negatives: {', '.join(analysis.main_negatives)}")++ if analysis.would_recommend is not None:+ recommend_text = "Yes" if analysis.would_recommend else "No"+ print(f"π Would Recommend: {recommend_text}")++ print(f"\nπ Summary: {analysis.summary}")++ if analysis.key_phrases:+ print(f"π Key Phrases: {', '.join(analysis.key_phrases)}")++ # Show aspects that were mentioned+ aspects_mentioned = []+ if analysis.aspects.quality:+ aspects_mentioned.append(f"Quality: {analysis.aspects.quality}")+ if analysis.aspects.value_for_money:+ aspects_mentioned.append(f"Value: {analysis.aspects.value_for_money}")+ if analysis.aspects.shipping:+ aspects_mentioned.append(f"Shipping: {analysis.aspects.shipping}")+ if analysis.aspects.customer_service:+ aspects_mentioned.append(f"Service: {analysis.aspects.customer_service}")+ if analysis.aspects.ease_of_use:+ aspects_mentioned.append(f"Usability: {analysis.aspects.ease_of_use}")++ if aspects_mentioned:+ print(f"\nπ Specific Aspects: {' | '.join(aspects_mentioned)}")++ except Exception as e:+ print(f"β Error: {e}")++ print()+ print("-" * 60)+ print()++def interactive_mode():+ """Interactive mode for analyzing product reviews"""+ print("=== Interactive Product Review Analysis ===")+ print("Paste a product review and I'll extract structured data from it.")+ print("Type 'quit' to exit.")+ print()++ while True:+ review_text = input("Product Review: ").strip()++ if review_text.lower() in ['quit', 'exit', 'bye']:+ print("Goodbye!")+ break++ if not review_text:+ continue++ try:+ print("\nAnalyzing review...")+ result = Runner.run_sync(product_review_agent, review_text)+ analysis = result.final_output++ print("\n" + "="*50)+ print("π REVIEW ANALYSIS COMPLETE")+ print("="*50)++ # Product Information+ print("π·οΈ PRODUCT INFO:")+ print(f" Name: {analysis.product_info.name or 'Not specified'}")+ print(f" Brand: {analysis.product_info.brand or 'Not specified'}")+ print(f" Category: {analysis.product_info.category.value.title()}")+ if analysis.product_info.price_mentioned:+ print(f" Price: {analysis.product_info.price_mentioned}")++ # Metrics+ print(f"\nπ METRICS:")+ print(f" Rating: {analysis.metrics.rating}/5 β")+ print(f" Sentiment: {analysis.metrics.sentiment.value.replace('_', ' ').title()}")+ print(f" Confidence: {analysis.metrics.confidence_score:.1%}")++ # Key Points+ if analysis.main_positives:+ print(f"\nβ POSITIVES: {', '.join(analysis.main_positives)}")+ if analysis.main_negatives:+ print(f"\nβ NEGATIVES: {', '.join(analysis.main_negatives)}")++ # Summary+ print(f"\nπ SUMMARY: {analysis.summary}")++ print("="*50)+ print()++ except Exception as e:+ print(f"β Error: {e}")+ print()++def main():+ """Main function"""+ # Check API key+ if not os.getenv("OPENAI_API_KEY"):+ print("β Error: OPENAI_API_KEY not found in environment variables")+ print("Please create a .env file with your OpenAI API key")+ return++ try:+ # Run demonstrations+ demonstrate_review_analysis()++ # Interactive mode+ interactive_mode()++ except Exception as e:+ print(f"β Error: {e}")++if __name__ == "__main__":+ main()diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/requirements.txtnew file mode 100644index 00000000..41a538fd--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/requirements.txt@@ -0,0 +1,4 @@+openai-agents>=1.0.0+streamlit>=1.28.0+python-dotenv>=1.0.0+pydantic>=2.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/support_ticket_agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/support_ticket_agent.pynew file mode 100644index 00000000..29a9d62c--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/support_ticket_agent.py@@ -0,0 +1,219 @@+"""+OpenAI Agents SDK Tutorial 2: Structured Output Agent - Support Tickets++This module demonstrates how to create an agent that returns structured data+using Pydantic models for support ticket creation.+"""++import os+from typing import List, Optional+from enum import Enum+from dotenv import load_dotenv+from pydantic import BaseModel, Field+from agents import Agent, Runner++# Load environment variables+load_dotenv()++class Priority(str, Enum):+ """Priority levels for support tickets"""+ LOW = "low"+ MEDIUM = "medium"+ HIGH = "high"+ CRITICAL = "critical"++class Category(str, Enum):+ """Support ticket categories"""+ TECHNICAL = "technical"+ BILLING = "billing"+ ACCOUNT = "account"+ PRODUCT = "product"+ GENERAL = "general"++class SupportTicket(BaseModel):+ """Structured support ticket model"""+ title: str = Field(description="A concise summary of the issue")+ description: str = Field(description="Detailed description of the problem")+ priority: Priority = Field(description="The ticket priority level")+ category: Category = Field(description="The department this ticket belongs to")+ customer_name: Optional[str] = Field(+ description="Customer name if mentioned",+ default=None+ )+ steps_to_reproduce: Optional[List[str]] = Field(+ description="Steps to reproduce the issue (for technical problems)",+ default=None+ )+ estimated_resolution_time: str = Field(+ description="Estimated time to resolve this issue"+ )+ urgency_keywords: List[str] = Field(+ description="Keywords that indicate urgency or importance",+ default=[]+ )++# Create the support ticket agent+support_ticket_agent = Agent(+ name="Support Ticket Creator",+ instructions="""+ You are a support ticket creation assistant that converts customer complaints+ and issues into well-structured support tickets.++ Based on customer descriptions, create structured support tickets with:+ - Clear, concise titles+ - Detailed problem descriptions+ - Appropriate priority levels (low/medium/high/critical)+ - Correct categories (technical/billing/account/product/general)+ - Customer names if mentioned+ - Steps to reproduce for technical issues+ - Realistic resolution time estimates+ - Keywords that indicate urgency++ Priority Guidelines:+ - CRITICAL: System down, security issues, data loss+ - HIGH: Core features not working, urgent business impact+ - MEDIUM: Important features affected, moderate business impact+ - LOW: Minor issues, feature requests, general questions++ Category Guidelines:+ - TECHNICAL: App crashes, login issues, performance problems+ - BILLING: Payment issues, subscription problems, invoice questions+ - ACCOUNT: Profile issues, access problems, account settings+ - PRODUCT: Feature requests, product feedback, functionality questions+ - GENERAL: General inquiries, documentation, training++ Resolution Time Guidelines:+ - Critical: "1-4 hours"+ - High: "4-24 hours"+ - Medium: "1-3 business days"+ - Low: "3-7 business days"++ Always return a valid JSON object matching the SupportTicket schema.+ """,+ output_type=SupportTicket+)++def demonstrate_support_tickets():+ """Demonstrate the support ticket agent with various examples"""+ print("π― OpenAI Agents SDK - Tutorial 2: Support Ticket Agent")+ print("=" * 60)+ print()++ # Test cases with different types of issues+ test_cases = [+ {+ "description": "Billing Issue",+ "complaint": "Hi, I'm John Smith and I noticed my credit card was charged twice for last month's premium subscription. I only signed up once but see two $29.99 charges on my statement from January 15th. This needs to be resolved quickly as it's affecting my budget."+ },+ {+ "description": "Technical Issue",+ "complaint": "The mobile app keeps crashing whenever I try to upload photos. I'm using an iPhone 14 with iOS 17. Steps: 1) Open app 2) Go to gallery 3) Select photo 4) Tap upload 5) App crashes immediately. This is blocking my work completely!"+ },+ {+ "description": "Account Issue",+ "complaint": "I can't log into my account. My username is [email protected] and I keep getting 'invalid credentials' even though I'm sure my password is correct. I've tried resetting it but never received the email. I need access urgently for a client meeting tomorrow."+ },+ {+ "description": "Low Priority Request",+ "complaint": "Hey there! I was wondering if you could add a dark mode feature to the app? It would be really nice to have, especially for us night owls. Not urgent at all, just a suggestion. Thanks!"+ }+ ]++ for i, test_case in enumerate(test_cases, 1):+ print(f"=== Test Case {i}: {test_case['description']} ===")+ print(f"Customer Complaint:")+ print(f'"{test_case["complaint"]}"')+ print()++ try:+ # Generate structured support ticket+ result = Runner.run_sync(support_ticket_agent, test_case["complaint"])+ ticket = result.final_output++ print("Generated Support Ticket:")+ print(f"π Title: {ticket.title}")+ print(f"π·οΈ Category: {ticket.category.value.title()}")+ print(f"β‘ Priority: {ticket.priority.value.title()}")+ if ticket.customer_name:+ print(f"π€ Customer: {ticket.customer_name}")+ print(f"π Description: {ticket.description}")+ if ticket.steps_to_reproduce:+ print(f"π Steps to Reproduce:")+ for step in ticket.steps_to_reproduce:+ print(f" β’ {step}")+ print(f"β±οΈ Estimated Resolution: {ticket.estimated_resolution_time}")+ if ticket.urgency_keywords:+ print(f"π¨ Urgency Keywords: {', '.join(ticket.urgency_keywords)}")++ except Exception as e:+ print(f"β Error: {e}")++ print()+ print("-" * 60)+ print()++def interactive_mode():+ """Interactive mode for creating support tickets"""+ print("=== Interactive Support Ticket Creation ===")+ print("Describe a customer issue and I'll create a structured support ticket.")+ print("Type 'quit' to exit.")+ print()++ while True:+ complaint = input("Customer Complaint: ").strip()++ if complaint.lower() in ['quit', 'exit', 'bye']:+ print("Goodbye!")+ break++ if not complaint:+ continue++ try:+ print("\nGenerating support ticket...")+ result = Runner.run_sync(support_ticket_agent, complaint)+ ticket = result.final_output++ print("\n" + "="*50)+ print("π SUPPORT TICKET CREATED")+ print("="*50)+ print(f"Title: {ticket.title}")+ print(f"Category: {ticket.category.value.title()}")+ print(f"Priority: {ticket.priority.value.title()}")+ if ticket.customer_name:+ print(f"Customer: {ticket.customer_name}")+ print(f"Description: {ticket.description}")+ if ticket.steps_to_reproduce:+ print("Steps to Reproduce:")+ for i, step in enumerate(ticket.steps_to_reproduce, 1):+ print(f" {i}. {step}")+ print(f"Estimated Resolution: {ticket.estimated_resolution_time}")+ if ticket.urgency_keywords:+ print(f"Urgency Keywords: {', '.join(ticket.urgency_keywords)}")+ print("="*50)+ print()++ except Exception as e:+ print(f"β Error: {e}")+ print()++def main():+ """Main function"""+ # Check API key+ if not os.getenv("OPENAI_API_KEY"):+ print("β Error: OPENAI_API_KEY not found in environment variables")+ print("Please create a .env file with your OpenAI API key")+ return++ try:+ # Run demonstrations+ demonstrate_support_tickets()++ # Interactive mode+ interactive_mode()++ except Exception as e:+ print(f"β Error: {e}")++if __name__ == "__main__":+ main()diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/README.mdnew file mode 100644index 00000000..a68636e1--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/README.md@@ -0,0 +1,54 @@+# Function Tools Agent++Demonstrates custom function tools creation using the `@function_tool` decorator.++## π― What This Demonstrates++- **Custom Function Tools**: Creating tools with `@function_tool` decorator+- **Tool Descriptions**: Providing clear docstrings for LLM understanding+- **Parameter Handling**: Type hints and default parameters+- **Error Handling**: Graceful tool failure management++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ from agents import Runner+ from agent import root_agent++ result = Runner.run_sync(root_agent, "What time is it in New York?")+ print(result.final_output)+ ```++## π‘ Key Concepts++- **@function_tool Decorator**: Converting Python functions to agent tools+- **Tool Docstrings**: How LLM understands when to use tools+- **Type Hints**: Parameter validation and documentation+- **Tool Registration**: Adding tools to agent configuration++## π§ͺ Available Tools++### `get_current_time(timezone: str = "UTC")`+- Returns current time in specified timezone+- Handles timezone validation and error cases++### `greet_user(name: str)`+- Simple greeting tool demonstrating basic tool usage+- Shows parameter passing from LLM to tool++## π Next Steps++- [Built-in Tools](../3_2_builtin_tools/README.md) - Using WebSearch, CodeInterpreter+- [Agents as Tools](../3_3_agents_as_tools/README.md) - Advanced agent orchestrationdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/__init__.pynew file mode 100644index 00000000..04b04664--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/__init__.py@@ -0,0 +1 @@+# Function Tools Agent Packagediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/agent.pynew file mode 100644index 00000000..4f46a633--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/agent.py@@ -0,0 +1,24 @@+from agents import Agent+from .tools import add_numbers, multiply_numbers, get_weather, convert_temperature++# Create an agent with custom function tools+root_agent = Agent(+ name="Function Tools Agent",+ instructions="""+ You are a helpful assistant with access to various tools.++ Available tools:+ - add_numbers: Add two numbers together+ - multiply_numbers: Multiply two numbers together+ - get_weather: Get weather information for a city+ - convert_temperature: Convert between Celsius and Fahrenheit++ When users ask for calculations or information:+ 1. Use the appropriate tool for the task+ 2. Explain what you're doing+ 3. Show the result clearly++ Always use the provided tools rather than doing calculations yourself.+ """,+ tools=[add_numbers, multiply_numbers, get_weather, convert_temperature]+)diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/env.examplenew file mode 100644index 00000000..4eb3531e--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/env.example@@ -0,0 +1,2 @@+# OpenAI API Configuration+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/tools.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/tools.pynew file mode 100644index 00000000..cac737ca--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_1_function_tools/tools.py@@ -0,0 +1,28 @@+from agents import function_tool++@function_tool+def add_numbers(a: float, b: float) -> float:+ """Add two numbers together"""+ return a + b++@function_tool+def multiply_numbers(a: float, b: float) -> float:+ """Multiply two numbers together"""+ return a * b++@function_tool+def get_weather(city: str) -> str:+ """Get weather information for a city (mock implementation)"""+ return f"The weather in {city} is sunny with 72Β°F"++@function_tool+def convert_temperature(temperature: float, from_unit: str, to_unit: str) -> str:+ """Convert temperature between Celsius and Fahrenheit"""+ if from_unit.lower() == "celsius" and to_unit.lower() == "fahrenheit":+ result = (temperature * 9/5) + 32+ return f"{temperature}Β°C = {result:.1f}Β°F"+ elif from_unit.lower() == "fahrenheit" and to_unit.lower() == "celsius":+ result = (temperature - 32) * 5/9+ return f"{temperature}Β°F = {result:.1f}Β°C"+ else:+ return "Unsupported temperature conversion"diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/README.mdnew file mode 100644index 00000000..e73861f4--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/README.md@@ -0,0 +1,56 @@+# Built-in Tools Agent++Demonstrates using OpenAI Agents SDK built-in tools like WebSearchTool and CodeInterpreterTool.++## π― What This Demonstrates++- **WebSearchTool**: Real-time web search capabilities+- **CodeInterpreterTool**: Code execution and mathematical computation+- **Built-in Tool Integration**: Using pre-configured SDK tools+- **Tool Combination**: Leveraging multiple tools in one agent++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ from agents import Runner+ from agent import root_agent++ result = Runner.run_sync(root_agent, "What's the latest news about AI and calculate 15% of 200?")+ print(result.final_output)+ ```++## π‘ Key Concepts++- **WebSearchTool()**: Search the web for current information+- **CodeInterpreterTool()**: Execute Python code and calculations+- **Tool Instantiation**: Creating tool instances with default configurations+- **Multi-tool Agents**: Combining different tool types++## π§ͺ Available Tools++### WebSearchTool+- Search for current information on the internet+- Useful for factual questions requiring recent data+- Automatically formats search results for agent use++### CodeInterpreterTool+- Execute Python code in a secure environment+- Perfect for mathematical calculations+- Can handle data analysis and complex computations++## π Next Steps++- [Function Tools](../3_1_function_tools/README.md) - Custom function tools+- [Agents as Tools](../3_3_agents_as_tools/README.md) - Advanced orchestration patternsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/__init__.pynew file mode 100644index 00000000..69a20a64--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/__init__.py@@ -0,0 +1 @@+# Built-in Tools Agent Packagediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/agent.pynew file mode 100644index 00000000..260abd5f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/agent.py@@ -0,0 +1,26 @@+from agents import Agent+from agents.tools import WebSearchTool, CodeInterpreterTool++# Create an agent with built-in OpenAI tools+root_agent = Agent(+ name="Built-in Tools Agent",+ instructions="""+ You are a research and computation assistant with access to powerful built-in tools.++ Available tools:+ - WebSearchTool: Search the web for current information+ - CodeInterpreterTool: Execute Python code safely++ You can help with:+ - Finding current information and news+ - Performing complex calculations+ - Data analysis and visualization+ - Mathematical computations++ When users request information or calculations:+ 1. Use web search for current information+ 2. Use code execution for computations and analysis+ 3. Provide clear explanations of results+ """,+ tools=[WebSearchTool(), CodeInterpreterTool()]+)diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/env.examplenew file mode 100644index 00000000..4eb3531e--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_2_builtin_tools/env.example@@ -0,0 +1,2 @@+# OpenAI API Configuration+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/README.mdnew file mode 100644index 00000000..5757ecc9--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/README.md@@ -0,0 +1,70 @@+# Agents as Tools++Demonstrates advanced orchestration patterns where agents are used as tools by other agents.++## π― What This Demonstrates++- **Agent.as_tool()**: Converting agents to tools for orchestration+- **Custom Agent Tools**: Using `@function_tool` with `Runner.run()`+- **Multi-Agent Workflows**: Coordinating multiple specialized agents+- **Custom Configuration**: Per-agent settings like max_turns and run_config++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run basic orchestration**:+ ```python+ from agents import Runner+ from agent import root_agent++ result = Runner.run_sync(root_agent, "Say 'Hello, how are you?' in Spanish.")+ print(result.final_output)+ ```++4. **Try advanced orchestration**:+ ```python+ from advanced_agent import advanced_orchestrator++ result = Runner.run_sync(advanced_orchestrator, "Research the benefits of AI in healthcare.")+ print(result.final_output)+ ```++## π‘ Key Concepts++### Basic Agent Tools (`agent.py`)+- **Agent.as_tool()**: Simple agent-to-tool conversion+- **Translation Orchestration**: Multiple language agents coordinated+- **Tool Naming**: Custom tool names and descriptions++### Advanced Agent Tools (`advanced_agent.py`)+- **@function_tool with Runner.run()**: Custom agent tool implementations+- **Custom Configuration**: Per-run settings (max_turns, temperature)+- **Research-Writing Pipeline**: Complex multi-stage workflows++## π§ͺ Available Patterns++### Basic Orchestration+- Spanish translation agent+- French translation agent+- Orchestrator coordinates language tasks++### Advanced Orchestration+- Research agent for information gathering+- Writing agent for content creation+- Custom tool functions with Runner configuration++## π Next Steps++- [Function Tools](../3_1_function_tools/README.md) - Custom function tools+- [Built-in Tools](../3_2_builtin_tools/README.md) - SDK provided tools+- [Tutorial 4: Running Agents](../../4_running_agents/README.md) - Advanced execution patternsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/__init__.pynew file mode 100644index 00000000..7408eb04--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/__init__.py@@ -0,0 +1 @@+# Agents as Tools Packagediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/advanced_agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/advanced_agent.pynew file mode 100644index 00000000..cb79f71b--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/advanced_agent.py@@ -0,0 +1,65 @@+from agents import Agent, Runner, function_tool++# Define a specialized research agent+research_agent = Agent(+ name="Research Specialist",+ instructions="""+ You are a research specialist. Provide detailed, well-researched information+ on any topic with proper analysis and insights.+ """+)++# Define a writing agent+writing_agent = Agent(+ name="Writing Specialist",+ instructions="""+ You are a professional writer. Take research information and create+ well-structured, engaging content with proper formatting.+ """+)++@function_tool+async def run_research_agent(topic: str) -> str:+ """Research a topic using the specialized research agent with custom configuration"""++ result = await Runner.run(+ research_agent,+ input=f"Research this topic thoroughly: {topic}",+ max_turns=3 # Custom configuration+ )++ return str(result.final_output)++@function_tool+async def run_writing_agent(content: str, style: str = "professional") -> str:+ """Transform content using the specialized writing agent with custom style"""++ prompt = f"Rewrite this content in a {style} style: {content}"++ result = await Runner.run(+ writing_agent,+ input=prompt,+ max_turns=2 # Custom configuration+ )++ return str(result.final_output)++# Create orchestrator with custom agent tools+advanced_orchestrator = Agent(+ name="Content Creation Orchestrator",+ instructions="""+ You are a content creation orchestrator that combines research and writing expertise.++ You have access to:+ - Research agent: For in-depth topic research+ - Writing agent: For professional content creation++ When users request content:+ 1. First use the research agent to gather information+ 2. Then use the writing agent to create polished content+ 3. You can specify writing styles (professional, casual, academic, etc.)++ Coordinate both agents to create comprehensive, well-written content.+ """,+ tools=[run_research_agent, run_writing_agent]+)diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/agent.pynew file mode 100644index 00000000..c57861f4--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/agent.py@@ -0,0 +1,51 @@+from agents import Agent++# Define specialized translation agents+spanish_agent = Agent(+ name="Spanish Agent",+ instructions="You translate the user's message to Spanish"+)++french_agent = Agent(+ name="French Agent",+ instructions="You translate the user's message to French"+)++german_agent = Agent(+ name="German Agent",+ instructions="You translate the user's message to German"+)++# Create orchestrator agent that uses other agents as tools+root_agent = Agent(+ name="Translation Orchestrator",+ instructions="""+ You are a translation orchestrator agent. You coordinate specialized translation agents.++ You have access to translation agents for:+ - Spanish translations+ - French translations+ - German translations++ When users request translations:+ 1. Use the appropriate translation agent tool+ 2. You can use multiple agents if asked for multiple translations+ 3. Present the results clearly with language labels++ If asked for multiple translations, call the relevant tools for each language.+ """,+ tools=[+ spanish_agent.as_tool(+ tool_name="translate_to_spanish",+ tool_description="Translate the user's message to Spanish"+ ),+ french_agent.as_tool(+ tool_name="translate_to_french",+ tool_description="Translate the user's message to French"+ ),+ german_agent.as_tool(+ tool_name="translate_to_german",+ tool_description="Translate the user's message to German"+ )+ ]+)diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/env.examplenew file mode 100644index 00000000..b6071535--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/3_3_agents_as_tools/env.example@@ -0,0 +1,8 @@+# OpenAI API Configuration+OPENAI_API_KEY=your_openai_api_key_here++# Optional: Set a different base URL if using a different provider+# OPENAI_BASE_URL=https://api.openai.com/v1++# Optional: Organization ID if using OpenAI organization+# OPENAI_ORG_ID=your_organization_id_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/README.mdnew file mode 100644index 00000000..723a44c8--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/README.md@@ -0,0 +1,233 @@+# π― Tutorial 3: Tool Using Agent++Welcome to the world of tools! This tutorial teaches you how to create agents that can use **custom functions and built-in tools** to perform specific tasks. This is where your agents become truly powerful and capable of real-world actions.++## π― What You'll Learn++- **Function Tools**: Creating custom Python functions as agent tools+- **Built-in Tools**: Using OpenAI's pre-built capabilities+- **Tool Integration**: Adding tools to agents effectively+- **Tool Execution**: Understanding how agents decide when to use tools++## π§ Core Concept: Tools in OpenAI Agents SDK++Tools are **functions that your agent can call** to perform specific tasks. Think of them as the agent's "hands" - they allow the agent to:+- Perform calculations and data processing+- Search the web and access real-time information+- Execute code and analyze data+- Call external APIs and services+- Access databases and file systems++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β AGENT WITH TOOLS β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β βββββββββββββββ βββββββββββββββ βββββββββββββββ β+β β INPUT βββββΆβ AGENT βββββΆβ OUTPUT β β+β β "Calculate β β Reasoning β β "Using the β β+β β compound β β + Tool Use β β calculator β β+β β interest" β β β β tool: $..."β β+β βββββββββββββββ βββββββββββββββ βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ β+β β TOOLS β β+β β βββββββββββ β β+β β βCalculatorβ β β+β β βββββββββββ€ β β+β β βWeb Searchβ β β+β β βββββββββββ€ β β+β β βFile I/O β β β+β β βββββββββββ β β+β βββββββββββββββ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π§ Types of Tools++### 1. **Function Tools**+Custom Python functions you create:+```python+@function_tool+def calculate_compound_interest(principal: float, rate: float, time: int) -> float:+ """Calculate compound interest"""+ return principal * (1 + rate) ** time+```++### 2. **Built-in Tools**+OpenAI provides powerful pre-built tools:+- **WebSearchTool**: Search the web for current information+- **CodeInterpreterTool**: Execute Python code safely+- **FileSearchTool**: Search through uploaded files++## π Tutorial Overview++This tutorial includes **three focused tool integration examples**:++### **1. Function Tools** (`3_1_function_tools/`)+- Custom Python functions as tools+- `@function_tool` decorator usage+- Basic mathematical and utility functions++### **2. Built-in Tools** (`3_2_builtin_tools/`)+- OpenAI's WebSearchTool integration+- CodeInterpreterTool for computations+- Pre-built tool capabilities++### **3. Agents as Tools** (`3_3_agents_as_tools/`)+- Using agents as tools for orchestration+- Specialized agent coordination+- Advanced agent composition patterns++## π Project Structure++```+3_tool_using_agent/+βββ README.md # This file - concept explanation+βββ requirements.txt # Dependencies+βββ 3_1_function_tools/ # Custom function tools+β βββ __init__.py+β βββ tools.py # Custom tool definitions+β βββ agent.py # Agent with function tools (25 lines)+βββ 3_2_builtin_tools/ # Built-in tools integration+β βββ __init__.py+β βββ agent.py # Agent with built-in tools (30 lines)+βββ 3_3_agents_as_tools/ # Agents as tools pattern+β βββ __init__.py+β βββ agent.py # Basic agent orchestration (40 lines)+β βββ advanced_agent.py # Custom agent tools with Runner config+βββ app.py # Streamlit web interface (optional)+βββ env.example # Environment variables template+```++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How to create custom function tools with `@function_tool`+- β How to integrate built-in tools like WebSearch and CodeInterpreter+- β How agents decide when and how to use tools+- β Best practices for tool design and integration+- β Error handling and tool validation++## π Getting Started++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Install dependencies**:+ ```bash+ pip install -r requirements.txt+ ```++2. **Set up environment variables**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Test the calculator agent**:+ ```bash+ python calculator_agent.py+ ```++4. **Test the research agent**:+ ```bash+ python research_agent.py+ ```++5. **Test the data analysis agent**:+ ```bash+ python data_analysis_agent.py+ ```++6. **Run the interactive web interface**:+ ```bash+ streamlit run app.py+ ```++## π§ͺ Sample Use Cases++### Agents as Tools+Try these orchestration requests:+- "Translate 'Hello, how are you?' to Spanish and French"+- "Say 'Good morning' in all available languages"+- "Research artificial intelligence and write a professional summary"++### Research Agent+Try these information requests:+- "What's the latest news about artificial intelligence?"+- "Find information about renewable energy trends in 2024"+- "Search for Python programming best practices"++### Data Analysis Agent+Try these data requests:+- "Analyze this CSV data: [paste some data]"+- "Create a simple bar chart of sales data"+- "Calculate statistical measures for this dataset"++## π§ Key Tool Patterns++### 1. **Simple Function Tool**+```python+@function_tool+def add_numbers(a: float, b: float) -> float:+ """Add two numbers together"""+ return a + b+```++### 2. **Complex Function Tool with Validation**+```python+@function_tool+def get_weather(city: str, units: str = "metric") -> str:+ """Get current weather for a city"""+ if not city.strip():+ return "Error: City name cannot be empty"++ # API call logic here+ return f"Weather data for {city}"+```++### 3. **Agents as Tools Integration**+```python+from agents import Agent++# Define specialized agents+translator = Agent(name="Translator", instructions="Translate text")++# Use agent as a tool+orchestrator = Agent(+ name="Orchestrator",+ instructions="Coordinate translation tasks",+ tools=[+ translator.as_tool(+ tool_name="translate_text",+ tool_description="Translate user's message"+ )+ ]+)+```++## π‘ Tool Design Best Practices++1. **Clear Docstrings**: Tools need descriptive docstrings for the agent to understand their purpose+2. **Type Hints**: Always use proper type hints for parameters and return values+3. **Error Handling**: Handle errors gracefully and return meaningful messages+4. **Simple Parameters**: Keep tool parameters simple and well-defined+5. **Single Purpose**: Each tool should do one thing well++## π Next Steps++After completing this tutorial, you'll be ready for:+- **[Tutorial 4: Runner Execution Methods](../4_runner_execution/README.md)** - Master different execution patterns+- **[Tutorial 5: Context Management](../5_context_management/README.md)** - Manage state across interactions+- **[Tutorial 6: Guardrails & Validation](../6_guardrails_validation/README.md)** - Add safety and validation++## π¨ Troubleshooting++- **Tool Not Called**: Check that your tool docstring clearly describes its purpose+- **Type Errors**: Verify that parameter types match the function signature+- **Import Issues**: Make sure you've imported the `function_tool` decorator+- **API Errors**: For built-in tools, check your OpenAI API key and permissionsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/calculator_agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/calculator_agent.pynew file mode 100644index 00000000..002b3345--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/calculator_agent.py@@ -0,0 +1,208 @@+"""+OpenAI Agents SDK Tutorial 3: Tool Using Agent - Calculator++This module demonstrates how to create custom function tools for mathematical operations.+"""++import os+import math+from dotenv import load_dotenv+from agents import Agent, Runner, function_tool++# Load environment variables+load_dotenv()++@function_tool+def add_numbers(a: float, b: float) -> float:+ """Add two numbers together"""+ return a + b++@function_tool+def subtract_numbers(a: float, b: float) -> float:+ """Subtract second number from first number"""+ return a - b++@function_tool+def multiply_numbers(a: float, b: float) -> float:+ """Multiply two numbers together"""+ return a * b++@function_tool+def divide_numbers(a: float, b: float) -> float:+ """Divide first number by second number"""+ if b == 0:+ return "Error: Cannot divide by zero"+ return a / b++@function_tool+def calculate_compound_interest(principal: float, rate: float, time: int, compounds_per_year: int = 1) -> str:+ """Calculate compound interest using the formula A = P(1 + r/n)^(nt)"""+ if principal <= 0 or rate < 0 or time <= 0 or compounds_per_year <= 0:+ return "Error: All values must be positive"++ # Convert percentage to decimal if needed+ if rate > 1:+ rate = rate / 100++ amount = principal * (1 + rate/compounds_per_year) ** (compounds_per_year * time)+ interest = amount - principal++ return f"Principal: ${principal:,.2f}, Final Amount: ${amount:,.2f}, Interest Earned: ${interest:,.2f}"++@function_tool+def calculate_circle_area(radius: float) -> str:+ """Calculate the area of a circle given its radius"""+ if radius <= 0:+ return "Error: Radius must be positive"++ area = math.pi * radius ** 2+ return f"Circle with radius {radius} has area {area:.2f} square units"++@function_tool+def calculate_triangle_area(base: float, height: float) -> str:+ """Calculate the area of a triangle given base and height"""+ if base <= 0 or height <= 0:+ return "Error: Base and height must be positive"++ area = 0.5 * base * height+ return f"Triangle with base {base} and height {height} has area {area:.2f} square units"++@function_tool+def convert_temperature(temperature: float, from_unit: str, to_unit: str) -> str:+ """Convert temperature between Celsius, Fahrenheit, and Kelvin"""+ from_unit = from_unit.lower()+ to_unit = to_unit.lower()++ # Convert to Celsius first+ if from_unit == "fahrenheit" or from_unit == "f":+ celsius = (temperature - 32) * 5/9+ elif from_unit == "kelvin" or from_unit == "k":+ celsius = temperature - 273.15+ elif from_unit == "celsius" or from_unit == "c":+ celsius = temperature+ else:+ return "Error: Supported units are Celsius, Fahrenheit, and Kelvin"++ # Convert from Celsius to target unit+ if to_unit == "fahrenheit" or to_unit == "f":+ result = celsius * 9/5 + 32+ unit_symbol = "Β°F"+ elif to_unit == "kelvin" or to_unit == "k":+ result = celsius + 273.15+ unit_symbol = "K"+ elif to_unit == "celsius" or to_unit == "c":+ result = celsius+ unit_symbol = "Β°C"+ else:+ return "Error: Supported units are Celsius, Fahrenheit, and Kelvin"++ return f"{temperature}Β° {from_unit.title()} = {result:.2f}{unit_symbol}"++# Create the calculator agent+calculator_agent = Agent(+ name="Calculator Agent",+ instructions="""+ You are a mathematical calculator assistant with access to various calculation tools.++ You can help with:+ - Basic arithmetic (addition, subtraction, multiplication, division)+ - Compound interest calculations+ - Geometric calculations (circle and triangle areas)+ - Temperature conversions between Celsius, Fahrenheit, and Kelvin++ When users ask for calculations:+ 1. Use the appropriate tool for the calculation+ 2. Explain what calculation you're performing+ 3. Show the result clearly+ 4. Provide additional context if helpful++ Always use the provided tools rather than doing calculations yourself.+ Be helpful and explain your calculations step by step.+ """,+ tools=[+ add_numbers,+ subtract_numbers,+ multiply_numbers,+ divide_numbers,+ calculate_compound_interest,+ calculate_circle_area,+ calculate_triangle_area,+ convert_temperature+ ]+)++def demonstrate_calculator():+ """Demonstrate the calculator agent with various examples"""+ print("π― OpenAI Agents SDK - Tutorial 3: Calculator Agent")+ print("=" * 60)+ print()++ # Test cases+ test_cases = [+ "Calculate 15 + 27",+ "What's the compound interest on $5000 at 3.5% for 8 years?",+ "Find the area of a circle with radius 12",+ "Convert 100 degrees Fahrenheit to Celsius",+ "What's 144 divided by 12?",+ "Calculate the area of a triangle with base 8 and height 6"+ ]++ for i, question in enumerate(test_cases, 1):+ print(f"=== Calculation {i} ===")+ print(f"Question: {question}")++ try:+ result = Runner.run_sync(calculator_agent, question)+ print(f"Answer: {result.final_output}")+ except Exception as e:+ print(f"β Error: {e}")++ print()+ print("-" * 40)+ print()++def interactive_mode():+ """Interactive calculator mode"""+ print("=== Interactive Calculator ===")+ print("Ask me to perform any mathematical calculation!")+ print("Type 'quit' to exit.")+ print()++ while True:+ question = input("Math Question: ").strip()++ if question.lower() in ['quit', 'exit', 'bye']:+ print("Goodbye!")+ break++ if not question:+ continue++ try:+ result = Runner.run_sync(calculator_agent, question)+ print(f"π Answer: {result.final_output}")+ print()+ except Exception as e:+ print(f"β Error: {e}")+ print()++def main():+ """Main function"""+ # Check API key+ if not os.getenv("OPENAI_API_KEY"):+ print("β Error: OPENAI_API_KEY not found in environment variables")+ print("Please create a .env file with your OpenAI API key")+ return++ try:+ # Run demonstrations+ demonstrate_calculator()++ # Interactive mode+ interactive_mode()++ except Exception as e:+ print(f"β Error: {e}")++if __name__ == "__main__":+ main()diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/env.examplenew file mode 100644index 00000000..b6071535--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/env.example@@ -0,0 +1,8 @@+# OpenAI API Configuration+OPENAI_API_KEY=your_openai_api_key_here++# Optional: Set a different base URL if using a different provider+# OPENAI_BASE_URL=https://api.openai.com/v1++# Optional: Organization ID if using OpenAI organization+# OPENAI_ORG_ID=your_organization_id_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/README.mdnew file mode 100644index 00000000..78eb9a4f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/README.md@@ -0,0 +1,45 @@+# Execution Methods++Demonstrates the three execution methods available in the OpenAI Agents SDK: sync, async, and streaming.++## π― What This Demonstrates++- **Runner.run()**: Asynchronous execution for non-blocking operations+- **Runner.run_sync()**: Synchronous execution for simple blocking calls+- **Runner.run_streamed()**: Streaming execution for real-time responses+- **Performance Comparison**: When to use each method++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ from agents import Runner+ from agent import root_agent++ # Test sync execution+ result = root_agent.sync_execution_example()+ print(result)+ ```++## π‘ Key Concepts++- **Sync Execution**: Blocks until completion, simple to use+- **Async Execution**: Non-blocking, enables concurrency+- **Streaming Execution**: Real-time response processing+- **Use Case Selection**: Choose based on application needs++## π Next Steps++- [Conversation Management](../4_2_conversation_management/README.md) - Threading and sessions+- [Run Configuration](../4_3_run_configuration/README.md) - Advanced settingsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/__init__.pynew file mode 100644index 00000000..da822068--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/__init__.py@@ -0,0 +1 @@+# Execution Methods Packagediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/agent.pynew file mode 100644index 00000000..6de551ac--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/agent.py@@ -0,0 +1,43 @@+from agents import Agent, Runner+import asyncio++# Create a simple agent for demonstrating execution methods+root_agent = Agent(+ name="Execution Demo Agent",+ instructions="""+ You are a helpful assistant demonstrating different execution patterns.++ Provide clear, informative responses that help users understand:+ - Synchronous execution (blocking)+ - Asynchronous execution (non-blocking)+ - Streaming execution (real-time)++ Keep responses appropriate for the execution method being demonstrated.+ """+)++# Example 1: Synchronous execution+def sync_execution_example():+ """Demonstrates Runner.run_sync() - blocking execution"""+ result = Runner.run_sync(root_agent, "Explain synchronous execution in simple terms")+ return result.final_output++# Example 2: Asynchronous execution+async def async_execution_example():+ """Demonstrates Runner.run() - non-blocking execution"""+ result = await Runner.run(root_agent, "Explain asynchronous execution benefits")+ return result.final_output++# Example 3: Streaming execution+async def streaming_execution_example():+ """Demonstrates Runner.run_streamed() - real-time streaming"""+ full_response = ""++ async for event in Runner.run_streamed(root_agent, "Write a detailed explanation of streaming execution"):+ # Handle streaming events as they arrive+ if hasattr(event, 'content') and event.content:+ full_response += event.content+ print(event.content, end='', flush=True) # Print in real-time++ print() # New line after streaming+ return full_responsediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_1_execution_methods/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/README.mdnew file mode 100644index 00000000..3b671421--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/README.md@@ -0,0 +1,44 @@+# Conversation Management++Demonstrates manual conversation threading with `to_input_list()` and automatic management with Sessions.++## π― What This Demonstrates++- **Manual Threading**: Using `result.to_input_list()` for conversation history+- **Automatic Sessions**: Using `SQLiteSession` for memory management+- **Conversation Context**: Maintaining state across multiple turns+- **Thread Management**: Different approaches to conversation flow++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import manual_conversation_example, session_conversation_example++ # Test manual conversation management+ asyncio.run(manual_conversation_example())+ ```++## π‘ Key Concepts++- **to_input_list()**: Manual conversation history management+- **SQLiteSession**: Automatic conversation persistence+- **Context Preservation**: Maintaining conversation state+- **Session Storage**: In-memory vs persistent storage++## π Next Steps++- [Execution Methods](../4_1_execution_methods/README.md) - Basic execution patterns+- [Streaming Events](../4_4_streaming_events/README.md) - Real-time processingdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/__init__.pynew file mode 100644index 00000000..97458d63--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/__init__.py@@ -0,0 +1 @@+# Conversation Management Packagediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/agent.pynew file mode 100644index 00000000..684216a7--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/agent.py@@ -0,0 +1,39 @@+from agents import Agent, Runner, SQLiteSession++# Create an agent for demonstrating conversation management+root_agent = Agent(+ name="Conversation Agent",+ instructions="You are a helpful assistant that remembers conversation context. Reply concisely but reference previous context when relevant."+)++# Example 1: Manual conversation management+async def manual_conversation_example():+ """Demonstrates manual conversation management using result.to_input_list()"""++ # First turn+ result = await Runner.run(root_agent, "My name is Alice and I live in San Francisco.")+ print(f"Turn 1: {result.final_output}")++ # Second turn - manually pass conversation history+ new_input = result.to_input_list() + [{"role": "user", "content": "What city do I live in?"}]+ result = await Runner.run(root_agent, new_input)+ print(f"Turn 2: {result.final_output}")++ return result++# Example 2: Automatic conversation management with Sessions+async def session_conversation_example():+ """Demonstrates automatic conversation management using SQLiteSession"""++ # Create session instance+ session = SQLiteSession("conversation_123")++ # First turn+ result = await Runner.run(root_agent, "I'm a software developer working on AI projects.", session=session)+ print(f"Session Turn 1: {result.final_output}")++ # Second turn - session automatically remembers context+ result = await Runner.run(root_agent, "What kind of work do I do?", session=session)+ print(f"Session Turn 2: {result.final_output}")++ return resultdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_2_conversation_management/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_3_run_configuration/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_3_run_configuration/__init__.pynew file mode 100644index 00000000..41b50427--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_3_run_configuration/__init__.py@@ -0,0 +1 @@+# Run Configuration Packagediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_3_run_configuration/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_3_run_configuration/agent.pynew file mode 100644index 00000000..98335a8a--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_3_run_configuration/agent.py@@ -0,0 +1,53 @@+from agents import Agent, Runner, RunConfig++# Create an agent for demonstrating run configuration+root_agent = Agent(+ name="Configuration Demo Agent",+ instructions="You are a helpful assistant that demonstrates run configuration options."+)++# Example 1: Basic run configuration with model settings+async def model_config_example():+ """Demonstrates run configuration with model overrides and settings"""++ run_config = RunConfig(+ model="gpt-4o", # Override agent's default model+ model_settings={+ "temperature": 0.1, # Low temperature for consistent responses+ "top_p": 0.9+ },+ max_turns=5, # Limit conversation turns+ workflow_name="demo_workflow", # For tracing+ trace_metadata={"experiment": "config_demo"}+ )++ result = await Runner.run(+ root_agent,+ "Explain the weather in exactly 3 sentences.",+ run_config=run_config+ )++ return result.final_output++# Example 2: Run configuration with tracing settings+async def tracing_config_example():+ """Demonstrates run configuration with tracing options"""++ run_config = RunConfig(+ tracing_disabled=False, # Enable tracing+ trace_include_sensitive_data=False, # Exclude sensitive data+ workflow_name="production_workflow",+ group_id="user_session_456", # Link multiple runs+ trace_metadata={+ "user_id": "user_123",+ "feature": "chat_assistance"+ }+ )++ result = await Runner.run(+ root_agent,+ "What are the benefits of structured logging?",+ run_config=run_config+ )++ return result.final_outputdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_4_streaming_events/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_4_streaming_events/__init__.pynew file mode 100644index 00000000..51938115--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_4_streaming_events/__init__.py@@ -0,0 +1 @@+# Streaming Events module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_4_streaming_events/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_4_streaming_events/agent.pynew file mode 100644index 00000000..d5f65a3a--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/4_4_streaming_events/agent.py@@ -0,0 +1,200 @@+from agents import Agent, Runner+import asyncio+import time++# Create agents for demonstrating streaming events+root_agent = Agent(+ name="Streaming Demo Agent",+ instructions="""+ You are a helpful assistant that demonstrates streaming capabilities.++ When asked to write long content, be comprehensive and detailed.+ When asked technical questions, provide thorough explanations.+ """+)++# Example 1: Basic streaming with event processing+async def basic_streaming_example():+ """Demonstrates basic streaming event handling"""++ print("=== Basic Streaming Events ===")+ print("Requesting a detailed explanation...")++ full_response = ""+ start_time = time.time()++ # Use run_streamed to get real-time events+ async for event in Runner.run_streamed(+ root_agent,+ "Write a comprehensive explanation of how machine learning works, including examples."+ ):+ # Process different types of streaming events+ if hasattr(event, 'content') and event.content:+ # This is a text content event+ full_response += event.content+ print(event.content, end='', flush=True)++ if hasattr(event, 'type'):+ # Handle different event types+ if event.type == "response_start":+ print(f"\n[EVENT] Response started")+ elif event.type == "response_complete":+ print(f"\n[EVENT] Response completed")++ elapsed_time = time.time() - start_time+ print(f"\n\nStreaming completed in {elapsed_time:.2f} seconds")+ print(f"Total response length: {len(full_response)} characters")++ return full_response++# Example 2: Advanced streaming with RunResultStreaming+async def advanced_streaming_example():+ """Shows how to work with RunResultStreaming object"""++ print("\n=== Advanced Streaming with RunResultStreaming ===")+ print("Generating a long story with progress tracking...")++ # Track streaming progress+ events_count = 0+ chunks_received = []++ # Get the streaming result generator+ streaming_result = Runner.run_streamed(+ root_agent,+ "Write a creative short story about a robot who discovers emotions. Make it at least 500 words."+ )++ print("Processing streaming events:")++ async for event in streaming_result:+ events_count += 1++ # Collect content chunks+ if hasattr(event, 'content') and event.content:+ chunks_received.append(event.content)+ # Show progress every 10 chunks+ if len(chunks_received) % 10 == 0:+ print(f"\n[PROGRESS] Received {len(chunks_received)} chunks...")+ print(event.content, end='', flush=True)++ # Handle specific event types+ if hasattr(event, 'type'):+ if event.type == "tool_call_start":+ print(f"\n[EVENT] Tool call started")+ elif event.type == "tool_call_complete":+ print(f"\n[EVENT] Tool call completed")++ print(f"\n\nStreaming summary:")+ print(f"- Total events processed: {events_count}")+ print(f"- Content chunks received: {len(chunks_received)}")+ print(f"- Final story length: {sum(len(chunk) for chunk in chunks_received)} characters")++ # Access the final result+ final_result = "".join(chunks_received)+ return final_result++# Example 3: Streaming with custom processing+async def custom_streaming_processing():+ """Demonstrates custom streaming event processing"""++ print("\n=== Custom Streaming Processing ===")+ print("Analyzing streaming patterns...")++ # Custom streaming analytics+ analytics = {+ "words_per_second": [],+ "chunk_sizes": [],+ "response_time": None,+ "total_words": 0+ }++ start_time = time.time()+ last_update = start_time+ current_content = ""++ async for event in Runner.run_streamed(+ root_agent,+ "Explain the benefits and challenges of renewable energy in detail."+ ):+ current_time = time.time()++ if hasattr(event, 'content') and event.content:+ # Track chunk size+ chunk_size = len(event.content)+ analytics["chunk_sizes"].append(chunk_size)++ # Update content+ current_content += event.content++ # Calculate words per second every few chunks+ if len(analytics["chunk_sizes"]) % 5 == 0:+ time_diff = current_time - last_update+ if time_diff > 0:+ words_in_chunk = len(event.content.split())+ wps = words_in_chunk / time_diff+ analytics["words_per_second"].append(wps)+ last_update = current_time++ print(event.content, end='', flush=True)++ # Final analytics+ analytics["response_time"] = time.time() - start_time+ analytics["total_words"] = len(current_content.split())++ print(f"\n\nStreaming Analytics:")+ print(f"- Total response time: {analytics['response_time']:.2f} seconds")+ print(f"- Total words: {analytics['total_words']}")+ print(f"- Average chunk size: {sum(analytics['chunk_sizes'])/len(analytics['chunk_sizes']):.1f} chars")++ if analytics["words_per_second"]:+ avg_wps = sum(analytics["words_per_second"]) / len(analytics["words_per_second"])+ print(f"- Average words per second: {avg_wps:.1f}")++ return analytics++# Example 4: Streaming with error handling+async def streaming_with_error_handling():+ """Shows proper error handling for streaming operations"""++ print("\n=== Streaming with Error Handling ===")++ try:+ response_parts = []++ async for event in Runner.run_streamed(+ root_agent,+ "What are the top 3 programming languages and why?"+ ):+ try:+ if hasattr(event, 'content') and event.content:+ response_parts.append(event.content)+ print(event.content, end='', flush=True)++ except Exception as chunk_error:+ print(f"\n[ERROR] Error processing chunk: {chunk_error}")+ continue # Continue with next chunk++ print(f"\n\nStreaming completed successfully!")+ print(f"Collected {len(response_parts)} response parts")++ return "".join(response_parts)++ except Exception as streaming_error:+ print(f"\n[ERROR] Streaming failed: {streaming_error}")+ return None++# Main execution+async def main():+ print("π OpenAI Agents SDK - Streaming Events")+ print("=" * 60)++ await basic_streaming_example()+ await advanced_streaming_example()+ await custom_streaming_processing()+ await streaming_with_error_handling()++ print("\nβ Streaming events tutorial complete!")+ print("Streaming enables real-time response processing for better user experience")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/README.mdnew file mode 100644index 00000000..0435fa4d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/README.md@@ -0,0 +1,228 @@+# π Tutorial 4: Running Agents++Master the complete OpenAI Agents SDK execution system! This tutorial covers all aspects of running agents including execution methods, streaming, the agent loop, exception handling, and advanced configuration based on the [official running agents documentation](https://openai.github.io/openai-agents-python/running_agents/).++## π― What You'll Learn++- **Three Execution Methods**: `Runner.run()`, `Runner.run_sync()`, `Runner.run_streamed()`+- **The Agent Loop**: Understanding LLM calls, tool execution, and handoffs+- **Streaming Events**: Real-time response handling with detailed event processing+- **Exception Handling**: Managing all SDK exceptions properly+- **Advanced Run Configuration**: Guardrails, tracing, and workflow control++## π§ Core Concept: The Agent Loop++When you call any Runner method, the SDK executes a sophisticated loop that handles the complete agent workflow:++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β THE AGENT LOOP β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β START: Runner.run(agent, input) β+β β β+β βΌ β+β βββββββββββββββ 1. CALL LLM β+β β LLM β β¦ Current agent + input β+β β CALL β β¦ Generate response β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 2. PROCESS OUTPUT β+β β OUTPUT β β¦ Final output? β END β+β β ANALYSIS β β¦ Tool calls? β Execute tools β+β βββββββββββββββ β¦ Handoff? β Switch agent β+β β β+β βΌ β+β βββββββββββββββ 3. CONTINUE LOOP β+β β REPEAT β β¦ Append results to input β+β β LOOP β β¦ Check max_turns limit β+β βββββββββββββββ β¦ Loop until final output β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Tutorial Overview++This tutorial demonstrates **five key running patterns**:++### **1. Execution Methods** (`4_1_execution_methods/`)+- Sync, async, and streaming execution comparison+- Performance and use case analysis+- Basic agent loop understanding++### **2. Conversation Management** (`4_2_conversation_management/`)+- Manual conversation threading with `to_input_list()`+- Automatic conversation management with Sessions+- Thread ID and group management++### **3. Run Configuration** (`4_3_run_configuration/`)+- Model overrides and settings+- Tracing configuration and metadata+- Workflow naming and organization++### **4. Streaming Events** (`4_4_streaming_events/`)+- Detailed streaming event handling+- `RunResultStreaming` object usage+- Real-time response processing patterns++### **5. Exception Handling** (`4_5_exception_handling/`)+- All SDK exceptions: `MaxTurnsExceeded`, `ModelBehaviorError`, etc.+- Proper error handling patterns+- Recovery and retry strategies++## π Project Structure++```+4_running_agents/+βββ README.md # This file - comprehensive guide+βββ requirements.txt # Dependencies+βββ 4_1_execution_methods/+β βββ __init__.py+β βββ agent.py # Three execution methods (45 lines)+βββ 4_2_conversation_management/+β βββ __init__.py+β βββ agent.py # Manual vs automatic threading (40 lines)+βββ 4_3_run_configuration/+β βββ __init__.py+β βββ agent.py # RunConfig examples (55 lines)+βββ 4_4_streaming_events/+β βββ __init__.py+β βββ agent.py # Detailed streaming handling (50 lines)+βββ 4_5_exception_handling/+β βββ __init__.py+β βββ agent.py # All exception types (60 lines)+βββ agent_runner.py # Streamlit demo interface (recommended)+βββ env.example # Environment variables+```++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β The complete agent execution loop and when each step occurs+- β How to choose between sync, async, and streaming execution+- β Detailed streaming event processing for real-time applications+- β Proper exception handling for production-ready applications+- β Advanced run configuration for complex workflows++## π Getting Started++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Install dependencies**:+ ```bash+ pip install -r requirements.txt+ ```++2. **Set up environment variables**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Test execution methods**:+ ```bash+ python -m 4_1_execution_methods.agent+ ```++4. **Try conversation management**:+ ```bash+ python -m 4_2_conversation_management.agent+ ```++5. **Explore run configuration**:+ ```bash+ python -m 4_3_run_configuration.agent+ ```++6. **Test streaming events**:+ ```bash+ python -m 4_4_streaming_events.agent+ ```++7. **Practice exception handling**:+ ```bash+ python -m 4_5_exception_handling.agent+ ```++## π§ Key Running Concepts++### 1. **The Agent Loop Process**+- **LLM Call**: Agent processes input and generates response+- **Output Analysis**: Check for final output, tool calls, or handoffs+- **Tool Execution**: Run any tool calls and append results+- **Handoff Processing**: Switch to new agent if handoff occurs+- **Loop Continuation**: Repeat until final output or max_turns reached++### 2. **Three Execution Methods**+```python+# 1. Async (non-blocking, returns RunResult)+result = await Runner.run(agent, "message")++# 2. Sync (blocking, wraps async under hood)+result = Runner.run_sync(agent, "message")++# 3. Streaming (async, returns RunResultStreaming)+async for event in Runner.run_streamed(agent, "message"):+ # Process events in real-time+ pass+```++### 3. **Streaming Event Types**+Based on the documentation, streaming provides real-time events as the LLM generates responses, including partial text, tool calls, and completion events.++### 4. **Exception Hierarchy**+- **AgentsException**: Base exception class+- **MaxTurnsExceeded**: Too many loop iterations+- **ModelBehaviorError**: LLM output issues (malformed JSON, etc.)+- **UserError**: SDK usage errors+- **InputGuardrailTripwireTriggered**: Input validation failures+- **OutputGuardrailTripwireTriggered**: Output validation failures++## π§ͺ Sample Use Cases++### Execution Methods+- **Sync**: Simple scripts, batch processing, quick responses+- **Async**: Web applications, concurrent users, non-blocking operations+- **Streaming**: Long content generation, real-time chat, progress updates++### Conversation Management+- **Manual**: Custom conversation logic, special threading requirements+- **Sessions**: Standard chat applications, automatic history management++### Exception Handling+- **Production Apps**: Graceful error recovery, user-friendly messages+- **Development**: Debugging agent behavior, understanding failures++## π‘ Running Agents Best Practices++1. **Choose Right Method**: Sync for scripts, async for apps, streaming for long responses+2. **Handle Exceptions**: Always wrap Runner calls in proper exception handling+3. **Configure Appropriately**: Use RunConfig for production settings+4. **Monitor Performance**: Track execution time and resource usage+5. **Manage Conversations**: Choose manual vs Sessions based on requirements++## π Next Steps++After completing this tutorial, you'll be ready for:+- **[Tutorial 5: Context Management](../5_context_management/README.md)** - Advanced state management+- **[Tutorial 6: Guardrails & Validation](../6_guardrails_validation/README.md)** - Input/output safety+- **[Tutorial 7: Sessions](../7_sessions/README.md)** - Memory and conversation management++## π¨ Troubleshooting++- **Async Issues**: Always use `await` with `Runner.run()` and `Runner.run_streamed()`+- **Streaming Problems**: Handle partial events and connection interruptions+- **Exception Handling**: Catch specific exception types for better error recovery+- **Performance**: Monitor max_turns settings to prevent infinite loops+- **Configuration**: Verify RunConfig settings match your use case requirements++## π‘ Pro Tips++- **Start Simple**: Begin with `run_sync`, move to `run` when you need concurrency+- **Use Streaming Wisely**: Reserve for responses longer than 30 seconds+- **Exception Strategy**: Plan for each exception type in production code+- **Configuration Consistency**: Use RunConfig for repeatable execution patterns+- **Monitor the Loop**: Use tracing to understand complex agent interactions\ No newline at end of filediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/agent_runner.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/agent_runner.pynew file mode 100644index 00000000..24761fab--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/agent_runner.py@@ -0,0 +1,687 @@+import streamlit as st+import asyncio+import time+import json+from datetime import datetime+from agents import Agent, Runner, RunConfig, SQLiteSession+from agents.exceptions import (+ AgentsException,+ MaxTurnsExceeded,+ ModelBehaviorError,+ UserError+)+from dotenv import load_dotenv++# Load environment variables+load_dotenv()++# Page configuration+st.set_page_config(+ page_title="Agent Runner Demo",+ page_icon="π",+ layout="wide",+ initial_sidebar_state="expanded"+)++# Initialize agents[email protected]_resource+def initialize_agents():+ """Initialize agents for different demonstrations"""++ execution_agent = Agent(+ name="Execution Demo Agent",+ instructions="""+ You are a helpful assistant demonstrating different execution patterns.++ Provide clear, informative responses that help users understand:+ - Synchronous execution (blocking)+ - Asynchronous execution (non-blocking)+ - Streaming execution (real-time)++ Keep responses appropriate for the execution method being demonstrated.+ """+ )++ conversation_agent = Agent(+ name="Conversation Agent",+ instructions="You are a helpful assistant that remembers conversation context. Reply concisely but reference previous context when relevant."+ )++ config_agent = Agent(+ name="Configuration Demo Agent",+ instructions="You are a helpful assistant that demonstrates run configuration options. Be precise and informative."+ )++ streaming_agent = Agent(+ name="Streaming Demo Agent",+ instructions="""+ You are a helpful assistant that demonstrates streaming capabilities.++ When asked to write long content, be comprehensive and detailed.+ When asked technical questions, provide thorough explanations.+ """+ )++ return execution_agent, conversation_agent, config_agent, streaming_agent++# Session management+class StreamingCapture:+ def __init__(self):+ self.events = []+ self.content = ""+ self.start_time = None+ self.end_time = None++ def reset(self):+ self.events = []+ self.content = ""+ self.start_time = None+ self.end_time = None++# Initialize session state+if 'session_manager' not in st.session_state:+ st.session_state.session_manager = {}+if 'streaming_capture' not in st.session_state:+ st.session_state.streaming_capture = StreamingCapture()++# Main UI+def main():+ st.title("π Agent Runner Demo")+ st.markdown("**Demonstrates OpenAI Agents SDK execution capabilities**")++ # Initialize agents+ execution_agent, conversation_agent, config_agent, streaming_agent = initialize_agents()++ # Sidebar for configuration+ with st.sidebar:+ st.header("βοΈ Execution Configuration")++ demo_type = st.selectbox(+ "Select Demo Type",+ ["Execution Methods", "Conversation Management", "Run Configuration", "Streaming Events", "Exception Handling"]+ )++ st.divider()++ # Global settings+ st.subheader("Global Settings")++ # Model configuration+ model_choice = st.selectbox(+ "Model",+ ["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo"],+ index=0+ )++ temperature = st.slider(+ "Temperature",+ min_value=0.0,+ max_value=2.0,+ value=0.7,+ step=0.1+ )++ max_turns = st.number_input(+ "Max Turns",+ min_value=1,+ max_value=20,+ value=10+ )++ # Main content area+ if demo_type == "Execution Methods":+ render_execution_methods(execution_agent, model_choice, temperature, max_turns)+ elif demo_type == "Conversation Management":+ render_conversation_management(conversation_agent, model_choice, temperature, max_turns)+ elif demo_type == "Run Configuration":+ render_run_configuration(config_agent, model_choice, temperature, max_turns)+ elif demo_type == "Streaming Events":+ render_streaming_events(streaming_agent, model_choice, temperature, max_turns)+ elif demo_type == "Exception Handling":+ render_exception_handling(execution_agent, model_choice, temperature, max_turns)++def render_execution_methods(agent, model_choice, temperature, max_turns):+ """Render the execution methods demo"""+ st.header("β‘ Execution Methods Demo")+ st.markdown("Compare synchronous, asynchronous, and streaming execution patterns.")++ col1, col2, col3 = st.columns(3)++ with col1:+ st.subheader("π Synchronous (Blocking)")+ st.caption("Runner.run_sync() - Blocks until complete")++ with st.form("sync_form"):+ sync_input = st.text_area("Your message:", key="sync_input", value="Explain synchronous execution in simple terms")+ sync_submitted = st.form_submit_button("Run Sync")++ if sync_submitted and sync_input:+ with st.spinner("Processing synchronously..."):+ start_time = time.time()++ try:+ result = Runner.run_sync(agent, sync_input)+ execution_time = time.time() - start_time++ st.success(f"β Completed in {execution_time:.2f}s")+ st.write("**Response:**")+ st.write(result.final_output)++ except Exception as e:+ st.error(f"β Error: {e}")++ with col2:+ st.subheader("β‘ Asynchronous (Non-blocking)")+ st.caption("Runner.run() - Returns awaitable")++ with st.form("async_form"):+ async_input = st.text_area("Your message:", key="async_input", value="Explain asynchronous execution benefits")+ async_submitted = st.form_submit_button("Run Async")++ if async_submitted and async_input:+ with st.spinner("Processing asynchronously..."):+ start_time = time.time()++ try:+ result = asyncio.run(Runner.run(agent, async_input))+ execution_time = time.time() - start_time++ st.success(f"β Completed in {execution_time:.2f}s")+ st.write("**Response:**")+ st.write(result.final_output)++ except Exception as e:+ st.error(f"β Error: {e}")++ with col3:+ st.subheader("π Streaming (Real-time)")+ st.caption("Runner.run_streamed() - Live updates")++ with st.form("streaming_form"):+ streaming_input = st.text_area("Your message:", key="streaming_input", value="Write a detailed explanation of streaming execution")+ streaming_submitted = st.form_submit_button("Run Streaming")++ if streaming_submitted and streaming_input:+ st.info("π Streaming response...")++ # Create containers for streaming output+ response_container = st.empty()+ progress_container = st.empty()++ try:+ full_response = ""+ start_time = time.time()++ async def stream_response():+ nonlocal full_response+ async for event in Runner.run_streamed(agent, streaming_input):+ if hasattr(event, 'content') and event.content:+ full_response += event.content+ response_container.write(f"**Response:**\n{full_response}")++ execution_time = time.time() - start_time+ progress_container.success(f"β Streaming completed in {execution_time:.2f}s")++ asyncio.run(stream_response())++ except Exception as e:+ st.error(f"β Streaming error: {e}")++def render_conversation_management(agent, model_choice, temperature, max_turns):+ """Render the conversation management demo"""+ st.header("π¬ Conversation Management Demo")+ st.markdown("Compare manual conversation threading vs automatic session management.")++ tab1, tab2 = st.tabs(["Manual Threading", "Session Management"])++ with tab1:+ st.subheader("π§ Manual Conversation Threading")+ st.caption("Using result.to_input_list() for conversation history")++ # Initialize conversation history in session state+ if 'manual_conversation' not in st.session_state:+ st.session_state.manual_conversation = []++ with st.form("manual_form"):+ manual_input = st.text_input("Your message:")+ manual_submitted = st.form_submit_button("Send Message")++ if manual_submitted and manual_input:+ with st.spinner("Processing..."):+ try:+ # Build input list manually+ input_list = st.session_state.manual_conversation.copy()+ input_list.append({"role": "user", "content": manual_input})++ result = asyncio.run(Runner.run(agent, input_list))++ # Update conversation history+ st.session_state.manual_conversation = result.to_input_list()++ st.success("Message sent!")+ st.write(f"**Assistant:** {result.final_output}")++ except Exception as e:+ st.error(f"β Error: {e}")++ # Show conversation history+ if st.button("π Show Manual History"):+ if st.session_state.manual_conversation:+ st.write("**Conversation History:**")+ for i, item in enumerate(st.session_state.manual_conversation, 1):+ role_emoji = "π€" if item['role'] == 'user' else "π€"+ st.write(f"{i}. {role_emoji} **{item['role'].title()}:** {item['content']}")+ else:+ st.info("No conversation history yet.")++ if st.button("ποΈ Clear Manual History"):+ st.session_state.manual_conversation = []+ st.success("Manual conversation history cleared!")++ with tab2:+ st.subheader("π Automatic Session Management")+ st.caption("Using SQLiteSession for automatic conversation memory")++ session_id = "demo_conversation"++ with st.form("session_form"):+ session_input = st.text_input("Your message:")+ session_submitted = st.form_submit_button("Send Message")++ if session_submitted and session_input:+ with st.spinner("Processing..."):+ try:+ # Get or create session+ if session_id not in st.session_state.session_manager:+ st.session_state.session_manager[session_id] = SQLiteSession(session_id)++ session = st.session_state.session_manager[session_id]+ result = asyncio.run(Runner.run(agent, session_input, session=session))++ st.success("Message sent!")+ st.write(f"**Assistant:** {result.final_output}")++ except Exception as e:+ st.error(f"β Error: {e}")++ # Show session history+ if st.button("π Show Session History"):+ if session_id in st.session_state.session_manager:+ session = st.session_state.session_manager[session_id]+ try:+ items = asyncio.run(session.get_items())+ if items:+ st.write("**Session History:**")+ for i, item in enumerate(items, 1):+ role_emoji = "π€" if item['role'] == 'user' else "π€"+ st.write(f"{i}. {role_emoji} **{item['role'].title()}:** {item['content']}")+ else:+ st.info("No session history yet.")+ except Exception as e:+ st.error(f"β Error retrieving history: {e}")+ else:+ st.info("No session created yet.")++ if st.button("ποΈ Clear Session History"):+ if session_id in st.session_state.session_manager:+ try:+ session = st.session_state.session_manager[session_id]+ asyncio.run(session.clear_session())+ del st.session_state.session_manager[session_id]+ st.success("Session history cleared!")+ except Exception as e:+ st.error(f"β Error clearing session: {e}")++def render_run_configuration(agent, model_choice, temperature, max_turns):+ """Render the run configuration demo"""+ st.header("βοΈ Run Configuration Demo")+ st.markdown("Demonstrates advanced run configuration options with RunConfig.")++ col1, col2 = st.columns(2)++ with col1:+ st.subheader("ποΈ Basic Configuration")++ with st.form("basic_config_form"):+ st.write("**Model Settings:**")+ config_temperature = st.slider("Temperature", 0.0, 2.0, 0.1, 0.1, key="config_temp")+ config_top_p = st.slider("Top P", 0.0, 1.0, 0.9, 0.1, key="config_top_p")+ config_max_turns = st.number_input("Max Turns", 1, 20, 5, key="config_turns")++ config_input = st.text_area("Your message:", value="Explain the weather in exactly 3 sentences.")+ config_submitted = st.form_submit_button("Run with Config")++ if config_submitted and config_input:+ with st.spinner("Processing with configuration..."):+ try:+ run_config = RunConfig(+ model=model_choice,+ model_settings={+ "temperature": config_temperature,+ "top_p": config_top_p+ },+ max_turns=config_max_turns,+ workflow_name="basic_config_demo"+ )++ start_time = time.time()+ result = asyncio.run(Runner.run(agent, config_input, run_config=run_config))+ execution_time = time.time() - start_time++ st.success(f"β Completed in {execution_time:.2f}s")+ st.write("**Response:**")+ st.write(result.final_output)++ # Show configuration used+ st.write("**Configuration Used:**")+ st.json({+ "model": model_choice,+ "temperature": config_temperature,+ "top_p": config_top_p,+ "max_turns": config_max_turns+ })++ except Exception as e:+ st.error(f"β Error: {e}")++ with col2:+ st.subheader("π Tracing Configuration")++ with st.form("tracing_config_form"):+ st.write("**Tracing Settings:**")+ workflow_name = st.text_input("Workflow Name", value="production_workflow")+ group_id = st.text_input("Group ID", value="user_session_456")+ user_id = st.text_input("User ID", value="user_123")+ feature_name = st.text_input("Feature", value="chat_assistance")++ tracing_input = st.text_area("Your message:", value="What are the benefits of structured logging?")+ tracing_submitted = st.form_submit_button("Run with Tracing")++ if tracing_submitted and tracing_input:+ with st.spinner("Processing with tracing..."):+ try:+ run_config = RunConfig(+ model=model_choice,+ tracing_disabled=False,+ trace_include_sensitive_data=False,+ workflow_name=workflow_name,+ group_id=group_id,+ trace_metadata={+ "user_id": user_id,+ "feature": feature_name,+ "timestamp": datetime.now().isoformat()+ }+ )++ start_time = time.time()+ result = asyncio.run(Runner.run(agent, tracing_input, run_config=run_config))+ execution_time = time.time() - start_time++ st.success(f"β Completed with tracing in {execution_time:.2f}s")+ st.write("**Response:**")+ st.write(result.final_output)++ # Show tracing configuration+ st.write("**Tracing Configuration:**")+ st.json({+ "workflow_name": workflow_name,+ "group_id": group_id,+ "metadata": {+ "user_id": user_id,+ "feature": feature_name+ }+ })++ except Exception as e:+ st.error(f"β Error: {e}")++def render_streaming_events(agent, model_choice, temperature, max_turns):+ """Render the streaming events demo"""+ st.header("π Streaming Events Demo")+ st.markdown("Demonstrates advanced streaming event processing and real-time analytics.")++ tab1, tab2 = st.tabs(["Basic Streaming", "Advanced Analytics"])++ with tab1:+ st.subheader("π― Basic Streaming with Event Processing")++ with st.form("streaming_basic_form"):+ streaming_input = st.text_area(+ "Your message:",+ value="Write a comprehensive explanation of how machine learning works, including examples."+ )+ streaming_submitted = st.form_submit_button("Start Streaming")++ if streaming_submitted and streaming_input:+ st.info("π Streaming in progress...")++ # Create containers+ response_container = st.empty()+ stats_container = st.empty()++ try:+ full_response = ""+ events_count = 0+ start_time = time.time()++ async def process_streaming():+ nonlocal full_response, events_count++ async for event in Runner.run_streamed(agent, streaming_input):+ events_count += 1++ if hasattr(event, 'content') and event.content:+ full_response += event.content++ # Update display+ response_container.write(f"**Response:**\n{full_response}")++ # Update stats+ elapsed = time.time() - start_time+ char_count = len(full_response)+ word_count = len(full_response.split())++ stats_container.metric(+ label="Streaming Progress",+ value=f"{char_count} chars, {word_count} words",+ delta=f"{elapsed:.1f}s elapsed"+ )++ asyncio.run(process_streaming())++ final_time = time.time() - start_time+ st.success(f"β Streaming completed! {events_count} events in {final_time:.2f}s")++ except Exception as e:+ st.error(f"β Streaming error: {e}")++ with tab2:+ st.subheader("π Advanced Streaming Analytics")++ with st.form("streaming_analytics_form"):+ analytics_input = st.text_area(+ "Your message:",+ value="Explain the benefits and challenges of renewable energy in detail."+ )+ analytics_submitted = st.form_submit_button("Stream with Analytics")++ if analytics_submitted and analytics_input:+ st.info("π Streaming with analytics...")++ # Create analytics containers+ response_container = st.empty()+ metrics_col1, metrics_col2, metrics_col3 = st.columns(3)++ try:+ analytics = {+ "chunks": [],+ "chunk_sizes": [],+ "timestamps": [],+ "content": ""+ }++ start_time = time.time()++ async def process_analytics_streaming():+ async for event in Runner.run_streamed(agent, analytics_input):+ current_time = time.time()++ if hasattr(event, 'content') and event.content:+ # Collect analytics+ analytics["chunks"].append(event.content)+ analytics["chunk_sizes"].append(len(event.content))+ analytics["timestamps"].append(current_time - start_time)+ analytics["content"] += event.content++ # Update display+ response_container.write(f"**Response:**\n{analytics['content']}")++ # Update metrics+ with metrics_col1:+ st.metric("Chunks", len(analytics["chunks"]))++ with metrics_col2:+ avg_chunk_size = sum(analytics["chunk_sizes"]) / len(analytics["chunk_sizes"])+ st.metric("Avg Chunk Size", f"{avg_chunk_size:.1f} chars")++ with metrics_col3:+ elapsed = current_time - start_time+ if elapsed > 0:+ chars_per_sec = len(analytics["content"]) / elapsed+ st.metric("Speed", f"{chars_per_sec:.1f} chars/s")++ asyncio.run(process_analytics_streaming())++ # Final analytics+ total_time = time.time() - start_time+ total_words = len(analytics["content"].split())++ st.success(f"β Analytics complete!")++ # Display final analytics+ st.write("**Final Analytics:**")+ col1, col2, col3, col4 = st.columns(4)++ with col1:+ st.metric("Total Time", f"{total_time:.2f}s")++ with col2:+ st.metric("Total Words", total_words)++ with col3:+ st.metric("Total Chunks", len(analytics["chunks"]))++ with col4:+ if total_time > 0:+ st.metric("Words/Second", f"{total_words/total_time:.1f}")++ except Exception as e:+ st.error(f"β Analytics streaming error: {e}")++def render_exception_handling(agent, model_choice, temperature, max_turns):+ """Render the exception handling demo"""+ st.header("β οΈ Exception Handling Demo")+ st.markdown("Demonstrates proper exception handling for different SDK error scenarios.")++ col1, col2 = st.columns(2)++ with col1:+ st.subheader("π« MaxTurns Exception")+ st.caption("Trigger MaxTurnsExceeded exception")++ with st.form("maxturns_form"):+ max_turns_test = st.number_input("Max Turns (set low to trigger)", 1, 5, 2)+ maxturns_input = st.text_area(+ "Your message:",+ value="Keep asking me questions and I'll keep responding. Let's have a long conversation."+ )+ maxturns_submitted = st.form_submit_button("Test MaxTurns")++ if maxturns_submitted and maxturns_input:+ try:+ run_config = RunConfig(max_turns=max_turns_test)+ result = asyncio.run(Runner.run(agent, maxturns_input, run_config=run_config))+ st.success("β Completed without hitting max turns")+ st.write(f"**Response:** {result.final_output}")++ except MaxTurnsExceeded as e:+ st.warning(f"β οΈ MaxTurnsExceeded: {e}")+ st.info("This is expected when max_turns is set too low for complex conversations.")++ except Exception as e:+ st.error(f"β Unexpected error: {e}")++ with col2:+ st.subheader("π§ General Exception Handling")+ st.caption("Comprehensive exception handling")++ with st.form("exception_form"):+ exception_input = st.text_area("Your message:", value="Tell me about artificial intelligence")+ exception_submitted = st.form_submit_button("Test Exception Handling")++ if exception_submitted and exception_input:+ try:+ with st.spinner("Processing with full exception handling..."):+ result = asyncio.run(Runner.run(agent, exception_input))+ st.success("β Successfully processed")+ st.write(f"**Response:** {result.final_output}")++ except MaxTurnsExceeded as e:+ st.warning(f"β οΈ Hit maximum turns limit: {e}")+ st.info("Consider increasing max_turns or simplifying the request.")++ except ModelBehaviorError as e:+ st.error(f"π€ Model behavior error: {e}")+ st.info("The model produced unexpected output. Try rephrasing your request.")++ except UserError as e:+ st.error(f"π€ User error: {e}")+ st.info("There's an issue with the request. Please check your input.")++ except AgentsException as e:+ st.error(f"π§ SDK error: {e}")+ st.info("An error occurred within the Agents SDK.")++ except Exception as e:+ st.error(f"β Unexpected error: {e}")+ st.info("An unexpected error occurred. Please try again.")++ # Exception handling reference+ st.divider()+ st.subheader("π Exception Handling Reference")++ exception_info = {+ "MaxTurnsExceeded": "Agent hit the maximum conversation turns limit",+ "ModelBehaviorError": "LLM produced malformed or unexpected output",+ "UserError": "Invalid SDK usage or request parameters",+ "AgentsException": "Base exception for all SDK-related errors",+ "InputGuardrailTripwireTriggered": "Input validation failed",+ "OutputGuardrailTripwireTriggered": "Output validation failed"+ }++ for exception, description in exception_info.items():+ st.write(f"**{exception}**: {description}")++# Footer+def render_footer():+ st.divider()+ st.markdown("""+ ### π― Agent Runner Capabilities Demonstrated++ 1. **Execution Methods**: Sync, async, and streaming execution patterns+ 2. **Conversation Management**: Manual threading vs automatic sessions+ 3. **Run Configuration**: Model settings, tracing, and workflow management+ 4. **Streaming Events**: Real-time processing and analytics+ 5. **Exception Handling**: Comprehensive error handling patterns++ **Key Benefits:**+ - Flexible execution patterns for different use cases+ - Automatic conversation memory with sessions+ - Advanced configuration for production deployments+ - Real-time streaming for better user experience+ - Robust error handling for production reliability+ """)++if __name__ == "__main__":+ main()+ render_footer()diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/requirements.txtnew file mode 100644index 00000000..a88bde1d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/requirements.txt@@ -0,0 +1,3 @@+openai-agents>=1.0.0+streamlit>=1.28.0+python-dotenv>=1.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/README.mdnew file mode 100644index 00000000..873e07c3--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/README.md@@ -0,0 +1,227 @@+# π§ Tutorial 5: Context Management++Master context-aware agent development with the OpenAI Agents SDK! This tutorial teaches you how to use `RunContextWrapper` to pass custom context objects that enable agents to access user data, session information, and state throughout their execution.++## π― What You'll Learn++- **RunContextWrapper**: Pass custom context objects to agents+- **Context-Aware Tools**: Build tools that access user state and preferences+- **Type-Safe Context**: Use generic types for compile-time safety+- **Context Manipulation**: Update and modify context during agent execution+- **Production Patterns**: Real-world context management strategies++## π§ Core Concept: What is Context Management?++Context management allows you to pass **custom data structures** to your agents that persist throughout the entire agent execution. Think of context as a **shared state container** that:++- Stores user information, preferences, and session data+- Provides access to external systems and databases+- Maintains state across multiple tool calls+- Enables personalized agent behavior+- Supports type-safe data access++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β CONTEXT WORKFLOW β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β USER CONTEXT β+β βββββββββββββββ β+β β UserInfo β 1. PASS TO RUNNER β+β β - name β βββββββββββββββββββββββββββββββββββββββββ β+β β - uid β β β+β β - prefs β βΌ β+β βββββββββββββββ β+β βββββββββββββββ β+β β AGENT β 2. CONTEXT AVAILABLE β+β β RUNNER β TO ALL TOOLS β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 3. TOOLS ACCESS β+β β TOOL CALLS β CONTEXT VIA β+β β WITH β RunContextWrapper β+β β CONTEXT β β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 4. CONTEXT CAN BE β+β β CONTEXT β MODIFIED AND β+β β UPDATED β PERSISTS β+β βββββββββββββββ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Key Context Management Concepts++### **Context Objects**+Custom data classes that hold state and user information:++```python+@dataclass+class UserInfo:+ name: str+ uid: int+ preferences: dict = None+```++### **RunContextWrapper**+Type-safe wrapper that provides access to context in tools:++```python+@function_tool+async def my_tool(wrapper: RunContextWrapper[UserInfo]) -> str:+ user = wrapper.context # Access the UserInfo object+ return f"Hello {user.name}"+```++### **Context-Aware Agents**+Agents that use generic typing for context safety:++```python+agent = Agent[UserInfo](+ name="Context Agent",+ tools=[context_aware_tool]+)+```++## π§ͺ What This Demonstrates++### **1. User Information Context**+- Storing user profile data (name, ID, preferences)+- Personalizing agent responses based on user context+- Updating user preferences during conversation++### **2. Context-Aware Tools**+- `fetch_user_profile()`: Retrieve user information from context+- `update_user_preference()`: Modify user settings in context+- `get_personalized_greeting()`: Generate custom greetings++### **3. Type Safety**+- Generic typing with `Agent[UserInfo]` for compile-time checks+- Typed context access with `RunContextWrapper[UserInfo]`+- IDE support and autocompletion for context objects++### **4. Context Persistence**+- Context modifications persist across tool calls+- State changes are maintained throughout agent execution+- Updated context is available to subsequent operations++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How to create custom context objects with dataclasses+- β Using RunContextWrapper for type-safe context access+- β Building context-aware tools that read and modify state+- β Implementing personalized agent behavior with context+- β Production patterns for context management at scale++## π Getting Started++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the context example**:+ ```python+ import asyncio+ from agent import context_example++ # Test context management+ asyncio.run(context_example())+ ```++## π§ͺ Sample Use Cases++### Basic Context Usage+- "Hello! I'd like to know about my profile and prefer casual greetings."+- "Update my greeting style to friendly"+- "What are my current preferences?"++### Personalization Examples+- Customized greetings based on user preferences+- Tailored responses using user profile information+- Dynamic behavior modification through context updates++### Production Applications+- User session management in web applications+- Customer support with account context+- E-commerce with shopping preferences and history++## π§ Key Context Patterns++### 1. **Basic Context Creation**+```python+from dataclasses import dataclass++@dataclass+class UserInfo:+ name: str+ uid: int+ preferences: dict = None+```++### 2. **Context-Aware Tool**+```python+@function_tool+async def my_tool(wrapper: RunContextWrapper[UserInfo]) -> str:+ user = wrapper.context+ return f"Processing for {user.name}"+```++### 3. **Running with Context**+```python+user_context = UserInfo(name="Alice", uid=123)+result = await Runner.run(agent, "message", context=user_context)+```++### 4. **Context Updates**+```python+@function_tool+async def update_preference(wrapper: RunContextWrapper[UserInfo], key: str, value: str) -> str:+ wrapper.context.preferences[key] = value+ return f"Updated {key} to {value}"+```++## π‘ Context Management Best Practices++1. **Use Dataclasses**: Leverage Python dataclasses for clean context objects+2. **Type Safety**: Always use generic typing for compile-time validation+3. **Immutable Where Possible**: Consider frozen dataclasses for read-only context+4. **Validation**: Add validation to context object initialization+5. **Documentation**: Document context fields and their purposes clearly++## π Related Concepts++- **Sessions**: Context works alongside session memory for comprehensive state+- **Guardrails**: Context can be used in guardrail validation logic+- **Tool Calling**: Context enables sophisticated tool behavior++## π¨ Common Pitfalls++- **Missing Generic Types**: Always specify context type in Agent[YourContextType]+- **Context Mutations**: Be careful about unintended context modifications+- **Memory Leaks**: Clean up large context objects when no longer needed+- **Thread Safety**: Consider concurrent access in multi-threaded applications++## π‘ Pro Tips++- **Start Simple**: Begin with basic user info, expand to complex state objects+- **Validate Early**: Add validation to context object constructors+- **Use Type Hints**: Leverage Python type hints for better IDE support+- **Consider Immutability**: Use frozen dataclasses for read-only context when appropriate+- **Document Context**: Clear documentation helps team members understand context structure++## π Next Steps++After mastering context management, you'll be ready for:+- **[Tutorial 6: Guardrails & Validation](../6_guardrails_validation/README.md)** - Input/output safety with context+- **[Tutorial 7: Sessions](../7_sessions/README.md)** - Combining context with conversation memory+- **[Tutorial 8: Production Patterns](../8_production_patterns/README.md)** - Scaling context in real applicationsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/agent.pynew file mode 100644index 00000000..2f9f7d2c--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/agent.py@@ -0,0 +1,83 @@+from dataclasses import dataclass+from agents import Agent, RunContextWrapper, Runner, function_tool++@dataclass+class UserInfo:+ """Context object containing user information and session data"""+ name: str+ uid: int+ preferences: dict = None++ def __post_init__(self):+ if self.preferences is None:+ self.preferences = {}++@function_tool+async def fetch_user_profile(wrapper: RunContextWrapper[UserInfo]) -> str:+ """Fetch detailed user profile information from the context"""+ user = wrapper.context+ return f"User Profile: {user.name} (ID: {user.uid}), Preferences: {user.preferences}"++@function_tool+async def update_user_preference(wrapper: RunContextWrapper[UserInfo], key: str, value: str) -> str:+ """Update a user preference in the context"""+ user = wrapper.context+ user.preferences[key] = value+ return f"Updated {user.name}'s preference: {key} = {value}"++@function_tool+async def get_personalized_greeting(wrapper: RunContextWrapper[UserInfo]) -> str:+ """Generate a personalized greeting based on user context"""+ user = wrapper.context+ preferred_style = user.preferences.get('greeting_style', 'formal')++ if preferred_style == 'casual':+ return f"Hey {user.name}! What's up?"+ elif preferred_style == 'friendly':+ return f"Hi there, {user.name}! How can I help you today?"+ else:+ return f"Good day, {user.name}. How may I assist you?"++# Create agent with context-aware tools+root_agent = Agent[UserInfo](+ name="Context-Aware Assistant",+ instructions="""+ You are a personalized assistant that uses user context to provide tailored responses.++ You have access to:+ - User profile information (name, ID, preferences)+ - Ability to update user preferences+ - Personalized greeting generation++ Use the context tools to:+ 1. Fetch user information when needed+ 2. Update preferences when users express them+ 3. Provide personalized greetings and responses++ Always consider the user's context when responding.+ """,+ tools=[fetch_user_profile, update_user_preference, get_personalized_greeting]+)++# Example usage with context+async def context_example():+ """Demonstrates context management with user information"""++ # Create user context+ user_context = UserInfo(+ name="Alice Johnson",+ uid=12345,+ preferences={"greeting_style": "friendly", "topic_interest": "technology"}+ )++ # Run agent with context+ result = await Runner.run(+ root_agent,+ "Hello! I'd like to know about my profile and prefer casual greetings.",+ context=user_context+ )++ print(f"Response: {result.final_output}")+ print(f"Updated context: {user_context}")++ return resultdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/6_guardrails_validation/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/6_guardrails_validation/README.mdnew file mode 100644index 00000000..cb16758b--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/6_guardrails_validation/README.md@@ -0,0 +1,292 @@+# π‘οΈ Tutorial 6: Guardrails & Validation++Master AI safety and validation with the OpenAI Agents SDK! This tutorial teaches you how to implement input and output guardrails to create safe, reliable AI agents that validate requests and responses before and after agent execution.++## π― What You'll Learn++- **Input Guardrails**: Validate and filter user inputs before processing+- **Output Guardrails**: Check and sanitize agent responses before delivery+- **Guardrail Agents**: Specialized agents for validation and safety checks+- **Tripwire System**: Automatic blocking when validation fails+- **Exception Handling**: Proper error handling for guardrail violations+- **Production Safety**: Real-world patterns for AI safety in production++## π§ Core Concept: What are Guardrails?++Guardrails are **automated safety mechanisms** that validate inputs and outputs to ensure AI agents operate within acceptable boundaries. Think of guardrails as **safety checkpoints** that:++- Prevent processing of inappropriate or harmful content+- Block responses that violate safety policies+- Validate inputs against business rules and constraints+- Ensure compliance with content policies+- Provide automatic error handling and user feedback++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β GUARDRAILS WORKFLOW β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β USER INPUT β+β β β+β βΌ β+β βββββββββββββββ 1. INPUT VALIDATION β+β β INPUT β β¦ Check content safety β+β β GUARDRAILS β β¦ Validate business rules β+β βββββββββββββββ β¦ Filter inappropriate requests β+β β β+β βΌ 2. PASS/BLOCK DECISION β+β βββββββββββββββ β+β β AGENT β β PASS: Continue to agent β+β β PROCESSING β π« BLOCK: Throw exception β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 3. OUTPUT VALIDATION β+β β OUTPUT β β¦ Safety check responses β+β β GUARDRAILS β β¦ Filter sensitive information β+β βββββββββββββββ β¦ Ensure policy compliance β+β β β+β βΌ 4. FINAL DECISION β+β βββββββββββββββ β+β β FINAL β β SAFE: Return to user β+β β RESPONSE β π« UNSAFE: Block and handle β+β βββββββββββββββ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Key Guardrails Concepts++### **Input Guardrails**+Validate user inputs before agent processing:++```python+@input_guardrail+async def content_filter(ctx, agent, input) -> GuardrailFunctionOutput:+ # Check if input violates policies+ if is_inappropriate(input):+ return GuardrailFunctionOutput(+ tripwire_triggered=True,+ output_info="Content blocked for safety"+ )+ return GuardrailFunctionOutput(tripwire_triggered=False)+```++### **Output Guardrails**+Validate agent responses before delivery:++```python+@output_guardrail+async def response_filter(ctx, agent, output) -> GuardrailFunctionOutput:+ # Check if response contains sensitive data+ if contains_sensitive_info(output):+ return GuardrailFunctionOutput(+ tripwire_triggered=True,+ output_info="Response blocked for safety"+ )+ return GuardrailFunctionOutput(tripwire_triggered=False)+```++### **Guardrail Agents**+Specialized agents for validation logic:++```python+validation_agent = Agent(+ name="Content Validator",+ instructions="Check content for safety violations",+ output_type=SafetyCheck+)+```++## π§ͺ What This Demonstrates++### **1. Math Homework Detection**+- Input guardrail that detects academic homework requests+- Confidence-based blocking with threshold validation+- Structured output validation with Pydantic models++### **2. Content Safety Validation**+- Output guardrail for inappropriate content detection+- Severity-based filtering (low, medium, high)+- Automated response blocking for policy violations++### **3. Exception Handling**+- `InputGuardrailTripwireTriggered` exception handling+- `OutputGuardrailTripwireTriggered` exception handling+- Graceful error recovery and user feedback++### **4. Guardrail Integration**+- Seamless integration with existing agent workflows+- Multiple guardrails on single agent+- Custom validation logic with business rules++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How to implement input validation to filter requests+- β Creating output guardrails for response safety+- β Building specialized guardrail agents for validation+- β Handling guardrail exceptions gracefully+- β Production-ready safety patterns for AI applications++## π Getting Started++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the guardrails example**:+ ```python+ import asyncio+ from agent import guardrails_example, test_input_guardrail++ # Test guardrails system+ asyncio.run(guardrails_example())+ asyncio.run(test_input_guardrail())+ ```++## π§ͺ Sample Use Cases++### Input Guardrail Testing+- "How do I reset my password?" β (Should pass)+- "Can you solve this equation: 2x + 5 = 15?" π« (Should trigger homework detection)+- "What are your product features?" β (Should pass)++### Output Guardrail Testing+- Normal customer support responses β+- Responses containing sensitive information π«+- Policy-violating content π«++### Exception Scenarios+- Graceful handling of blocked requests+- User-friendly error messages+- Logging and monitoring of guardrail violations++## π§ Key Guardrail Patterns++### 1. **Input Validation Pattern**+```python+@input_guardrail+async def validate_input(ctx, agent, input) -> GuardrailFunctionOutput:+ validation_result = await validate_with_ai(input)+ return GuardrailFunctionOutput(+ tripwire_triggered=validation_result.is_violation,+ output_info=validation_result.details+ )+```++### 2. **Output Safety Pattern**+```python+@output_guardrail+async def safety_check(ctx, agent, output) -> GuardrailFunctionOutput:+ safety_result = await check_safety(output.response)+ return GuardrailFunctionOutput(+ tripwire_triggered=safety_result.is_unsafe,+ output_info=safety_result.reason+ )+```++### 3. **Exception Handling Pattern**+```python+try:+ result = await Runner.run(protected_agent, user_input)+ return result.final_output+except InputGuardrailTripwireTriggered as e:+ return "Request blocked by safety filters"+except OutputGuardrailTripwireTriggered as e:+ return "Response blocked for safety reasons"+```++### 4. **Confidence-Based Blocking**+```python+return GuardrailFunctionOutput(+ tripwire_triggered=violation_detected and confidence > 0.7,+ output_info={"confidence": confidence, "reason": reason}+)+```++## π‘ Guardrails Best Practices++1. **Layered Defense**: Use both input and output guardrails for comprehensive protection+2. **Confidence Thresholds**: Implement confidence-based blocking to reduce false positives+3. **Clear Messaging**: Provide helpful error messages that guide users to appropriate requests+4. **Performance Optimization**: Cache validation results and use efficient validation models+5. **Monitoring & Logging**: Track guardrail violations for system improvement++## π§ Advanced Patterns++### **Multi-Level Validation**+```python+agent = Agent(+ name="Protected Agent",+ input_guardrails=[content_filter, spam_detector, policy_checker],+ output_guardrails=[safety_validator, privacy_filter]+)+```++### **Context-Aware Guardrails**+```python+@input_guardrail+async def user_context_validator(ctx: RunContextWrapper[UserInfo], agent, input):+ user = ctx.context+ # Validate based on user permissions or context+ if user.permission_level < required_level:+ return GuardrailFunctionOutput(tripwire_triggered=True)+```++### **Business Rule Validation**+```python+@input_guardrail+async def business_rules(ctx, agent, input) -> GuardrailFunctionOutput:+ # Validate against business constraints+ if violates_business_rules(input):+ return GuardrailFunctionOutput(+ tripwire_triggered=True,+ output_info="Request violates business policies"+ )+```++## π¨ Common Pitfalls++- **Over-Blocking**: Setting thresholds too low can block legitimate requests+- **Under-Blocking**: Setting thresholds too high may allow harmful content+- **Performance Impact**: Heavy validation can slow response times+- **False Positives**: Poorly trained validation models may block valid requests++## π‘ Pro Tips++- **Test Thoroughly**: Create comprehensive test suites for guardrail validation+- **Monitor Metrics**: Track false positive and false negative rates+- **Iterative Improvement**: Continuously refine validation logic based on real usage+- **User Feedback**: Implement appeals process for blocked requests+- **Gradual Rollout**: Deploy new guardrails gradually with monitoring++## π Production Considerations++### **Scalability**+- Use efficient validation models+- Implement caching for repeated validations+- Consider async validation for better performance++### **Monitoring**+- Log all guardrail decisions for analysis+- Track violation patterns and trends+- Monitor system performance impact++### **Compliance**+- Align guardrails with regulatory requirements+- Implement audit trails for compliance reporting+- Regular review and updates of validation rules++## π Next Steps++After mastering guardrails, you'll be ready for:+- **[Tutorial 7: Sessions](../7_sessions/README.md)** - Combining safety with conversation memory+- **[Tutorial 8: Production Patterns](../8_production_patterns/README.md)** - Scaling guardrails in production+- **[Tutorial 9: Advanced Security](../9_advanced_security/README.md)** - Enterprise-grade AI safety patternsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/6_guardrails_validation/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/6_guardrails_validation/agent.pynew file mode 100644index 00000000..e336b268--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/6_guardrails_validation/agent.py@@ -0,0 +1,157 @@+from pydantic import BaseModel+from agents import (+ Agent,+ GuardrailFunctionOutput,+ InputGuardrailTripwireTriggered,+ OutputGuardrailTripwireTriggered,+ RunContextWrapper,+ Runner,+ TResponseInputItem,+ input_guardrail,+ output_guardrail,+)++# Pydantic models for guardrail outputs+class MathHomeworkCheck(BaseModel):+ is_math_homework: bool+ reasoning: str+ confidence: float++class ContentSafetyCheck(BaseModel):+ is_inappropriate: bool+ reasoning: str+ severity: str++class AgentResponse(BaseModel):+ response: str++# Guardrail agents+input_guardrail_agent = Agent(+ name="Input Guardrail",+ instructions="""+ Check if the user is asking for math homework help or inappropriate content.++ Classify as math homework if:+ - Asking to solve equations, math problems+ - Requesting help with calculations that seem like homework++ Classify as inappropriate if:+ - Contains harmful, offensive, or malicious content+ - Attempts to bypass safety measures++ Provide reasoning and confidence score (0-1).+ """,+ output_type=MathHomeworkCheck+)++output_guardrail_agent = Agent(+ name="Output Guardrail",+ instructions="""+ Check if the agent's response contains inappropriate content or sensitive information.++ Flag as inappropriate if:+ - Contains harmful or offensive language+ - Provides dangerous instructions+ - Leaks sensitive information++ Assign severity: low, medium, high+ """,+ output_type=ContentSafetyCheck+)++# Input guardrail function+@input_guardrail+async def math_homework_guardrail(+ ctx: RunContextWrapper[None],+ agent: Agent,+ input: str | list[TResponseInputItem]+) -> GuardrailFunctionOutput:+ """Prevents math homework requests from being processed"""++ result = await Runner.run(input_guardrail_agent, input, context=ctx.context)+ output = result.final_output++ return GuardrailFunctionOutput(+ output_info=output,+ tripwire_triggered=output.is_math_homework and output.confidence > 0.7+ )++# Output guardrail function+@output_guardrail+async def content_safety_guardrail(+ ctx: RunContextWrapper[None],+ agent: Agent,+ output: AgentResponse+) -> GuardrailFunctionOutput:+ """Ensures agent responses are safe and appropriate"""++ result = await Runner.run(output_guardrail_agent, output.response, context=ctx.context)+ safety_check = result.final_output++ return GuardrailFunctionOutput(+ output_info=safety_check,+ tripwire_triggered=safety_check.is_inappropriate and safety_check.severity in ["medium", "high"]+ )++# Main agent with guardrails+root_agent = Agent(+ name="Protected Customer Support Agent",+ instructions="""+ You are a helpful customer support agent.++ You help customers with:+ - Product questions and information+ - Account issues and support+ - General inquiries and guidance++ You DO NOT help with:+ - Academic homework (especially math)+ - Inappropriate or harmful requests+ - Sensitive or confidential information++ Be helpful but maintain appropriate boundaries.+ """,+ input_guardrails=[math_homework_guardrail],+ output_guardrails=[content_safety_guardrail],+ output_type=AgentResponse+)++# Example usage with guardrails+async def guardrails_example():+ """Demonstrates guardrails with various inputs"""++ test_cases = [+ "How do I reset my password?", # Should pass+ "Can you solve this equation: 2x + 5 = 15?", # Should trigger input guardrail+ "What are your product features?", # Should pass+ ]++ for i, test_input in enumerate(test_cases, 1):+ print(f"\n--- Test Case {i}: {test_input} ---")++ try:+ result = await Runner.run(root_agent, test_input)+ print(f"β Success: {result.final_output.response}")++ except InputGuardrailTripwireTriggered as e:+ print(f"π« Input Guardrail Triggered: {e}")++ except OutputGuardrailTripwireTriggered as e:+ print(f"β οΈ Output Guardrail Triggered: {e}")++ except Exception as e:+ print(f"β Error: {e}")++# Standalone example functions+async def test_input_guardrail():+ """Test input guardrail specifically"""+ try:+ await Runner.run(root_agent, "Can you help me solve this calculus problem?")+ print("β Guardrail should have triggered")+ except InputGuardrailTripwireTriggered:+ print("β Input guardrail correctly triggered for math homework")++async def test_valid_request():+ """Test valid customer support request"""+ result = await Runner.run(root_agent, "I'm having trouble logging into my account. Can you help?")+ print(f"β Valid request processed: {result.final_output.response}")diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/6_guardrails_validation/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/6_guardrails_validation/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/6_guardrails_validation/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/README.mdnew file mode 100644index 00000000..21498483--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/README.md@@ -0,0 +1,64 @@+# Basic Sessions++Demonstrates fundamental session memory management with SQLiteSession for automatic conversation history.++## π― What This Demonstrates++- **In-Memory Sessions**: Temporary session storage for development+- **Persistent Sessions**: File-based session storage for production+- **Multi-Turn Conversations**: Automatic context preservation+- **Session Memory**: Eliminating manual `.to_input_list()` handling++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import in_memory_session_example, persistent_session_example++ # Test in-memory sessions+ asyncio.run(in_memory_session_example())++ # Test persistent sessions+ asyncio.run(persistent_session_example())+ ```++## π‘ Key Concepts++- **SQLiteSession**: Automatic conversation memory management+- **In-Memory vs Persistent**: Choose storage based on use case+- **Session IDs**: Organizing conversations by unique identifiers+- **Automatic Context**: No manual conversation threading required++## π§ͺ Available Examples++### In-Memory Sessions+- Temporary conversation storage+- Lost when process ends+- Perfect for development and testing++### Persistent Sessions+- File-based conversation storage+- Survives application restarts+- Essential for production applications++### Multi-Turn Conversations+- Extended conversation flows+- Automatic context preservation+- Natural conversation progression++## π Next Steps++- [Memory Operations](../7_2_memory_operations/README.md) - Advanced memory manipulation+- [Multi Sessions](../7_3_multi_sessions/README.md) - Managing multiple conversationsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/__init__.pynew file mode 100644index 00000000..7b7b8860--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/__init__.py@@ -0,0 +1 @@+# Basic Sessions module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/agent.pynew file mode 100644index 00000000..328918d5--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/agent.py@@ -0,0 +1,145 @@+from agents import Agent, Runner, SQLiteSession++# Create an agent for session demonstrations+root_agent = Agent(+ name="Session Demo Assistant",+ instructions="""+ You are a helpful assistant that demonstrates session memory.++ Remember previous conversation context and reference it when relevant.+ Reply concisely but show that you remember previous interactions.+ """+)++# Example 1: In-memory session (temporary)+async def in_memory_session_example():+ """Demonstrates in-memory SQLite session that doesn't persist"""++ # In-memory session - lost when process ends+ session = SQLiteSession("temp_conversation")++ print("=== In-Memory Session Example ===")++ # First turn+ result = await Runner.run(+ root_agent,+ "My name is Alice and I live in San Francisco.",+ session=session+ )+ print(f"Turn 1: {result.final_output}")++ # Second turn - agent remembers automatically+ result = await Runner.run(+ root_agent,+ "What city do I live in?",+ session=session+ )+ print(f"Turn 2: {result.final_output}")++ return session++# Example 2: Persistent session (survives restarts)+async def persistent_session_example():+ """Demonstrates persistent SQLite session that saves to file"""++ # Persistent session - saves to database file+ session = SQLiteSession("user_123", "conversation_history.db")++ print("\n=== Persistent Session Example ===")++ # First conversation+ result = await Runner.run(+ root_agent,+ "I'm a software developer working on AI projects.",+ session=session+ )+ print(f"First message: {result.final_output}")++ # Second conversation - context preserved+ result = await Runner.run(+ root_agent,+ "What kind of work do I do?",+ session=session+ )+ print(f"Follow-up: {result.final_output}")++ return session++# Example 3: Multi-turn conversation (mimicking OpenAI SDK docs example)+async def multi_turn_conversation():+ """Demonstrates extended conversation with automatic memory like SDK docs"""++ session = SQLiteSession("conversation_123", "conversations.db")++ print("\n=== Multi-Turn Conversation (like SDK docs) ===")++ # Similar to the OpenAI SDK documentation example+ print("π First turn:")+ result = await Runner.run(root_agent, "What city is the Golden Gate Bridge in?", session=session)+ print(f"User: What city is the Golden Gate Bridge in?")+ print(f"Assistant: {result.final_output}")++ print("\nποΈ Second turn (agent remembers automatically):")+ result = await Runner.run(root_agent, "What state is it in?", session=session)+ print(f"User: What state is it in?")+ print(f"Assistant: {result.final_output}")++ print("\nπ₯ Third turn (continuing context):")+ result = await Runner.run(root_agent, "What's the population of that state?", session=session)+ print(f"User: What's the population of that state?")+ print(f"Assistant: {result.final_output}")++ print("\nπ‘ Notice how the agent remembers context automatically!")+ print(" Sessions handle conversation history without manual .to_input_list()")++ return session++# Example 4: Session comparison - with vs without sessions+async def session_comparison():+ """Demonstrates the difference between using sessions vs no sessions"""++ print("\n=== Session vs No Session Comparison ===")++ # Without session (no memory)+ print("π« WITHOUT Sessions (no memory):")+ result1 = await Runner.run(root_agent, "My name is Alice")+ print(f"Turn 1: {result1.final_output}")++ result2 = await Runner.run(root_agent, "What's my name?")+ print(f"Turn 2: {result2.final_output}")+ print(" βͺοΈ Agent doesn't remember - no session used")++ # With session (automatic memory)+ print(f"\nβ WITH Sessions (automatic memory):")+ session = SQLiteSession("comparison_demo", "comparison.db")++ result3 = await Runner.run(root_agent, "My name is Alice", session=session)+ print(f"Turn 1: {result3.final_output}")++ result4 = await Runner.run(root_agent, "What's my name?", session=session)+ print(f"Turn 2: {result4.final_output}")+ print(" βͺοΈ Agent remembers - session automatically handles history!")++ return session++# Main execution function+async def main():+ """Run all basic session examples"""+ print("π§ OpenAI Agents SDK - Basic Sessions Examples")+ print("=" * 60)++ await in_memory_session_example()+ await persistent_session_example()+ await multi_turn_conversation()+ await session_comparison()++ print("\nβ Basic sessions examples completed!")+ print("Key concepts demonstrated:")+ print(" β’ In-memory sessions: SQLiteSession('session_id')")+ print(" β’ Persistent sessions: SQLiteSession('session_id', 'file.db')")+ print(" β’ Automatic memory: No manual .to_input_list() needed")+ print(" β’ Session vs no session: Memory comparison")++if __name__ == "__main__":+ import asyncio+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_1_basic_sessions/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/README.mdnew file mode 100644index 00000000..b2c0dc95--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/README.md@@ -0,0 +1,69 @@+# Memory Operations++Demonstrates advanced session memory operations including item manipulation, conversation corrections, and session management.++## π― What This Demonstrates++- **get_items()**: Retrieving conversation history programmatically+- **add_items()**: Manually adding conversation items+- **pop_item()**: Removing and correcting conversation turns+- **clear_session()**: Resetting conversation history++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import basic_memory_operations, conversation_corrections++ # Test memory operations+ asyncio.run(basic_memory_operations())++ # Test conversation corrections+ asyncio.run(conversation_corrections())+ ```++## π‘ Key Concepts++- **Memory Inspection**: Understanding conversation structure+- **Manual Item Management**: Adding custom conversation entries+- **Conversation Corrections**: Undoing and modifying interactions+- **Session Cleanup**: Clearing conversation history++## π§ͺ Available Operations++### Basic Memory Operations+- Retrieving conversation items+- Adding custom conversation entries+- Inspecting session contents++### Conversation Corrections+- Using `pop_item()` to undo responses+- Correcting user questions+- Modifying conversation flow++### Session Management+- Clearing conversation history+- Starting fresh conversations+- Managing session lifecycle++### Memory Inspection+- Analyzing conversation structure+- Limiting retrieved items+- Understanding memory patterns++## π Next Steps++- [Basic Sessions](../7_1_basic_sessions/README.md) - Session fundamentals+- [Multi Sessions](../7_3_multi_sessions/README.md) - Multiple conversation managementdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/__init__.pynew file mode 100644index 00000000..6f6c3bfe--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/__init__.py@@ -0,0 +1 @@+# Memory Operations module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/agent.pynew file mode 100644index 00000000..08382eae--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/agent.py@@ -0,0 +1,188 @@+from agents import Agent, Runner, SQLiteSession++# Create agent for memory operations demonstrations+root_agent = Agent(+ name="Memory Operations Agent",+ instructions="""+ You are a helpful assistant demonstrating session memory operations.++ Remember previous conversation context and reference it when relevant.+ Reply concisely but show understanding of conversation history.+ """+)++# Example 1: Basic memory operations - get_items()+async def basic_memory_operations():+ """Demonstrates get_items, add_items, and session inspection from OpenAI SDK docs"""++ session = SQLiteSession("memory_demo", "operations.db")++ print("=== Basic Memory Operations ===")++ # Start conversation+ result = await Runner.run(root_agent, "Hello, my favorite color is blue.", session=session)+ print(f"Agent Response: {result.final_output}")++ # Demonstrate get_items() - retrieve conversation history+ items = await session.get_items()+ print(f"\nπ Session Memory Inspection (get_items()):")+ print(f" Total items in session: {len(items)}")+ for i, item in enumerate(items, 1):+ content_preview = item['content'][:50] + "..." if len(item['content']) > 50 else item['content']+ print(f" {i}. [{item['role']}]: {content_preview}")++ # Demonstrate add_items() - manually add conversation items+ print(f"\nβ Adding Custom Items (add_items()):")+ custom_items = [+ {"role": "user", "content": "I also love hiking and photography."},+ {"role": "assistant", "content": "Wonderful! Blue, hiking, and photography - I'll remember these interests."}+ ]+ await session.add_items(custom_items)++ updated_items = await session.get_items()+ print(f" Items after manual addition: {len(updated_items)} (was {len(items)})")++ # Continue conversation with enriched context+ result = await Runner.run(root_agent, "What hobbies do I have?", session=session)+ print(f"\nπ€ Agent with enriched context: {result.final_output}")++ return session++# Example 2: Using pop_item() for corrections (from OpenAI SDK docs)+async def conversation_corrections():+ """Demonstrates using pop_item to correct or undo conversation turns"""++ session = SQLiteSession("correction_demo", "corrections.db")++ print("\n=== Conversation Corrections with pop_item() ===")++ # Initial question with wrong math+ result = await Runner.run(root_agent, "What's 2 + 2?", session=session)+ print(f"β Original Question: What's 2 + 2?")+ print(f"π€ Agent Answer: {result.final_output}")++ print(f"\nπ Items before correction: {len(await session.get_items())}")++ # User wants to correct their question using pop_item()+ print(f"\nπ Correcting conversation using pop_item()...")++ # Remove assistant's response using pop_item()+ assistant_item = await session.pop_item()+ if assistant_item:+ print(f" β©οΈ Removed assistant response: {assistant_item['content'][:50]}...")++ # Remove user's original question using pop_item()+ user_item = await session.pop_item()+ if user_item:+ print(f" β©οΈ Removed user question: {user_item['content']}")++ print(f"π Items after corrections: {len(await session.get_items())}")++ # Ask corrected question+ result = await Runner.run(root_agent, "What's 2 + 3?", session=session)+ print(f"\nβ Corrected Question: What's 2 + 3?")+ print(f"π€ New Answer: {result.final_output}")++ return session++# Example 3: clear_session() for session reset (from OpenAI SDK docs)+async def session_management():+ """Demonstrates clear_session() and session lifecycle management"""++ session = SQLiteSession("management_demo", "management.db")++ print("\n=== Session Management with clear_session() ===")++ # Build up conversation history+ print("ποΈ Building conversation history...")+ await Runner.run(root_agent, "I work as a teacher.", session=session)+ await Runner.run(root_agent, "I teach mathematics.", session=session)+ await Runner.run(root_agent, "I love solving puzzles.", session=session)++ items_before = await session.get_items()+ print(f"π Session contains {len(items_before)} items before clearing")++ # Test agent memory before clearing+ result = await Runner.run(root_agent, "What do I do for work?", session=session)+ print(f"π€ Agent remembers: {result.final_output}")++ # Demonstrate clear_session() - removes all conversation history+ print(f"\nπ§Ή Clearing session with clear_session()...")+ await session.clear_session()++ items_after = await session.get_items()+ print(f"π Session contains {len(items_after)} items after clearing")++ # Test fresh conversation after clearing+ result = await Runner.run(root_agent, "Do you know anything about me?", session=session)+ print(f"π€ Fresh conversation (no memory): {result.final_output}")++ return session++# Example 4: Advanced memory inspection with get_items(limit)+async def memory_inspection():+ """Demonstrates get_items with limit parameter and detailed memory analysis"""++ session = SQLiteSession("inspection_demo", "inspection.db")++ print("\n=== Advanced Memory Inspection ===")++ # Build longer conversation for inspection+ conversation_items = [+ "Hello, I'm learning about AI.",+ "What is machine learning?",+ "How does deep learning work?",+ "What's the difference between AI and ML?",+ "Can you explain neural networks?"+ ]++ print("ποΈ Building extended conversation...")+ for item in conversation_items:+ await Runner.run(root_agent, item, session=session)++ # Demonstrate get_items() with limit parameter (from SDK docs)+ print(f"\nπ Memory Inspection with get_items(limit=3):")+ recent_items = await session.get_items(limit=3)+ print(f" Last 3 items (out of full conversation):")+ for i, item in enumerate(recent_items, 1):+ content_preview = item['content'][:60] + "..." if len(item['content']) > 60 else item['content']+ print(f" {i}. [{item['role']}]: {content_preview}")++ # Compare with full conversation+ all_items = await session.get_items()+ print(f"\nπ Full conversation analysis:")+ print(f" Total items in session: {len(all_items)}")+ print(f" Recent items retrieved: {len(recent_items)}")++ # Count items by role+ user_items = [item for item in all_items if item['role'] == 'user']+ assistant_items = [item for item in all_items if item['role'] == 'assistant']+ print(f" User messages: {len(user_items)}")+ print(f" Assistant responses: {len(assistant_items)}")++ return session++# Main execution function+async def main():+ """Run all memory operations examples"""+ import asyncio++ print("π§ OpenAI Agents SDK - Memory Operations Examples")+ print("=" * 60)++ await basic_memory_operations()+ await conversation_corrections()+ await session_management()+ await memory_inspection()++ print("\nβ All memory operations examples completed!")+ print("Key operations demonstrated:")+ print(" β’ get_items() - Retrieve conversation history")+ print(" β’ add_items() - Manually add conversation items")+ print(" β’ pop_item() - Remove last item for corrections")+ print(" β’ clear_session() - Reset conversation history")+ print(" β’ get_items(limit=N) - Retrieve recent items only")++if __name__ == "__main__":+ import asyncio+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_2_memory_operations/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/README.mdnew file mode 100644index 00000000..8a4ee884--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/README.md@@ -0,0 +1,71 @@+# Multi Sessions++Demonstrates managing multiple concurrent sessions for different users, contexts, and conversation types.++## π― What This Demonstrates++- **Multi-User Sessions**: Separate conversations for different users+- **Context-Based Sessions**: Different session types (support, sales, etc.)+- **Shared Sessions**: Multiple agents using the same conversation+- **Session Organization**: Naming strategies and management patterns++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import multi_user_sessions, context_based_sessions++ # Test multi-user sessions+ asyncio.run(multi_user_sessions())++ # Test context-based sessions+ asyncio.run(context_based_sessions())+ ```++## π‘ Key Concepts++- **Session Isolation**: Keeping conversations separate+- **User-Based Sessions**: Individual user conversation histories+- **Context Switching**: Different conversation types and purposes+- **Agent Handoffs**: Sharing sessions between specialized agents++## π§ͺ Available Patterns++### Multi-User Sessions+- Separate sessions for Alice and Bob+- Isolated conversation histories+- User-specific context preservation++### Context-Based Sessions+- Support ticket conversations+- Sales inquiry conversations+- Feature-specific sessions++### Shared Session Agents+- Customer handoff scenarios+- Multiple agents, single conversation+- Context preservation across agent switches++### Session Organization+- User-based naming: `user_123`+- Feature-based naming: `chat_feature_user_123`+- Thread-based naming: `thread_abc123`+- Timestamp-based naming: `user_123_20241215`++## π Next Steps++- [Basic Sessions](../7_1_basic_sessions/README.md) - Session fundamentals+- [Memory Operations](../7_2_memory_operations/README.md) - Advanced memory manipulation+- [Tutorial 8: Handoffs & Delegation](../../8_handoffs_delegation/README.md) - Agent handoffsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/__init__.pynew file mode 100644index 00000000..e34678fa--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/__init__.py@@ -0,0 +1 @@+# Multi Sessions module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/agent.pynew file mode 100644index 00000000..d48cc492--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/agent.py@@ -0,0 +1,150 @@+from agents import Agent, Runner, SQLiteSession++# Create agents for multi-session demonstrations+support_agent = Agent(+ name="Support Agent",+ instructions="You are a customer support representative. Help with account and technical issues."+)++sales_agent = Agent(+ name="Sales Agent",+ instructions="You are a sales representative. Help with product information and purchases."+)++# Example 1: Different users with separate sessions+async def multi_user_sessions():+ """Demonstrates separate sessions for different users"""++ print("=== Multi-User Sessions ===")++ # Create separate sessions for different users+ alice_session = SQLiteSession("user_alice", "multi_user.db")+ bob_session = SQLiteSession("user_bob", "multi_user.db")++ # Alice's conversation+ print("Alice's conversation:")+ result = await Runner.run(support_agent, "I forgot my password", session=alice_session)+ print(f"Alice: I forgot my password")+ print(f"Support: {result.final_output}")++ result = await Runner.run(support_agent, "My email is [email protected]", session=alice_session)+ print(f"Alice: My email is [email protected]")+ print(f"Support: {result.final_output}")++ # Bob's separate conversation+ print("\nBob's conversation:")+ result = await Runner.run(support_agent, "My app keeps crashing", session=bob_session)+ print(f"Bob: My app keeps crashing")+ print(f"Support: {result.final_output}")++ # Alice continues her conversation (agent remembers her context)+ print("\nAlice continues:")+ result = await Runner.run(support_agent, "Did you find my account?", session=alice_session)+ print(f"Alice: Did you find my account?")+ print(f"Support: {result.final_output}")++ return alice_session, bob_session++# Example 2: Different conversation contexts+async def context_based_sessions():+ """Demonstrates sessions for different conversation contexts"""++ print("\n=== Context-Based Sessions ===")++ # Different conversation contexts+ support_session = SQLiteSession("support_ticket_123", "contexts.db")+ sales_session = SQLiteSession("sales_inquiry_456", "contexts.db")++ # Support conversation+ print("Support context:")+ result = await Runner.run(support_agent, "I can't access my premium features", session=support_session)+ print(f"Customer: I can't access my premium features")+ print(f"Support: {result.final_output}")++ # Sales conversation+ print("\nSales context:")+ result = await Runner.run(sales_agent, "What premium features do you offer?", session=sales_session)+ print(f"Prospect: What premium features do you offer?")+ print(f"Sales: {result.final_output}")++ # Continue support conversation+ print("\nBack to support:")+ result = await Runner.run(support_agent, "I'm on the premium plan", session=support_session)+ print(f"Customer: I'm on the premium plan")+ print(f"Support: {result.final_output}")++ return support_session, sales_session++# Example 3: Shared session across different agents+async def shared_session_agents():+ """Demonstrates how different agents can share the same session"""++ print("\n=== Shared Session Across Agents ===")++ # Shared session for customer handoff scenario+ shared_session = SQLiteSession("customer_handoff", "shared.db")++ # Start with sales agent+ print("Starting with Sales Agent:")+ result = await Runner.run(+ sales_agent,+ "I'm interested in your premium plan but have technical questions.",+ session=shared_session+ )+ print(f"Customer: I'm interested in your premium plan but have technical questions.")+ print(f"Sales: {result.final_output}")++ # Handoff to support agent (same session, so context is preserved)+ print("\nHandoff to Support Agent:")+ result = await Runner.run(+ support_agent,+ "Can you help me understand the technical requirements?",+ session=shared_session+ )+ print(f"Customer: Can you help me understand the technical requirements?")+ print(f"Support: {result.final_output}")++ # Back to sales for closing+ print("\nBack to Sales Agent:")+ result = await Runner.run(+ sales_agent,+ "Thanks for the technical info. How do I upgrade?",+ session=shared_session+ )+ print(f"Customer: Thanks for the technical info. How do I upgrade?")+ print(f"Sales: {result.final_output}")++ return shared_session++# Example 4: Session organization strategies+async def session_organization():+ """Demonstrates different session organization strategies"""++ print("\n=== Session Organization Strategies ===")++ # Strategy 1: User-based with timestamps+ import datetime+ timestamp = datetime.datetime.now().strftime("%Y%m%d")+ user_daily_session = SQLiteSession(f"user_123_{timestamp}", "daily_sessions.db")++ # Strategy 2: Feature-based sessions+ chat_session = SQLiteSession("chat_feature_user_123", "feature_sessions.db")+ support_session = SQLiteSession("support_feature_user_123", "feature_sessions.db")++ # Strategy 3: Thread-based sessions+ thread_session = SQLiteSession("thread_abc123", "thread_sessions.db")++ # Demonstrate different approaches+ print("Daily user session:")+ result = await Runner.run(support_agent, "Daily check-in", session=user_daily_session)+ print(f"Response: {result.final_output}")++ print("\nFeature-specific chat:")+ result = await Runner.run(support_agent, "Chat feature question", session=chat_session)+ print(f"Response: {result.final_output}")++ print("\nThread-based conversation:")+ result = await Runner.run(support_agent, "Thread conversation", session=thread_session)+ print(f"Response: {result.final_output}")++ return user_daily_session, chat_session, thread_sessiondiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/7_3_multi_sessions/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/README.mdnew file mode 100644index 00000000..2bfdacd7--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/README.md@@ -0,0 +1,216 @@+# π― Tutorial 7: Sessions & Memory Management++Master automatic conversation memory with Sessions! This tutorial teaches you how to use the OpenAI Agents SDK's built-in session memory to maintain conversation history across multiple agent runs without manual memory management.++## π― What You'll Learn++- **Automatic Memory**: Sessions handle conversation history automatically+- **SQLite Sessions**: Persistent and in-memory conversation storage+- **Memory Operations**: Adding, retrieving, and managing conversation items+- **Session Management**: Multiple sessions and custom implementations++## π§ Core Concept: What Are Sessions?++Sessions provide **automatic conversation memory** that eliminates the need to manually handle `.to_input_list()` between turns. Think of sessions as a **smart conversation database** that:++- Automatically stores all conversation history+- Retrieves context before each agent run+- Maintains separate conversations for different session IDs+- Supports persistent storage across application restarts++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β SESSION WORKFLOW β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β USER INPUT β+β β β+β βΌ β+β βββββββββββββββ 1. RETRIEVE HISTORY β+β β SESSION ββββββββββββββββββββββββββββββββββββββββββββ β+β β MEMORY β β β+β βββββββββββββββ 2. PREPEND TO INPUT β β+β β β β+β βΌ β β+β βββββββββββββββ β β+β β AGENT β 3. PROCESS WITH CONTEXT β β+β β RUNNER β β β+β βββββββββββββββ β β+β β β β+β βΌ β β+β βββββββββββββββ 4. STORE NEW ITEMS β β+β β RESPONSE ββββββββββββββββββββββββββββββββββββββββββββ β+β β GENERATED β β+β βββββββββββββββ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Tutorial Overview++This tutorial demonstrates **three key session patterns**:++### **1. Basic SQLite Sessions** (`basic_sessions.py`)+- In-memory and persistent session storage+- Automatic conversation history management+- Simple multi-turn conversations++### **2. Advanced Memory Operations** (`memory_operations.py`)+- Memory manipulation with `get_items()`, `add_items()`, `pop_item()`+- Conversation corrections and modifications+- Session management operations++### **3. Multiple Sessions** (`multi_sessions.py`)+- Managing different conversation contexts+- Session isolation and organization+- Custom session implementations++## π Project Structure++```+7_sessions/+βββ README.md # This file - concept explanation+βββ requirements.txt # Dependencies+βββ streamlit_sessions_app.py # Interactive Streamlit demo (recommended)+βββ 7_1_basic_sessions/+β βββ agent.py # SQLite sessions basics+β βββ README.md # Basic sessions documentation+βββ 7_2_memory_operations/+β βββ agent.py # Advanced memory operations+β βββ README.md # Memory operations documentation+βββ 7_3_multi_sessions/+β βββ agent.py # Multiple session management+β βββ README.md # Multi-sessions documentation+βββ env.example # Environment variables template+```++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How to use SQLiteSession for automatic memory management+- β Difference between in-memory and persistent sessions+- β Advanced memory operations for conversation management+- β Managing multiple concurrent sessions+- β When to use sessions vs manual conversation management++## π Getting Started++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Install dependencies**:+ ```bash+ pip install -r requirements.txt+ ```++2. **Set up environment variables**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Launch interactive demo (recommended)**:+ ```bash+ streamlit run streamlit_sessions_app.py+ ```++ OR run individual examples:++4. **Test basic sessions**:+ ```bash+ python 7_1_basic_sessions/agent.py+ ```++5. **Try memory operations**:+ ```bash+ python 7_2_memory_operations/agent.py+ ```++6. **Test multiple sessions**:+ ```bash+ python 7_3_multi_sessions/agent.py+ ```++## π§ͺ Sample Use Cases++### Basic Sessions+- "What city is the Golden Gate Bridge in?" β "What state is it in?"+- "My name is Alice" β "What's my name?"+- "I work as a developer" β "What do I do for work?"++### Memory Operations+- Correcting previous messages with `pop_item()`+- Clearing conversation history with `clear_session()`+- Adding custom conversation items++### Multiple Sessions+- Different users: `user_123`, `user_456`+- Different contexts: `support_ticket_789`, `sales_inquiry_101`+- Different applications: `chatbot_session`, `assistant_session`++## π§ Key Session Patterns++### 1. **Basic Session Usage**+```python+from agents import Agent, Runner, SQLiteSession++agent = Agent(name="Assistant", instructions="Reply concisely.")+session = SQLiteSession("conversation_123")++result = await Runner.run(agent, "Hello", session=session)+```++### 2. **Persistent vs In-Memory**+```python+# In-memory (lost when process ends)+session = SQLiteSession("user_123")++# Persistent file-based+session = SQLiteSession("user_123", "conversations.db")+```++### 3. **Memory Operations**+```python+# Get conversation history+items = await session.get_items()++# Add custom items+await session.add_items([{"role": "user", "content": "Hello"}])++# Remove last item (for corrections)+last_item = await session.pop_item()++# Clear all history+await session.clear_session()+```++## π‘ Session Design Best Practices++1. **Meaningful Session IDs**: Use descriptive IDs like `user_12345` or `support_ticket_789`+2. **Persistent Storage**: Use file-based sessions for production applications+3. **Session Isolation**: Keep different conversation contexts in separate sessions+4. **Memory Management**: Use `pop_item()` for conversation corrections+5. **Cleanup**: Clear sessions when conversations should start fresh++## π Next Steps++After completing this tutorial, you'll be ready for:+- **[Tutorial 8: Handoffs & Delegation](../8_handoffs_delegation/README.md)** - Agent handoffs and task delegation+- **[Tutorial 9: Multi-Agent Orchestration](../9_multi_agent_orchestration/README.md)** - Complex multi-agent workflows+- **[Tutorial 10: Production Patterns](../10_production_patterns/README.md)** - Real-world deployment strategies++## π¨ Troubleshooting++- **Memory Not Persisting**: Ensure you're using file-based SQLiteSession with a database path+- **Session Conflicts**: Use unique session IDs for different conversation contexts+- **Performance Issues**: Consider implementing custom session backends for high-volume applications+- **Database Errors**: Check file permissions for SQLite database files++## π‘ Pro Tips++- **Start Simple**: Begin with in-memory sessions for development and testing+- **Plan Session Architecture**: Design your session ID strategy before building+- **Monitor Memory Usage**: Track conversation length and implement cleanup strategies+- **Test Session Persistence**: Verify that conversations survive application restarts+- **Consider Scaling**: Plan for custom session implementations in production systemsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/requirements.txtnew file mode 100644index 00000000..a88bde1d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/requirements.txt@@ -0,0 +1,3 @@+openai-agents>=1.0.0+streamlit>=1.28.0+python-dotenv>=1.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/streamlit_sessions_app.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/streamlit_sessions_app.pynew file mode 100644index 00000000..9b7d824f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/streamlit_sessions_app.py@@ -0,0 +1,418 @@+import streamlit as st+import asyncio+import os+from datetime import datetime+from agents import Agent, Runner, SQLiteSession+from dotenv import load_dotenv++# Load environment variables+load_dotenv()++# Page configuration+st.set_page_config(+ page_title="Session Management Demo",+ page_icon="π¬",+ layout="wide",+ initial_sidebar_state="expanded"+)++# Initialize agents[email protected]_resource+def initialize_agents():+ """Initialize AI agents for different use cases"""++ main_agent = Agent(+ name="Session Demo Assistant",+ instructions="""+ You are a helpful assistant demonstrating session memory capabilities.++ Remember previous conversation context and reference it when relevant.+ Reply concisely but show that you remember previous interactions.+ Be friendly and professional.+ """+ )++ support_agent = Agent(+ name="Support Agent",+ instructions="You are a customer support representative. Help with account and technical issues. Be helpful and solution-oriented."+ )++ sales_agent = Agent(+ name="Sales Agent",+ instructions="You are a sales representative. Help with product information and purchases. Be enthusiastic and informative."+ )++ return main_agent, support_agent, sales_agent++# Session management functions+class SessionManager:+ def __init__(self):+ self.sessions = {}++ def get_session(self, session_id: str, db_file: str = "demo_sessions.db"):+ """Get or create a session"""+ if session_id not in self.sessions:+ self.sessions[session_id] = SQLiteSession(session_id, db_file)+ return self.sessions[session_id]++ async def clear_session(self, session_id: str):+ """Clear a specific session"""+ if session_id in self.sessions:+ await self.sessions[session_id].clear_session()+ del self.sessions[session_id]++ async def get_session_items(self, session_id: str, limit: int = None):+ """Get conversation items from a session"""+ if session_id in self.sessions:+ return await self.sessions[session_id].get_items(limit=limit)+ return []++ async def add_custom_items(self, session_id: str, items: list):+ """Add custom items to a session"""+ if session_id in self.sessions:+ await self.sessions[session_id].add_items(items)++ async def pop_last_item(self, session_id: str):+ """Remove the last item from a session"""+ if session_id in self.sessions:+ return await self.sessions[session_id].pop_item()+ return None++# Initialize session manager+if 'session_manager' not in st.session_state:+ st.session_state.session_manager = SessionManager()++# Main UI+def main():+ st.title("π Session Management Demo")+ st.markdown("**Demonstrates OpenAI Agents SDK session capabilities**")++ # Initialize agents+ main_agent, support_agent, sales_agent = initialize_agents()++ # Sidebar for session configuration+ with st.sidebar:+ st.header("βοΈ Session Configuration")++ demo_type = st.selectbox(+ "Select Demo Type",+ ["Basic Sessions", "Memory Operations", "Multi Sessions"]+ )++ if demo_type == "Basic Sessions":+ session_type = st.radio(+ "Session Type",+ ["In-Memory", "Persistent"]+ )++ st.divider()++ # Session controls+ st.subheader("Session Controls")++ if st.button("ποΈ Clear All Sessions"):+ with st.spinner("Clearing sessions..."):+ for session_id in list(st.session_state.session_manager.sessions.keys()):+ asyncio.run(st.session_state.session_manager.clear_session(session_id))+ st.success("All sessions cleared!")+ st.rerun()++ # Main content area+ if demo_type == "Basic Sessions":+ render_basic_sessions(main_agent)+ elif demo_type == "Memory Operations":+ render_memory_operations(main_agent)+ elif demo_type == "Multi Sessions":+ render_multi_sessions(support_agent, sales_agent)++def render_basic_sessions(agent):+ """Render the basic sessions demo"""+ st.header("π Basic Sessions Demo")+ st.markdown("Demonstrates fundamental session memory with automatic conversation history.")++ col1, col2 = st.columns(2)++ with col1:+ st.subheader("πΎ In-Memory Session")+ st.caption("Temporary session storage (lost when app restarts)")++ session_id = "in_memory_demo"++ with st.form("in_memory_form"):+ user_input = st.text_input("Your message:", key="in_memory_input")+ submitted = st.form_submit_button("Send Message")++ if submitted and user_input:+ with st.spinner("Processing..."):+ session = st.session_state.session_manager.get_session(session_id)+ result = asyncio.run(Runner.run(agent, user_input, session=session))++ st.success("Message sent!")+ st.write(f"**Assistant:** {result.final_output}")++ # Show conversation history+ if st.button("π Show Conversation", key="show_in_memory"):+ items = asyncio.run(st.session_state.session_manager.get_session_items(session_id))+ if items:+ st.write("**Conversation History:**")+ for i, item in enumerate(items, 1):+ role_emoji = "π€" if item['role'] == 'user' else "π€"+ st.write(f"{i}. {role_emoji} **{item['role'].title()}:** {item['content']}")+ else:+ st.info("No conversation history yet.")++ with col2:+ st.subheader("π½ Persistent Session")+ st.caption("File-based storage (survives app restarts)")++ session_id = "persistent_demo"++ with st.form("persistent_form"):+ user_input = st.text_input("Your message:", key="persistent_input")+ submitted = st.form_submit_button("Send Message")++ if submitted and user_input:+ with st.spinner("Processing..."):+ session = st.session_state.session_manager.get_session(session_id, "persistent_demo.db")+ result = asyncio.run(Runner.run(agent, user_input, session=session))++ st.success("Message sent!")+ st.write(f"**Assistant:** {result.final_output}")++ # Show conversation history+ if st.button("π Show Conversation", key="show_persistent"):+ items = asyncio.run(st.session_state.session_manager.get_session_items(session_id))+ if items:+ st.write("**Conversation History:**")+ for i, item in enumerate(items, 1):+ role_emoji = "π€" if item['role'] == 'user' else "π€"+ st.write(f"{i}. {role_emoji} **{item['role'].title()}:** {item['content']}")+ else:+ st.info("No conversation history yet.")++def render_memory_operations(agent):+ """Render the memory operations demo"""+ st.header("π§ Memory Operations Demo")+ st.markdown("Demonstrates advanced session memory operations including item manipulation and corrections.")++ session_id = "memory_operations_demo"++ # Main conversation area+ st.subheader("π¬ Conversation")+ with st.form("memory_conversation"):+ user_input = st.text_input("Your message:")+ submitted = st.form_submit_button("Send Message")++ if submitted and user_input:+ with st.spinner("Processing..."):+ session = st.session_state.session_manager.get_session(session_id)+ result = asyncio.run(Runner.run(agent, user_input, session=session))++ st.success("Message sent!")+ st.write(f"**Assistant:** {result.final_output}")++ # Memory operations+ col1, col2 = st.columns(2)++ with col1:+ st.subheader("π Memory Inspection")++ if st.button("π Get All Items"):+ items = asyncio.run(st.session_state.session_manager.get_session_items(session_id))+ if items:+ st.write(f"**Total items:** {len(items)}")+ for i, item in enumerate(items, 1):+ role_emoji = "π€" if item['role'] == 'user' else "π€"+ content_preview = item['content'][:100] + "..." if len(item['content']) > 100 else item['content']+ st.write(f"{i}. {role_emoji} **{item['role'].title()}:** {content_preview}")+ else:+ st.info("No items in session yet.")++ # Get limited items+ limit = st.number_input("Get last N items:", min_value=1, max_value=20, value=3)+ if st.button("π Get Recent Items"):+ items = asyncio.run(st.session_state.session_manager.get_session_items(session_id, limit=limit))+ if items:+ st.write(f"**Last {len(items)} items:**")+ for i, item in enumerate(items, 1):+ role_emoji = "π€" if item['role'] == 'user' else "π€"+ st.write(f"{i}. {role_emoji} **{item['role'].title()}:** {item['content']}")+ else:+ st.info("No items to show.")++ with col2:+ st.subheader("βοΈ Memory Manipulation")++ # Add custom items+ st.write("**Add Custom Items:**")+ with st.form("add_items_form"):+ user_content = st.text_area("User message to add:")+ assistant_content = st.text_area("Assistant response to add:")+ add_submitted = st.form_submit_button("β Add Items")++ if add_submitted and user_content and assistant_content:+ custom_items = [+ {"role": "user", "content": user_content},+ {"role": "assistant", "content": assistant_content}+ ]+ asyncio.run(st.session_state.session_manager.add_custom_items(session_id, custom_items))+ st.success("Custom items added!")++ # Pop last item (correction)+ if st.button("βΆ Undo Last Response"):+ popped_item = asyncio.run(st.session_state.session_manager.pop_last_item(session_id))+ if popped_item:+ st.success(f"Removed: {popped_item['role']} - {popped_item['content'][:50]}...")+ else:+ st.warning("No items to remove.")++ # Clear session+ if st.button("ποΈ Clear Session"):+ asyncio.run(st.session_state.session_manager.clear_session(session_id))+ st.success("Session cleared!")++def render_multi_sessions(support_agent, sales_agent):+ """Render the multi-sessions demo"""+ st.header("π₯ Multi Sessions Demo")+ st.markdown("Demonstrates managing multiple conversations and different agent contexts.")++ tab1, tab2, tab3 = st.tabs(["π€ Multi-User", "π’ Context-Based", "π Agent Handoff"])++ with tab1:+ st.subheader("Different Users, Separate Sessions")++ col1, col2 = st.columns(2)++ with col1:+ st.write("**π© Alice's Session**")+ alice_session_id = "user_alice"++ with st.form("alice_form"):+ alice_input = st.text_input("Alice's message:", key="alice_input")+ alice_submitted = st.form_submit_button("Send as Alice")++ if alice_submitted and alice_input:+ with st.spinner("Processing Alice's message..."):+ session = st.session_state.session_manager.get_session(alice_session_id, "multi_user.db")+ result = asyncio.run(Runner.run(support_agent, alice_input, session=session))+ st.write(f"**Support:** {result.final_output}")++ if st.button("π Alice's History", key="alice_history"):+ items = asyncio.run(st.session_state.session_manager.get_session_items(alice_session_id))+ for item in items:+ role_emoji = "π©" if item['role'] == 'user' else "π οΈ"+ st.write(f"{role_emoji} **{item['role'].title()}:** {item['content']}")++ with col2:+ st.write("**π¨ Bob's Session**")+ bob_session_id = "user_bob"++ with st.form("bob_form"):+ bob_input = st.text_input("Bob's message:", key="bob_input")+ bob_submitted = st.form_submit_button("Send as Bob")++ if bob_submitted and bob_input:+ with st.spinner("Processing Bob's message..."):+ session = st.session_state.session_manager.get_session(bob_session_id, "multi_user.db")+ result = asyncio.run(Runner.run(support_agent, bob_input, session=session))+ st.write(f"**Support:** {result.final_output}")++ if st.button("π Bob's History", key="bob_history"):+ items = asyncio.run(st.session_state.session_manager.get_session_items(bob_session_id))+ for item in items:+ role_emoji = "π¨" if item['role'] == 'user' else "π οΈ"+ st.write(f"{role_emoji} **{item['role'].title()}:** {item['content']}")++ with tab2:+ st.subheader("Different Contexts, Different Sessions")++ col1, col2 = st.columns(2)++ with col1:+ st.write("**π οΈ Support Context**")+ support_session_id = "support_context"++ with st.form("support_context_form"):+ support_input = st.text_input("Support question:", key="support_context_input")+ support_submitted = st.form_submit_button("Ask Support")++ if support_submitted and support_input:+ with st.spinner("Processing support question..."):+ session = st.session_state.session_manager.get_session(support_session_id, "contexts.db")+ result = asyncio.run(Runner.run(support_agent, support_input, session=session))+ st.write(f"**Support:** {result.final_output}")++ with col2:+ st.write("**π° Sales Context**")+ sales_session_id = "sales_context"++ with st.form("sales_context_form"):+ sales_input = st.text_input("Sales inquiry:", key="sales_context_input")+ sales_submitted = st.form_submit_button("Ask Sales")++ if sales_submitted and sales_input:+ with st.spinner("Processing sales inquiry..."):+ session = st.session_state.session_manager.get_session(sales_session_id, "contexts.db")+ result = asyncio.run(Runner.run(sales_agent, sales_input, session=session))+ st.write(f"**Sales:** {result.final_output}")++ with tab3:+ st.subheader("Shared Session Across Different Agents")+ st.caption("Customer handoff scenario - same conversation, different agents")++ shared_session_id = "customer_handoff"++ # Agent selector+ selected_agent = st.radio(+ "Select Agent:",+ ["Sales Agent", "Support Agent"],+ horizontal=True+ )++ agent = sales_agent if selected_agent == "Sales Agent" else support_agent++ with st.form("handoff_form"):+ handoff_input = st.text_input("Customer message:")+ handoff_submitted = st.form_submit_button(f"Send to {selected_agent}")++ if handoff_submitted and handoff_input:+ with st.spinner(f"Processing with {selected_agent}..."):+ session = st.session_state.session_manager.get_session(shared_session_id, "shared.db")+ result = asyncio.run(Runner.run(agent, handoff_input, session=session))+ st.write(f"**{selected_agent}:** {result.final_output}")++ # Show shared conversation history+ if st.button("π Show Shared Conversation"):+ items = asyncio.run(st.session_state.session_manager.get_session_items(shared_session_id))+ if items:+ st.write("**Shared Conversation History:**")+ for i, item in enumerate(items, 1):+ if item['role'] == 'user':+ st.write(f"{i}. π€ **Customer:** {item['content']}")+ else:+ # Try to determine which agent responded based on content+ agent_emoji = "π°" if "sales" in item['content'].lower() or "price" in item['content'].lower() else "π οΈ"+ st.write(f"{i}. {agent_emoji} **Agent:** {item['content']}")+ else:+ st.info("No conversation history yet.")++# Footer+def render_footer():+ st.divider()+ st.markdown("""+ ### π― Session Capabilities Demonstrated++ 1. **Basic Sessions**: In-memory vs persistent storage+ 2. **Memory Operations**: get_items(), add_items(), pop_item(), clear_session()+ 3. **Multi Sessions**: Multiple users, contexts, and agent handoffs++ **Key Benefits:**+ - Automatic conversation history management+ - Flexible session organization strategies+ - Memory manipulation for corrections and custom flows+ - Multi-agent conversation support+ """)++if __name__ == "__main__":+ main()+ render_footer()diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/README.mdnew file mode 100644index 00000000..8f430828--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/README.md@@ -0,0 +1,75 @@+# Basic Handoffs++Demonstrates fundamental agent-to-agent task delegation using the OpenAI Agents SDK handoff system.++## π― What This Demonstrates++- **Agent Handoffs**: Simple task delegation between specialized agents+- **Automatic Tool Creation**: Handoffs automatically create transfer tools+- **Triage Patterns**: Intelligent routing based on request type+- **Specialized Agents**: Different agents for billing and technical support++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import main++ # Test basic handoffs+ asyncio.run(main())+ ```++## π‘ Key Concepts++- **Handoff Definition**: Adding agents to the `handoffs` parameter+- **Tool Generation**: Automatic creation of `transfer_to_*` tools+- **Agent Specialization**: Different expertise areas for different agents+- **Intelligent Routing**: LLM decides which agent to transfer to++## π§ͺ Available Examples++### Billing Agent Handoff+- "I was charged twice for my subscription"+- "Can you help me get a refund?"+- "What are my payment options?"++### Technical Support Handoff+- "My app keeps crashing"+- "I can't upload photos"+- "The app won't load"++### No Handoff Needed+- "What are your customer service hours?"+- "How do I contact support?"+- "What services do you offer?"++## π» Agent Architecture++```python+# Specialized agents+billing_agent = Agent(name="Billing Agent", instructions="Handle billing issues")+technical_agent = Agent(name="Technical Support Agent", instructions="Handle technical issues")++# Triage agent with handoffs+triage_agent = Agent(+ name="Customer Service Triage Agent",+ handoffs=[billing_agent, technical_agent] # Creates tools automatically+)+```++## π Next Steps++- [Advanced Handoffs](../8_2_advanced_handoffs/README.md) - Custom configuration and callbacks+- [Tutorial 9: Multi-Agent Orchestration](../../9_multi_agent_orchestration/README.md) - Complex workflowsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/__init__.pynew file mode 100644index 00000000..1d3547c5--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/__init__.py@@ -0,0 +1 @@+# Basic Handoffs module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/agent.pynew file mode 100644index 00000000..6d1912e7--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/agent.py@@ -0,0 +1,77 @@+from agents import Agent, Runner, handoff+from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX+import asyncio++# Create specialized agents+billing_agent = Agent(+ name="Billing Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You are a billing specialist. Help customers with:+ - Payment issues and billing questions+ - Subscription management and upgrades+ - Invoice and receipt requests+ - Refund processing++ Be helpful and provide specific billing assistance.+ """+)++technical_agent = Agent(+ name="Technical Support Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You are a technical support specialist. Help customers with:+ - App crashes and technical issues+ - Account access problems+ - Feature usage and troubleshooting+ - Bug reports and technical questions++ Provide clear technical guidance and solutions.+ """+)++# Create triage agent with handoffs+root_agent = Agent(+ name="Customer Service Triage Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You are a customer service triage agent. Your job is to:++ 1. Understand the customer's issue+ 2. Determine which specialist can best help them+ 3. Transfer them to the appropriate agent using handoff tools++ Available specialists:+ - Billing Agent: For payment, subscription, billing, and refund issues+ - Technical Support Agent: For app problems, technical issues, and troubleshooting++ If the issue is clearly billing-related, transfer to Billing Agent.+ If the issue is clearly technical, transfer to Technical Support Agent.+ If you can handle it yourself (general questions), do so.+ """,+ handoffs=[billing_agent, technical_agent] # Creates handoff tools automatically+)++# Example usage+async def main():+ print("π€ OpenAI Agents SDK - Basic Handoffs")+ print("=" * 50)++ # Test billing handoff+ print("=== Billing Handoff Example ===")+ result = await Runner.run(+ root_agent,+ "Hi, I was charged twice for my subscription this month. Can you help me get a refund?"+ )+ print(f"Response: {result.final_output}")++ # Test technical handoff+ print("\n=== Technical Support Handoff Example ===")+ result = await Runner.run(+ root_agent,+ "My app keeps crashing when I try to upload photos. This has been happening for 3 days."+ )+ print(f"Response: {result.final_output}")++ print("\nβ Basic handoffs tutorial complete!")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_1_basic_handoffs/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/README.mdnew file mode 100644index 00000000..7d7d639f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/README.md@@ -0,0 +1,92 @@+# Advanced Handoffs++Demonstrates advanced handoff configuration including callbacks, structured inputs, and custom tool naming.++## π― What This Demonstrates++- **Custom Handoff Configuration**: Using the `handoff()` function+- **Callback Functions**: Executing code when handoffs are triggered+- **Structured Input Data**: Passing specific data with handoffs+- **Tool Customization**: Custom tool names and descriptions++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import main++ # Test advanced handoffs+ asyncio.run(main())+ ```++## π‘ Key Concepts++- **handoff() Function**: Custom handoff configuration+- **Callback Execution**: on_handoff functions for tracking+- **Structured Input**: Pydantic models for handoff data+- **Tool Overrides**: Custom tool names and descriptions++## π§ͺ Advanced Features++### Escalation with Structured Data+```python+class EscalationData(BaseModel):+ reason: str+ priority: str+ customer_id: str++escalation_handoff = handoff(+ agent=escalation_agent,+ tool_name_override="escalate_to_manager",+ input_type=EscalationData+)+```++### Callback Functions+```python+async def on_escalation_handoff(ctx, input_data):+ print(f"π¨ ESCALATION: {input_data.reason}")+ # Log to monitoring system+ # Send notifications+ # Update tickets+```++### Custom Tool Configuration+- **tool_name_override**: Custom tool names+- **tool_description_override**: Custom tool descriptions+- **input_filter**: Control what context transfers+- **is_enabled**: Dynamic handoff enabling/disabling++## π» Advanced Patterns++### Escalation Handoff+- Angry customer scenarios+- High-value refund requests+- Complex technical issues++### Callback Integration+- Logging and monitoring+- Notification systems+- Metric tracking++### Input Filtering+- Context cleaning+- Sensitive data removal+- Conversation sanitization++## π Next Steps++- [Basic Handoffs](../8_1_basic_handoffs/README.md) - Handoff fundamentals+- [Tutorial 9: Multi-Agent Orchestration](../../9_multi_agent_orchestration/README.md) - Complex workflowsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/__init__.pynew file mode 100644index 00000000..ef5f5831--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/__init__.py@@ -0,0 +1 @@+# Advanced Handoffs module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/agent.pynew file mode 100644index 00000000..99d59279--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/agent.py@@ -0,0 +1,73 @@+from agents import Agent, Runner, handoff, RunContextWrapper+from agents.extensions import handoff_filters+from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX+from pydantic import BaseModel+import asyncio++# Define structured input for escalation handoff+class EscalationData(BaseModel):+ reason: str+ priority: str+ customer_id: str++# Create specialized agents+escalation_agent = Agent(+ name="Escalation Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You handle escalated customer issues. You have access to additional tools and authority+ to resolve complex problems that first-level support cannot handle.+ """+)++# Callback function for escalation tracking+async def on_escalation_handoff(ctx: RunContextWrapper[None], input_data: EscalationData):+ """Callback executed when escalation handoff is triggered"""+ print(f"π¨ ESCALATION ALERT:")+ print(f" Reason: {input_data.reason}")+ print(f" Priority: {input_data.priority}")+ print(f" Customer ID: {input_data.customer_id}")++# Create advanced handoff with custom configuration+escalation_handoff = handoff(+ agent=escalation_agent,+ tool_name_override="escalate_to_manager",+ tool_description_override="Escalate complex issues that require manager intervention",+ on_handoff=on_escalation_handoff,+ input_type=EscalationData # Structured input required+)++# Advanced triage agent+root_agent = Agent(+ name="Advanced Triage Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You are an advanced customer service agent with escalation capabilities.++ Handle most issues yourself, but use escalations for:+ - Angry customers or complex complaints+ - Issues requiring refunds > $100+ - Technical problems you cannot resolve++ When escalating, provide reason, priority (low/medium/high), and customer_id.+ """,+ handoffs=[escalation_handoff]+)++# Example usage+async def main():+ print("β‘ OpenAI Agents SDK - Advanced Handoffs")+ print("=" * 50)++ # Test escalation with structured input+ print("=== Escalation with Structured Input ===")+ result = await Runner.run(+ root_agent,+ """I am absolutely furious! Your service has been down for 3 days and I've lost thousands+ of dollars in business. I want a full refund of my annual subscription ($299) and+ compensation for my losses. My customer ID is CUST-789123."""+ )+ print(f"Response: {result.final_output}")++ print("\nβ Advanced handoffs tutorial complete!")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/8_2_advanced_handoffs/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/README.mdnew file mode 100644index 00000000..38b72c8a--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/README.md@@ -0,0 +1,178 @@+# π€ Tutorial 8: Handoffs & Delegation++Master agent-to-agent task delegation! This tutorial teaches you how to use the OpenAI Agents SDK's handoff system to create specialized agents that can intelligently delegate tasks to each other, building powerful multi-agent workflows.++## π― What You'll Learn++- **Agent Handoffs**: Delegating tasks between specialized agents+- **Handoff Configuration**: Custom tool names, descriptions, and callbacks+- **Input Filtering**: Controlling what context gets passed between agents+- **Triage Patterns**: Building intelligent routing and delegation systems++## π§ Core Concept: What Are Handoffs?++Handoffs enable **agent specialization and delegation** where agents can transfer tasks to other agents with specific expertise. Think of handoffs as a **smart routing system** that:++- Creates specialized agents for different domains (support, billing, technical)+- Allows intelligent task delegation based on user needs+- Maintains conversation context across agent transfers+- Provides custom routing logic and input filtering++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β HANDOFF WORKFLOW β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β USER REQUEST β+β β β+β βΌ β+β βββββββββββββββ 1. ANALYZE REQUEST β+β β TRIAGE β β+β β AGENT β 2. DECIDE DELEGATION β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 3. CALL HANDOFF TOOL β+β β HANDOFF β "transfer_to_billing_agent" β+β β TOOL β β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββ 4. TRANSFER CONTEXT β+β β BILLING β (with optional filtering) β+β β AGENT β β+β βββββββββββββββ 5. PROCESS REQUEST β+β β β+β βΌ β+β βββββββββββββββ 6. RETURN RESPONSE β+β β RESPONSE β β+β β TO USER β β+β βββββββββββββββ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Tutorial Overview++This tutorial demonstrates **key handoff patterns**:++### **1. Basic Handoffs** (`basic_handoffs.py`)+- Simple agent-to-agent delegation+- Customer support triage example+- Automatic tool creation from handoff definitions++### **2. Advanced Handoffs** (`advanced_handoffs.py`)+- Custom handoff configuration with callbacks+- Input filtering and context management+- Handoff with structured input data++## π Project Structure++```+8_handoffs_delegation/+βββ README.md # This file - concept explanation+βββ requirements.txt # Dependencies+βββ basic_handoffs.py # Simple agent handoffs (40 lines)+βββ advanced_handoffs.py # Advanced handoff patterns (50 lines)+βββ app.py # Streamlit handoff demo (optional)+βββ env.example # Environment variables template+```++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How to create agent handoffs for task delegation+- β Configuring handoff tools with custom names and descriptions+- β Using input filters to control context transfer+- β Building intelligent triage systems with multiple agents+- β When and how to use handoffs vs direct agent orchestration++## π Getting Started++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Install dependencies**:+ ```bash+ pip install -r requirements.txt+ ```++2. **Set up environment variables**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Test basic handoffs**:+ ```bash+ python basic_handoffs.py+ ```++4. **Try advanced patterns**:+ ```bash+ python advanced_handoffs.py+ ```++## π§ Key Handoff Patterns++### 1. **Basic Handoff Setup**+```python+from agents import Agent, handoff++billing_agent = Agent(name="Billing Agent")+support_agent = Agent(name="Support Agent")++triage_agent = Agent(+ name="Triage Agent",+ handoffs=[billing_agent, support_agent] # Creates tools automatically+)+```++### 2. **Custom Handoff Configuration**+```python+from agents import Agent, handoff++def on_handoff_callback(ctx):+ print(f"Handoff to {ctx.agent.name} initiated")++custom_handoff = handoff(+ agent=billing_agent,+ tool_name_override="escalate_to_billing",+ tool_description_override="Transfer complex billing issues",+ on_handoff=on_handoff_callback+)+```++### 3. **Input Filtering**+```python+from agents.extensions import handoff_filters++filtered_handoff = handoff(+ agent=support_agent,+ input_filter=handoff_filters.remove_all_tools # Clean context+)+```++## π‘ Handoff Design Best Practices++1. **Clear Specialization**: Each agent should have a distinct area of expertise+2. **Intelligent Routing**: Use descriptive tool names and instructions for LLM+3. **Context Management**: Consider what context should transfer between agents+4. **Callback Integration**: Use callbacks for logging, metrics, and workflows+5. **Input Validation**: Structure inputs when passing specific data++## π Next Steps++After completing this tutorial, you'll be ready for:+- **[Tutorial 9: Multi-Agent Orchestration](../9_multi_agent_orchestration/README.md)** - Complex multi-agent workflows with parallel execution+- **[Tutorial 10: Tracing & Observability](../10_tracing_observability/README.md)** - Monitoring and debugging+- **[Tutorial 11: Production Patterns](../11_production_patterns/README.md)** - Real-world deployment strategies++## π‘ Pro Tips++- **Start Simple**: Begin with basic handoffs, add complexity gradually+- **Clear Instructions**: Make agent roles and handoff triggers obvious+- **Test Routing**: Verify LLM chooses correct agents for different scenarios+- **Monitor Handoffs**: Use callbacks and tracing to track delegation patterns+- **Context Strategy**: Plan what information should transfer between agents\ No newline at end of filediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/advanced_handoffs.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/advanced_handoffs.pynew file mode 100644index 00000000..99d59279--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/advanced_handoffs.py@@ -0,0 +1,73 @@+from agents import Agent, Runner, handoff, RunContextWrapper+from agents.extensions import handoff_filters+from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX+from pydantic import BaseModel+import asyncio++# Define structured input for escalation handoff+class EscalationData(BaseModel):+ reason: str+ priority: str+ customer_id: str++# Create specialized agents+escalation_agent = Agent(+ name="Escalation Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You handle escalated customer issues. You have access to additional tools and authority+ to resolve complex problems that first-level support cannot handle.+ """+)++# Callback function for escalation tracking+async def on_escalation_handoff(ctx: RunContextWrapper[None], input_data: EscalationData):+ """Callback executed when escalation handoff is triggered"""+ print(f"π¨ ESCALATION ALERT:")+ print(f" Reason: {input_data.reason}")+ print(f" Priority: {input_data.priority}")+ print(f" Customer ID: {input_data.customer_id}")++# Create advanced handoff with custom configuration+escalation_handoff = handoff(+ agent=escalation_agent,+ tool_name_override="escalate_to_manager",+ tool_description_override="Escalate complex issues that require manager intervention",+ on_handoff=on_escalation_handoff,+ input_type=EscalationData # Structured input required+)++# Advanced triage agent+root_agent = Agent(+ name="Advanced Triage Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You are an advanced customer service agent with escalation capabilities.++ Handle most issues yourself, but use escalations for:+ - Angry customers or complex complaints+ - Issues requiring refunds > $100+ - Technical problems you cannot resolve++ When escalating, provide reason, priority (low/medium/high), and customer_id.+ """,+ handoffs=[escalation_handoff]+)++# Example usage+async def main():+ print("β‘ OpenAI Agents SDK - Advanced Handoffs")+ print("=" * 50)++ # Test escalation with structured input+ print("=== Escalation with Structured Input ===")+ result = await Runner.run(+ root_agent,+ """I am absolutely furious! Your service has been down for 3 days and I've lost thousands+ of dollars in business. I want a full refund of my annual subscription ($299) and+ compensation for my losses. My customer ID is CUST-789123."""+ )+ print(f"Response: {result.final_output}")++ print("\nβ Advanced handoffs tutorial complete!")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/basic_handoffs.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/basic_handoffs.pynew file mode 100644index 00000000..6d1912e7--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/basic_handoffs.py@@ -0,0 +1,77 @@+from agents import Agent, Runner, handoff+from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX+import asyncio++# Create specialized agents+billing_agent = Agent(+ name="Billing Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You are a billing specialist. Help customers with:+ - Payment issues and billing questions+ - Subscription management and upgrades+ - Invoice and receipt requests+ - Refund processing++ Be helpful and provide specific billing assistance.+ """+)++technical_agent = Agent(+ name="Technical Support Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You are a technical support specialist. Help customers with:+ - App crashes and technical issues+ - Account access problems+ - Feature usage and troubleshooting+ - Bug reports and technical questions++ Provide clear technical guidance and solutions.+ """+)++# Create triage agent with handoffs+root_agent = Agent(+ name="Customer Service Triage Agent",+ instructions=f"""{RECOMMENDED_PROMPT_PREFIX}+ You are a customer service triage agent. Your job is to:++ 1. Understand the customer's issue+ 2. Determine which specialist can best help them+ 3. Transfer them to the appropriate agent using handoff tools++ Available specialists:+ - Billing Agent: For payment, subscription, billing, and refund issues+ - Technical Support Agent: For app problems, technical issues, and troubleshooting++ If the issue is clearly billing-related, transfer to Billing Agent.+ If the issue is clearly technical, transfer to Technical Support Agent.+ If you can handle it yourself (general questions), do so.+ """,+ handoffs=[billing_agent, technical_agent] # Creates handoff tools automatically+)++# Example usage+async def main():+ print("π€ OpenAI Agents SDK - Basic Handoffs")+ print("=" * 50)++ # Test billing handoff+ print("=== Billing Handoff Example ===")+ result = await Runner.run(+ root_agent,+ "Hi, I was charged twice for my subscription this month. Can you help me get a refund?"+ )+ print(f"Response: {result.final_output}")++ # Test technical handoff+ print("\n=== Technical Support Handoff Example ===")+ result = await Runner.run(+ root_agent,+ "My app keeps crashing when I try to upload photos. This has been happening for 3 days."+ )+ print(f"Response: {result.final_output}")++ print("\nβ Basic handoffs tutorial complete!")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/requirements.txtnew file mode 100644index 00000000..41a538fd--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/8_handoffs_delegation/requirements.txt@@ -0,0 +1,4 @@+openai-agents>=1.0.0+streamlit>=1.28.0+python-dotenv>=1.0.0+pydantic>=2.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/README.mdnew file mode 100644index 00000000..b46fb968--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/README.md@@ -0,0 +1,88 @@+# Parallel Execution++Demonstrates running multiple agents simultaneously using `asyncio.gather()` for improved performance and quality through diversity.++## π― What This Demonstrates++- **Parallel Agent Execution**: Running multiple agents simultaneously+- **Quality Selection**: Choosing the best result from multiple attempts+- **Translation Orchestration**: Multiple language approaches+- **Content Generation Diversity**: Different writing styles in parallel++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import main++ # Test parallel execution patterns+ asyncio.run(main())+ ```++## π‘ Key Concepts++- **asyncio.gather()**: Running multiple agents concurrently+- **ItemHelpers**: Extracting text outputs from results+- **Quality Assessment**: Using picker agents to select best results+- **Trace Grouping**: Organizing parallel workflows in single traces++## π§ͺ Available Examples++### Parallel Translation with Quality Selection+```python+with trace("Parallel translation"):+ res_1, res_2, res_3 = await asyncio.gather(+ Runner.run(spanish_agent, msg),+ Runner.run(spanish_agent, msg),+ Runner.run(spanish_agent, msg),+ )++ best_translation = await Runner.run(+ translation_picker,+ f"Input: {msg}\n\nTranslations:\n{translations}"+ )+```++### Multi-Style Translation+- **Formal Spanish**: Using 'usted' forms+- **Casual Spanish**: Using 'tΓΊ' forms+- **Regional Spanish**: Mexican expressions++### Content Generation Diversity+- **Creative Writing**: Vivid imagery and storytelling+- **Informative Writing**: Clear, factual content+- **Persuasive Writing**: Compelling, action-oriented++## π» Parallel Patterns++### Quality Through Repetition+- Run same agent multiple times+- Compare results for consistency+- Select highest quality output++### Quality Through Specialization+- Different agents for different approaches+- Specialized expertise areas+- Diverse perspective synthesis++### Performance Optimization+- Concurrent execution vs sequential+- Reduced total response time+- Better resource utilization++## π Next Steps++- [Agents as Tools](../9_2_agents_as_tools/README.md) - Agent orchestration patterns+- [Tutorial 10: Tracing & Observability](../../10_tracing_observability/README.md) - Monitoring workflowsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/__init__.pynew file mode 100644index 00000000..54438b33--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/__init__.py@@ -0,0 +1 @@+# Parallel Execution module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/agent.pynew file mode 100644index 00000000..18affd5f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/agent.py@@ -0,0 +1,208 @@+import asyncio+from agents import Agent, ItemHelpers, Runner, trace++# Create specialized translation agent+spanish_agent = Agent(+ name="Spanish Translator",+ instructions="You translate the user's message to Spanish. Provide natural, fluent translations."+)++# Create translation quality picker+translation_picker = Agent(+ name="Translation Quality Picker",+ instructions="""+ You are an expert in Spanish translations.+ Given multiple Spanish translation options, pick the most natural, accurate, and fluent one.+ Explain briefly why you chose that translation.+ """+)++# Example 1: Basic parallel execution with quality selection+async def parallel_translation_example():+ """Demonstrates running the same agent multiple times in parallel for quality"""++ print("=== Parallel Translation with Quality Selection ===")++ msg = "Hello, how are you today? I hope you're having a wonderful time!"+ print(f"Original message: {msg}")++ # Ensure the entire workflow is a single trace+ with trace("Parallel Translation Workflow") as workflow_trace:+ print("Running 3 parallel translation attempts...")++ # Run 3 parallel translations+ res_1, res_2, res_3 = await asyncio.gather(+ Runner.run(spanish_agent, msg),+ Runner.run(spanish_agent, msg),+ Runner.run(spanish_agent, msg)+ )++ # Extract text outputs from results+ outputs = [+ ItemHelpers.text_message_outputs(res_1.new_items),+ ItemHelpers.text_message_outputs(res_2.new_items),+ ItemHelpers.text_message_outputs(res_3.new_items)+ ]++ # Combine all translations for comparison+ translations = "\n\n".join([f"Translation {i+1}: {output}" for i, output in enumerate(outputs)])+ print(f"\nAll translations:\n{translations}")++ # Use picker agent to select best translation+ best_translation = await Runner.run(+ translation_picker,+ f"Original English: {msg}\n\nTranslations to choose from:\n{translations}"+ )++ print(f"\nBest translation selected: {best_translation.final_output}")+ print(f"Workflow trace ID: {workflow_trace.trace_id}")++ return best_translation++# Example 2: Parallel execution with different specialized agents+async def parallel_specialized_agents():+ """Shows parallel execution with different agents for diverse perspectives"""++ print("\n=== Parallel Execution with Specialized Agents ===")++ # Create different specialized agents+ formal_translator = Agent(+ name="Formal Spanish Translator",+ instructions="Translate to formal, polite Spanish using 'usted' forms."+ )++ casual_translator = Agent(+ name="Casual Spanish Translator",+ instructions="Translate to casual, friendly Spanish using 'tΓΊ' forms."+ )++ regional_translator = Agent(+ name="Mexican Spanish Translator",+ instructions="Translate to Mexican Spanish with regional expressions and vocabulary."+ )++ msg = "Hey friend, want to grab some coffee later?"+ print(f"Original message: {msg}")++ with trace("Multi-Style Translation") as style_trace:+ print("Running parallel translations with different styles...")++ # Run different translation styles in parallel+ formal_result, casual_result, regional_result = await asyncio.gather(+ Runner.run(formal_translator, msg),+ Runner.run(casual_translator, msg),+ Runner.run(regional_translator, msg)+ )++ # Extract and display all results+ formal_text = ItemHelpers.text_message_outputs(formal_result.new_items)+ casual_text = ItemHelpers.text_message_outputs(casual_result.new_items)+ regional_text = ItemHelpers.text_message_outputs(regional_result.new_items)++ print(f"\nFormal style: {formal_text}")+ print(f"Casual style: {casual_text}")+ print(f"Regional style: {regional_text}")++ # Let user choose preferred style+ style_comparison = f"""+ Original: {msg}++ Formal Spanish: {formal_text}+ Casual Spanish: {casual_text}+ Mexican Spanish: {regional_text}+ """++ style_recommendation = await Runner.run(+ translation_picker,+ f"Compare these translation styles and recommend which is most appropriate for the context: {style_comparison}"+ )++ print(f"\nStyle recommendation: {style_recommendation.final_output}")+ print(f"Multi-style trace ID: {style_trace.trace_id}")++ return style_recommendation++# Example 3: Parallel execution for content generation diversity+async def parallel_content_generation():+ """Demonstrates parallel content generation for creative diversity"""++ print("\n=== Parallel Content Generation for Diversity ===")++ # Create content generation agents with different approaches+ creative_agent = Agent(+ name="Creative Writer",+ instructions="Write creative, engaging content with vivid imagery and storytelling."+ )++ informative_agent = Agent(+ name="Informative Writer",+ instructions="Write clear, factual, informative content focused on key information."+ )++ persuasive_agent = Agent(+ name="Persuasive Writer",+ instructions="Write compelling, persuasive content that motivates action."+ )++ topic = "The benefits of learning a new language"+ print(f"Content topic: {topic}")++ with trace("Diverse Content Generation") as content_trace:+ print("Generating content with different writing styles in parallel...")++ # Generate different content approaches simultaneously+ creative_result, informative_result, persuasive_result = await asyncio.gather(+ Runner.run(creative_agent, f"Write a short paragraph about: {topic}"),+ Runner.run(informative_agent, f"Write a short paragraph about: {topic}"),+ Runner.run(persuasive_agent, f"Write a short paragraph about: {topic}")+ )++ # Extract content+ creative_content = ItemHelpers.text_message_outputs(creative_result.new_items)+ informative_content = ItemHelpers.text_message_outputs(informative_result.new_items)+ persuasive_content = ItemHelpers.text_message_outputs(persuasive_result.new_items)++ print(f"\nCreative approach:\n{creative_content}")+ print(f"\nInformative approach:\n{informative_content}")+ print(f"\nPersuasive approach:\n{persuasive_content}")++ # Synthesize best elements from all approaches+ synthesis_agent = Agent(+ name="Content Synthesizer",+ instructions="Combine the best elements from multiple content pieces into one cohesive, high-quality paragraph."+ )++ combined_content = f"""+ Topic: {topic}++ Creative version: {creative_content}++ Informative version: {informative_content}++ Persuasive version: {persuasive_content}+ """++ synthesized_result = await Runner.run(+ synthesis_agent,+ f"Create the best possible paragraph by combining elements from these approaches: {combined_content}"+ )++ print(f"\nSynthesized content: {synthesized_result.final_output}")+ print(f"Content generation trace ID: {content_trace.trace_id}")++ return synthesized_result++# Main execution+async def main():+ print("πΌ OpenAI Agents SDK - Parallel Multi-Agent Execution")+ print("=" * 60)++ await parallel_translation_example()+ await parallel_specialized_agents()+ await parallel_content_generation()++ print("\nβ Parallel execution tutorial complete!")+ print("Parallel execution enables quality improvement through diversity and selection")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_1_parallel_execution/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/README.mdnew file mode 100644index 00000000..5088fa75--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/README.md@@ -0,0 +1,95 @@+# Agents as Tools++Demonstrates advanced orchestration patterns where specialized agents are used as function tools by orchestrator agents.++## π― What This Demonstrates++- **@function_tool with Agents**: Converting agents to reusable tools+- **Content Creation Pipeline**: Research β Writing β Editing workflow+- **Custom Configuration**: Per-agent settings and parameters+- **Intelligent Orchestration**: LLM-driven workflow coordination++## π Quick Start++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Set up environment**:+ ```bash+ cp ../env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Run the agent**:+ ```python+ import asyncio+ from agent import main++ # Test agent orchestration patterns+ asyncio.run(main())+ ```++## π‘ Key Concepts++- **Agent Tool Creation**: Using `@function_tool` with `Runner.run()`+- **Workflow Orchestration**: Coordinating multiple specialized agents+- **Custom Configuration**: Per-tool settings (max_turns, temperature)+- **Intelligent Coordination**: LLM decides when and how to use tools++## π§ͺ Available Tools++### Research Tool+```python+@function_tool+async def research_tool(topic: str) -> str:+ result = await Runner.run(+ research_agent,+ input=f"Research this topic thoroughly: {topic}",+ max_turns=3+ )+ return str(result.final_output)+```++### Writing Tool+```python+@function_tool+async def writing_tool(content: str, style: str = "professional") -> str:+ prompt = f"Write engaging {style} content based on this research: {content}"+ result = await Runner.run(writing_agent, input=prompt, max_turns=2)+ return str(result.final_output)+```++### Editing Tool+```python+@function_tool+async def editing_tool(content: str) -> str:+ result = await Runner.run(+ editing_agent,+ input=f"Edit and improve this content: {content}"+ )+ return str(result.final_output)+```++## π» Orchestration Patterns++### Basic Content Workflow+1. **Research**: Gather comprehensive information+2. **Write**: Create well-structured content+3. **Edit**: Polish and improve final output++### Advanced Orchestration+- **Conditional Logic**: Adapt workflow based on requirements+- **Style Selection**: Choose appropriate writing approach+- **Quality Control**: Multi-stage review and improvement++### Manual vs Automatic Comparison+- **Direct Agent Calls**: Manual orchestration+- **Tool-Based**: Automatic LLM coordination+- **Performance**: Compare execution patterns++## π Next Steps++- [Parallel Execution](../9_1_parallel_execution/README.md) - Concurrent agent patterns+- [Tutorial 10: Tracing & Observability](../../10_tracing_observability/README.md) - Monitoring workflowsdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/__init__.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/__init__.pynew file mode 100644index 00000000..4880429a--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/__init__.py@@ -0,0 +1 @@+# Agents as Tools module for OpenAI Agents SDK tutorialdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/agent.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/agent.pynew file mode 100644index 00000000..e527b489--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/agent.py@@ -0,0 +1,233 @@+from agents import Agent, Runner, function_tool+import asyncio++# Define specialized research agent+research_agent = Agent(+ name="Research Specialist",+ instructions="""+ You are a research specialist. Provide detailed, well-researched information+ on any topic with proper analysis and insights. Focus on factual accuracy+ and comprehensive coverage.+ """+)++# Define specialized writing agent+writing_agent = Agent(+ name="Writing Specialist",+ instructions="""+ You are a professional writer. Take research information and create+ well-structured, engaging content with proper formatting and flow.+ Make content accessible and compelling for readers.+ """+)++# Define editing agent+editing_agent = Agent(+ name="Editing Specialist",+ instructions="""+ You are a professional editor. Review written content for:+ - Grammar and spelling errors+ - Clarity and readability+ - Structure and flow+ - Consistency and tone++ Provide the improved version of the content.+ """+)++# Create function tools from agents+@function_tool+async def research_tool(topic: str) -> str:+ """Research a topic using the specialized research agent with custom configuration"""++ result = await Runner.run(+ research_agent,+ input=f"Research this topic thoroughly and provide key insights: {topic}",+ max_turns=3 # Allow deeper research+ )++ return str(result.final_output)++@function_tool+async def writing_tool(content: str, style: str = "professional") -> str:+ """Transform content using the specialized writing agent with custom style"""++ prompt = f"Write engaging {style} content based on this research: {content}"++ result = await Runner.run(+ writing_agent,+ input=prompt,+ max_turns=2+ )++ return str(result.final_output)++@function_tool+async def editing_tool(content: str) -> str:+ """Edit and improve content using the specialized editing agent"""++ result = await Runner.run(+ editing_agent,+ input=f"Edit and improve this content for clarity, grammar, and engagement: {content}"+ )++ return str(result.final_output)++# Create orchestrator agent that uses other agents as tools+content_orchestrator = Agent(+ name="Content Creation Orchestrator",+ instructions="""+ You are a content creation orchestrator that coordinates research, writing, and editing.++ You have access to:+ - research_tool: For in-depth topic research and insights+ - writing_tool: For professional content creation (specify style: professional, casual, academic, etc.)+ - editing_tool: For content review and improvement++ When users request content:+ 1. First use research_tool to gather comprehensive information+ 2. Then use writing_tool to create well-structured content+ 3. Finally use editing_tool to polish and improve the final piece++ Coordinate all three tools to create high-quality, well-researched content.+ """,+ tools=[research_tool, writing_tool, editing_tool]+)++# Example 1: Basic content creation workflow+async def basic_content_workflow():+ """Demonstrates basic orchestration using agents as tools"""++ print("=== Basic Content Creation Workflow ===")++ result = await Runner.run(+ content_orchestrator,+ """Create a comprehensive article about the benefits of renewable energy.+ I need it to be professional and well-researched, suitable for a business audience."""+ )++ print(f"Final article: {result.final_output}")++ return result++# Example 2: Custom workflow with specific requirements+async def custom_workflow_example():+ """Shows orchestrator handling specific workflow requirements"""++ print("\n=== Custom Workflow with Specific Requirements ===")++ result = await Runner.run(+ content_orchestrator,+ """I need content about artificial intelligence in healthcare for a technical blog.+ Make sure to:+ 1. Research current AI applications in medical diagnosis+ 2. Write in an accessible but technical style+ 3. Include both benefits and challenges+ 4. Keep it under 500 words++ Please go through the full research -> write -> edit process."""+ )++ print(f"Technical blog post: {result.final_output}")++ return result++# Example 3: Comparison with direct agent orchestration+async def direct_orchestration_comparison():+ """Compares agents-as-tools vs direct orchestration"""++ print("\n=== Direct Orchestration (Manual) ===")+ topic = "The future of remote work"++ # Manual orchestration - calling agents directly+ print("Step 1: Research...")+ research_result = await Runner.run(+ research_agent,+ f"Research trends and predictions about: {topic}"+ )++ print("Step 2: Writing...")+ writing_result = await Runner.run(+ writing_agent,+ f"Write a professional article based on this research: {research_result.final_output}"+ )++ print("Step 3: Editing...")+ editing_result = await Runner.run(+ editing_agent,+ f"Edit and improve this article: {writing_result.final_output}"+ )++ print(f"Manual orchestration result: {editing_result.final_output}")++ print("\n=== Agents-as-Tools Orchestration (Automatic) ===")++ # Automatic orchestration using orchestrator agent+ orchestrated_result = await Runner.run(+ content_orchestrator,+ f"Create a professional article about: {topic}. Go through research, writing, and editing."+ )++ print(f"Automatic orchestration result: {orchestrated_result.final_output}")++ return editing_result, orchestrated_result++# Example 4: Advanced orchestrator with conditional logic+async def advanced_orchestrator_example():+ """Shows more sophisticated orchestration logic"""++ print("\n=== Advanced Orchestrator with Conditional Logic ===")++ # Create advanced orchestrator with conditional workflows+ advanced_orchestrator = Agent(+ name="Advanced Content Orchestrator",+ instructions="""+ You are an intelligent content orchestrator that adapts workflows based on requirements.++ Available tools:+ - research_tool: For topic research+ - writing_tool: For content creation (styles: professional, casual, academic, creative)+ - editing_tool: For content improvement++ Workflow decisions:+ - For complex/technical topics: Do extra research first+ - For creative content: Use creative writing style+ - For short content: Skip detailed research+ - For business content: Always edit for professionalism+ - Always explain your workflow decisions++ Adapt your approach based on the specific request.+ """,+ tools=[research_tool, writing_tool, editing_tool]+ )++ # Test with different content types+ requests = [+ "Write a quick social media post about coffee benefits",+ "Create a detailed technical whitepaper on blockchain security",+ "Write a creative story about a robot learning to paint"+ ]++ for i, request in enumerate(requests, 1):+ print(f"\nRequest {i}: {request}")+ result = await Runner.run(advanced_orchestrator, request)+ print(f"Result: {result.final_output}")+ print("-" * 50)++ return requests++# Main execution+async def main():+ print("π§ OpenAI Agents SDK - Agents as Tools Orchestration")+ print("=" * 60)++ await basic_content_workflow()+ await custom_workflow_example()+ await direct_orchestration_comparison()+ await advanced_orchestrator_example()++ print("\nβ Agents as tools tutorial complete!")+ print("Agents as tools enable sophisticated workflow orchestration with intelligent coordination")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/9_2_agents_as_tools/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/README.mdnew file mode 100644index 00000000..e934ca21--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/README.md@@ -0,0 +1,232 @@+# πΌ Tutorial 9: Multi-Agent Orchestration++Master complex multi-agent workflows! This tutorial teaches you how to coordinate multiple agents using parallel execution, agents-as-tools patterns, and advanced orchestration techniques for building sophisticated AI systems.++## π― What You'll Learn++- **Parallel Execution**: Running multiple agents simultaneously with `asyncio.gather()`+- **Agents as Tools**: Using agents as function tools for complex orchestration+- **Workflow Coordination**: Sequential and parallel agent processing patterns+- **Result Synthesis**: Combining outputs from multiple agents intelligently++## π§ Core Concept: What Is Multi-Agent Orchestration?++Multi-agent orchestration enables **coordinated AI workflows** where multiple specialized agents work together to solve complex problems. Think of orchestration as a **conductor leading an orchestra** where:++- Different agents have specialized roles and expertise+- Agents can work in parallel or sequence based on workflow needs+- Results from multiple agents are synthesized intelligently+- Complex tasks are broken down across multiple AI capabilities++```+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β MULTI-AGENT ORCHESTRATION β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β COMPLEX TASK β+β β β+β βΌ β+β βββββββββββββββ 1. TASK DECOMPOSITION β+β βORCHESTRATOR β β+β β AGENT β 2. AGENT COORDINATION β+β βββββββββββββββ β+β β β+β βΌ β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β PARALLEL EXECUTION β β+β β βββββββββββ βββββββββββ βββββββββββ βββββββββββ β β+β β βRESEARCH β βWRITING β βANALYSIS β βREVIEW β β β+β β β AGENT β β AGENT β β AGENT β β AGENT β β β+β β βββββββββββ βββββββββββ βββββββββββ βββββββββββ β β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β β β β β+β βΌ βΌ βΌ βΌ β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β RESULT SYNTHESIS β β+β β β’ Combine outputs intelligently β β+β β β’ Quality assessment and selection β β+β β β’ Final coordinated response β β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## π Tutorial Overview++This tutorial demonstrates **three key orchestration patterns**:++### **1. Parallel Agent Execution** (`parallel_execution.py`)+- Running multiple agents simultaneously with `asyncio.gather()`+- Quality assessment and best result selection+- Translation example with multiple attempts++### **2. Agents as Tools Orchestration** (`agents_as_tools.py`)+- Using specialized agents as function tools+- Content creation workflow with research and writing agents+- Custom agent tool configuration and coordination++### **3. Complex Workflow Orchestration** (`complex_orchestration.py`)+- Multi-stage workflows combining parallel and sequential execution+- Content pipeline with research, writing, review, and optimization+- Advanced result synthesis and quality control++## π Project Structure++```+9_multi_agent_orchestration/+βββ README.md # This file - concept explanation+βββ requirements.txt # Dependencies+βββ parallel_execution.py # Parallel agent patterns (45 lines)+βββ agents_as_tools.py # Agents as tools orchestration (55 lines)+βββ complex_orchestration.py # Advanced workflow patterns (70 lines)+βββ app.py # Streamlit orchestration demo (optional)+βββ env.example # Environment variables template+```++## π― Learning Objectives++By the end of this tutorial, you'll understand:+- β How to run multiple agents in parallel for improved performance+- β Using agents as function tools for complex orchestration+- β Combining sequential and parallel execution patterns+- β Synthesizing results from multiple agents intelligently+- β When to use different orchestration patterns for various use cases++## π Getting Started++1. **Install OpenAI Agents SDK**:+ ```bash+ pip install openai-agents+ ```++2. **Install dependencies**:+ ```bash+ pip install -r requirements.txt+ ```++2. **Set up environment variables**:+ ```bash+ cp env.example .env+ # Edit .env and add your OpenAI API key+ ```++3. **Test parallel execution**:+ ```bash+ python parallel_execution.py+ ```++4. **Try agents as tools**:+ ```bash+ python agents_as_tools.py+ ```++5. **Explore complex workflows**:+ ```bash+ python complex_orchestration.py+ ```++## π§ͺ Sample Use Cases++### Parallel Execution+- Multiple translation attempts with quality selection+- Content generation with diversity and choice+- Research from multiple perspectives simultaneously++### Agents as Tools+- Content creation: research β writing β editing pipeline+- Analysis workflows: data processing β insights β recommendations+- Customer service: triage β specialist β quality assurance++### Complex Orchestration+- Multi-stage content production with feedback loops+- Research and development workflows with validation+- Educational content creation with multiple review stages++## π§ Key Orchestration Patterns++### 1. **Parallel Execution with Quality Selection**+```python+import asyncio+from agents import Agent, Runner, trace++# Run multiple agents in parallel+with trace("Parallel translation"):+ results = await asyncio.gather(+ Runner.run(translator_agent, message),+ Runner.run(translator_agent, message),+ Runner.run(translator_agent, message)+ )++ # Select best result+ best = await Runner.run(selector_agent, combined_results)+```++### 2. **Agents as Function Tools**+```python+from agents import Agent, function_tool++@function_tool+async def research_tool(topic: str) -> str:+ result = await Runner.run(research_agent, f"Research: {topic}")+ return str(result.final_output)++orchestrator = Agent(+ name="Content Orchestrator",+ tools=[research_tool, writing_tool]+)+```++### 3. **Sequential + Parallel Hybrid**+```python+# Sequential stages with parallel execution within stages+with trace("Content Creation Pipeline"):+ # Stage 1: Parallel research+ research_results = await asyncio.gather(+ research_agent_1.run(topic),+ research_agent_2.run(topic)+ )++ # Stage 2: Sequential writing+ content = await writing_agent.run(combined_research)++ # Stage 3: Parallel review+ reviews = await asyncio.gather(+ quality_agent.run(content),+ style_agent.run(content)+ )+```++## π‘ Orchestration Design Best Practices++1. **Task Decomposition**: Break complex tasks into agent-sized pieces+2. **Parallel Optimization**: Use parallel execution where agents are independent+3. **Quality Control**: Include review and selection mechanisms+4. **Error Handling**: Plan for agent failures and provide fallbacks+5. **Result Synthesis**: Design intelligent combination of multiple outputs++## π¨ Important Notes++- **Tracing Integration**: Use `trace()` to group multi-agent workflows+- **Resource Management**: Consider API rate limits with parallel execution+- **Quality vs Speed**: Balance parallelization with result quality+- **Error Propagation**: Handle failures gracefully in complex workflows++## π Next Steps++After completing this tutorial, you'll be ready for:+- **[Tutorial 10: Tracing & Observability](../10_tracing_observability/README.md)** - Monitoring complex workflows+- **[Tutorial 11: Production Patterns](../11_production_patterns/README.md)** - Real-world deployment strategies++## π¨ Troubleshooting++- **Performance Issues**: Check for unnecessary sequential execution+- **Quality Problems**: Improve result synthesis and selection logic+- **Rate Limiting**: Implement backoff and retry for parallel calls+- **Memory Usage**: Monitor resource consumption with many parallel agents++## π‘ Pro Tips++- **Start Simple**: Begin with basic parallel execution, add complexity gradually+- **Measure Performance**: Compare parallel vs sequential execution times+- **Quality Metrics**: Develop criteria for selecting best results from multiple agents+- **Workflow Visualization**: Use tracing to understand complex execution flows+- **Agent Specialization**: Design agents with clear, focused responsibilitiesdiff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/agents_as_tools.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/agents_as_tools.pynew file mode 100644index 00000000..e527b489--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/agents_as_tools.py@@ -0,0 +1,233 @@+from agents import Agent, Runner, function_tool+import asyncio++# Define specialized research agent+research_agent = Agent(+ name="Research Specialist",+ instructions="""+ You are a research specialist. Provide detailed, well-researched information+ on any topic with proper analysis and insights. Focus on factual accuracy+ and comprehensive coverage.+ """+)++# Define specialized writing agent+writing_agent = Agent(+ name="Writing Specialist",+ instructions="""+ You are a professional writer. Take research information and create+ well-structured, engaging content with proper formatting and flow.+ Make content accessible and compelling for readers.+ """+)++# Define editing agent+editing_agent = Agent(+ name="Editing Specialist",+ instructions="""+ You are a professional editor. Review written content for:+ - Grammar and spelling errors+ - Clarity and readability+ - Structure and flow+ - Consistency and tone++ Provide the improved version of the content.+ """+)++# Create function tools from agents+@function_tool+async def research_tool(topic: str) -> str:+ """Research a topic using the specialized research agent with custom configuration"""++ result = await Runner.run(+ research_agent,+ input=f"Research this topic thoroughly and provide key insights: {topic}",+ max_turns=3 # Allow deeper research+ )++ return str(result.final_output)++@function_tool+async def writing_tool(content: str, style: str = "professional") -> str:+ """Transform content using the specialized writing agent with custom style"""++ prompt = f"Write engaging {style} content based on this research: {content}"++ result = await Runner.run(+ writing_agent,+ input=prompt,+ max_turns=2+ )++ return str(result.final_output)++@function_tool+async def editing_tool(content: str) -> str:+ """Edit and improve content using the specialized editing agent"""++ result = await Runner.run(+ editing_agent,+ input=f"Edit and improve this content for clarity, grammar, and engagement: {content}"+ )++ return str(result.final_output)++# Create orchestrator agent that uses other agents as tools+content_orchestrator = Agent(+ name="Content Creation Orchestrator",+ instructions="""+ You are a content creation orchestrator that coordinates research, writing, and editing.++ You have access to:+ - research_tool: For in-depth topic research and insights+ - writing_tool: For professional content creation (specify style: professional, casual, academic, etc.)+ - editing_tool: For content review and improvement++ When users request content:+ 1. First use research_tool to gather comprehensive information+ 2. Then use writing_tool to create well-structured content+ 3. Finally use editing_tool to polish and improve the final piece++ Coordinate all three tools to create high-quality, well-researched content.+ """,+ tools=[research_tool, writing_tool, editing_tool]+)++# Example 1: Basic content creation workflow+async def basic_content_workflow():+ """Demonstrates basic orchestration using agents as tools"""++ print("=== Basic Content Creation Workflow ===")++ result = await Runner.run(+ content_orchestrator,+ """Create a comprehensive article about the benefits of renewable energy.+ I need it to be professional and well-researched, suitable for a business audience."""+ )++ print(f"Final article: {result.final_output}")++ return result++# Example 2: Custom workflow with specific requirements+async def custom_workflow_example():+ """Shows orchestrator handling specific workflow requirements"""++ print("\n=== Custom Workflow with Specific Requirements ===")++ result = await Runner.run(+ content_orchestrator,+ """I need content about artificial intelligence in healthcare for a technical blog.+ Make sure to:+ 1. Research current AI applications in medical diagnosis+ 2. Write in an accessible but technical style+ 3. Include both benefits and challenges+ 4. Keep it under 500 words++ Please go through the full research -> write -> edit process."""+ )++ print(f"Technical blog post: {result.final_output}")++ return result++# Example 3: Comparison with direct agent orchestration+async def direct_orchestration_comparison():+ """Compares agents-as-tools vs direct orchestration"""++ print("\n=== Direct Orchestration (Manual) ===")+ topic = "The future of remote work"++ # Manual orchestration - calling agents directly+ print("Step 1: Research...")+ research_result = await Runner.run(+ research_agent,+ f"Research trends and predictions about: {topic}"+ )++ print("Step 2: Writing...")+ writing_result = await Runner.run(+ writing_agent,+ f"Write a professional article based on this research: {research_result.final_output}"+ )++ print("Step 3: Editing...")+ editing_result = await Runner.run(+ editing_agent,+ f"Edit and improve this article: {writing_result.final_output}"+ )++ print(f"Manual orchestration result: {editing_result.final_output}")++ print("\n=== Agents-as-Tools Orchestration (Automatic) ===")++ # Automatic orchestration using orchestrator agent+ orchestrated_result = await Runner.run(+ content_orchestrator,+ f"Create a professional article about: {topic}. Go through research, writing, and editing."+ )++ print(f"Automatic orchestration result: {orchestrated_result.final_output}")++ return editing_result, orchestrated_result++# Example 4: Advanced orchestrator with conditional logic+async def advanced_orchestrator_example():+ """Shows more sophisticated orchestration logic"""++ print("\n=== Advanced Orchestrator with Conditional Logic ===")++ # Create advanced orchestrator with conditional workflows+ advanced_orchestrator = Agent(+ name="Advanced Content Orchestrator",+ instructions="""+ You are an intelligent content orchestrator that adapts workflows based on requirements.++ Available tools:+ - research_tool: For topic research+ - writing_tool: For content creation (styles: professional, casual, academic, creative)+ - editing_tool: For content improvement++ Workflow decisions:+ - For complex/technical topics: Do extra research first+ - For creative content: Use creative writing style+ - For short content: Skip detailed research+ - For business content: Always edit for professionalism+ - Always explain your workflow decisions++ Adapt your approach based on the specific request.+ """,+ tools=[research_tool, writing_tool, editing_tool]+ )++ # Test with different content types+ requests = [+ "Write a quick social media post about coffee benefits",+ "Create a detailed technical whitepaper on blockchain security",+ "Write a creative story about a robot learning to paint"+ ]++ for i, request in enumerate(requests, 1):+ print(f"\nRequest {i}: {request}")+ result = await Runner.run(advanced_orchestrator, request)+ print(f"Result: {result.final_output}")+ print("-" * 50)++ return requests++# Main execution+async def main():+ print("π§ OpenAI Agents SDK - Agents as Tools Orchestration")+ print("=" * 60)++ await basic_content_workflow()+ await custom_workflow_example()+ await direct_orchestration_comparison()+ await advanced_orchestrator_example()++ print("\nβ Agents as tools tutorial complete!")+ print("Agents as tools enable sophisticated workflow orchestration with intelligent coordination")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/env.example b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/env.examplenew file mode 100644index 00000000..3cac181d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/env.example@@ -0,0 +1 @@+OPENAI_API_KEY=your_openai_api_key_herediff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/parallel_execution.py b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/parallel_execution.pynew file mode 100644index 00000000..18affd5f--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/parallel_execution.py@@ -0,0 +1,208 @@+import asyncio+from agents import Agent, ItemHelpers, Runner, trace++# Create specialized translation agent+spanish_agent = Agent(+ name="Spanish Translator",+ instructions="You translate the user's message to Spanish. Provide natural, fluent translations."+)++# Create translation quality picker+translation_picker = Agent(+ name="Translation Quality Picker",+ instructions="""+ You are an expert in Spanish translations.+ Given multiple Spanish translation options, pick the most natural, accurate, and fluent one.+ Explain briefly why you chose that translation.+ """+)++# Example 1: Basic parallel execution with quality selection+async def parallel_translation_example():+ """Demonstrates running the same agent multiple times in parallel for quality"""++ print("=== Parallel Translation with Quality Selection ===")++ msg = "Hello, how are you today? I hope you're having a wonderful time!"+ print(f"Original message: {msg}")++ # Ensure the entire workflow is a single trace+ with trace("Parallel Translation Workflow") as workflow_trace:+ print("Running 3 parallel translation attempts...")++ # Run 3 parallel translations+ res_1, res_2, res_3 = await asyncio.gather(+ Runner.run(spanish_agent, msg),+ Runner.run(spanish_agent, msg),+ Runner.run(spanish_agent, msg)+ )++ # Extract text outputs from results+ outputs = [+ ItemHelpers.text_message_outputs(res_1.new_items),+ ItemHelpers.text_message_outputs(res_2.new_items),+ ItemHelpers.text_message_outputs(res_3.new_items)+ ]++ # Combine all translations for comparison+ translations = "\n\n".join([f"Translation {i+1}: {output}" for i, output in enumerate(outputs)])+ print(f"\nAll translations:\n{translations}")++ # Use picker agent to select best translation+ best_translation = await Runner.run(+ translation_picker,+ f"Original English: {msg}\n\nTranslations to choose from:\n{translations}"+ )++ print(f"\nBest translation selected: {best_translation.final_output}")+ print(f"Workflow trace ID: {workflow_trace.trace_id}")++ return best_translation++# Example 2: Parallel execution with different specialized agents+async def parallel_specialized_agents():+ """Shows parallel execution with different agents for diverse perspectives"""++ print("\n=== Parallel Execution with Specialized Agents ===")++ # Create different specialized agents+ formal_translator = Agent(+ name="Formal Spanish Translator",+ instructions="Translate to formal, polite Spanish using 'usted' forms."+ )++ casual_translator = Agent(+ name="Casual Spanish Translator",+ instructions="Translate to casual, friendly Spanish using 'tΓΊ' forms."+ )++ regional_translator = Agent(+ name="Mexican Spanish Translator",+ instructions="Translate to Mexican Spanish with regional expressions and vocabulary."+ )++ msg = "Hey friend, want to grab some coffee later?"+ print(f"Original message: {msg}")++ with trace("Multi-Style Translation") as style_trace:+ print("Running parallel translations with different styles...")++ # Run different translation styles in parallel+ formal_result, casual_result, regional_result = await asyncio.gather(+ Runner.run(formal_translator, msg),+ Runner.run(casual_translator, msg),+ Runner.run(regional_translator, msg)+ )++ # Extract and display all results+ formal_text = ItemHelpers.text_message_outputs(formal_result.new_items)+ casual_text = ItemHelpers.text_message_outputs(casual_result.new_items)+ regional_text = ItemHelpers.text_message_outputs(regional_result.new_items)++ print(f"\nFormal style: {formal_text}")+ print(f"Casual style: {casual_text}")+ print(f"Regional style: {regional_text}")++ # Let user choose preferred style+ style_comparison = f"""+ Original: {msg}++ Formal Spanish: {formal_text}+ Casual Spanish: {casual_text}+ Mexican Spanish: {regional_text}+ """++ style_recommendation = await Runner.run(+ translation_picker,+ f"Compare these translation styles and recommend which is most appropriate for the context: {style_comparison}"+ )++ print(f"\nStyle recommendation: {style_recommendation.final_output}")+ print(f"Multi-style trace ID: {style_trace.trace_id}")++ return style_recommendation++# Example 3: Parallel execution for content generation diversity+async def parallel_content_generation():+ """Demonstrates parallel content generation for creative diversity"""++ print("\n=== Parallel Content Generation for Diversity ===")++ # Create content generation agents with different approaches+ creative_agent = Agent(+ name="Creative Writer",+ instructions="Write creative, engaging content with vivid imagery and storytelling."+ )++ informative_agent = Agent(+ name="Informative Writer",+ instructions="Write clear, factual, informative content focused on key information."+ )++ persuasive_agent = Agent(+ name="Persuasive Writer",+ instructions="Write compelling, persuasive content that motivates action."+ )++ topic = "The benefits of learning a new language"+ print(f"Content topic: {topic}")++ with trace("Diverse Content Generation") as content_trace:+ print("Generating content with different writing styles in parallel...")++ # Generate different content approaches simultaneously+ creative_result, informative_result, persuasive_result = await asyncio.gather(+ Runner.run(creative_agent, f"Write a short paragraph about: {topic}"),+ Runner.run(informative_agent, f"Write a short paragraph about: {topic}"),+ Runner.run(persuasive_agent, f"Write a short paragraph about: {topic}")+ )++ # Extract content+ creative_content = ItemHelpers.text_message_outputs(creative_result.new_items)+ informative_content = ItemHelpers.text_message_outputs(informative_result.new_items)+ persuasive_content = ItemHelpers.text_message_outputs(persuasive_result.new_items)++ print(f"\nCreative approach:\n{creative_content}")+ print(f"\nInformative approach:\n{informative_content}")+ print(f"\nPersuasive approach:\n{persuasive_content}")++ # Synthesize best elements from all approaches+ synthesis_agent = Agent(+ name="Content Synthesizer",+ instructions="Combine the best elements from multiple content pieces into one cohesive, high-quality paragraph."+ )++ combined_content = f"""+ Topic: {topic}++ Creative version: {creative_content}++ Informative version: {informative_content}++ Persuasive version: {persuasive_content}+ """++ synthesized_result = await Runner.run(+ synthesis_agent,+ f"Create the best possible paragraph by combining elements from these approaches: {combined_content}"+ )++ print(f"\nSynthesized content: {synthesized_result.final_output}")+ print(f"Content generation trace ID: {content_trace.trace_id}")++ return synthesized_result++# Main execution+async def main():+ print("πΌ OpenAI Agents SDK - Parallel Multi-Agent Execution")+ print("=" * 60)++ await parallel_translation_example()+ await parallel_specialized_agents()+ await parallel_content_generation()++ print("\nβ Parallel execution tutorial complete!")+ print("Parallel execution enables quality improvement through diversity and selection")++if __name__ == "__main__":+ asyncio.run(main())diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/requirements.txt b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/requirements.txtnew file mode 100644index 00000000..a88bde1d--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/9_multi_agent_orchestration/requirements.txt@@ -0,0 +1,3 @@+openai-agents>=1.0.0+streamlit>=1.28.0+python-dotenv>=1.0.0diff --git a/ai_agent_framework_crash_course/openai_sdk_crash_course/README.md b/ai_agent_framework_crash_course/openai_sdk_crash_course/README.mdnew file mode 100644index 00000000..34d96b4a--- /dev/null+++ b/ai_agent_framework_crash_course/openai_sdk_crash_course/README.md@@ -0,0 +1,209 @@+# π OpenAI Agents SDK Crash Course++A comprehensive tutorial series for learning OpenAI's Agents SDK from basics to advanced concepts. This crash course is designed to take you from zero to hero in building AI agents with the OpenAI Agents SDK.++## π What is OpenAI Agents SDK?++OpenAI Agents SDK is a powerful framework for **developing and deploying AI agents**. It provides:++### Key Features:+- **Agent Orchestration**: Create and manage intelligent AI agents+- **Tool Integration**: Extend agents with custom and built-in tools+- **Structured Outputs**: Type-safe responses using Pydantic models+- **Multi-Agent Workflows**: Coordinate multiple agents with handoffs+- **Real-time Execution**: Sync, async, and streaming execution methods+- **Voice Integration**: Static, streaming, and realtime voice capabilities+- **Session Management**: Automatic conversation memory and history+- **Production Ready**: Built-in tracing, guardrails, and monitoring++## π― Learning Path++This crash course covers the essential concepts of OpenAI Agents SDK through hands-on tutorials:++### π **Tutorials**++#### **π± Foundation Layer**++1. **[1_starter_agent](./1_starter_agent/README.md)** - Your first OpenAI agent+ - Basic agent creation and configuration+ - Understanding different execution methods+ - Simple text processing and responses++2. **[2_structured_output_agent](./2_structured_output_agent/README.md)** - Type-safe responses+ - **Support Ticket Agent** - Convert complaints to structured tickets+ - **Product Review Agent** - Extract structured data from reviews+ - Pydantic models and validation++#### **π§ Core Capabilities Layer**++3. **[3_tool_using_agent](./3_tool_using_agent/README.md)** - Agent tools & functions+ - Custom function tools with `@function_tool`+ - Built-in tools (WebSearch, CodeInterpreter, FileSearch)+ - Tool integration and execution patterns++4. **[4_running_agents](./4_running_agents/README.md)** - Running & execution mastery+ - The agent loop: LLM calls, tool execution, handoffs+ - Sync, async, and streaming execution methods+ - Advanced streaming events and exception handling+ - Run configuration and conversation management++5. **[5_context_management](./5_context_management/README.md)** - State & context handling+ - Context passing between runs+ - State persistence and management+ - Conversation flow control++#### **π§ Advanced Features Layer**++6. **[6_guardrails_validation](./6_guardrails_validation/README.md)** - Safety & validation+ - Input guardrails for user validation+ - Output guardrails for response filtering+ - Custom business rule validation++7. **[7_sessions](./7_sessions/README.md)** - Sessions & memory management+ - Automatic conversation history with SQLiteSession+ - Memory operations and conversation corrections+ - Multiple session management and organization++#### **π€ Multi-Agent Layer**++8. **[8_handoffs_delegation](./8_handoffs_delegation/README.md)** - Agent handoffs & delegation+ - Agent-to-agent task delegation+ - Triage systems and smart routing+ - Advanced handoff configuration with callbacks++9. **[9_multi_agent_orchestration](./9_multi_agent_orchestration/README.md)** - Complex workflows+ - Parallel agent execution with `asyncio.gather()`+ - Agents as tools orchestration patterns+ - Multi-stage workflow coordination++#### **π Production Layer**++10. **[10_tracing_observability](./10_tracing_observability/README.md)** - Monitoring & debugging+ - Built-in tracing and execution visualization+ - Custom traces and spans for complex workflows+ - Performance monitoring and optimization++#### **ποΈ Voice & Advanced Features**++11. **[11_voice](./11_voice/README.md)** - Voice agents & real-time conversation+ - Static voice processing (turn-based interaction)+ - Streaming voice processing (real-time conversation)+ - Realtime voice agents (ultra-low latency with WebSocket)+ - Speech-to-text, text-to-speech, and voice pipelines++## π οΈ Prerequisites++Before starting this crash course, ensure you have:++- **Python 3.8+** installed (Python 3.9+ required for voice features)+- **OpenAI API Key** from [OpenAI Platform](https://platform.openai.com/api-keys)+- Basic understanding of Python and APIs+- Familiarity with async/await concepts (helpful but not required)+- **For voice tutorials**: Microphone and speakers/headphones++## π How to Use This Course++Each tutorial follows a consistent structure:++- **README.md**: Concept explanation and learning objectives+- **Python files**: Contains the agent implementations and examples+- **Interactive interfaces**: Streamlit web apps for hands-on testing+- **Submodules**: Organized examples for different concepts+- **requirements.txt**: Dependencies for the tutorial+- **env.example**: Environment variable template++### Learning Approach:+1. **Read the README** to understand the concept+2. **Examine the code** to see the implementation+3. **Run the examples** to see agents in action+4. **Experiment** by modifying the code+5. **Use interactive interfaces** for hands-on testing+6. **Try voice features** (tutorial 11) with your microphone+7. **Move to the next tutorial** when ready++## π― Tutorial Features++Each tutorial includes:+- β **Clear concept explanation**+- β **Minimal, working code examples**+- β **Real-world use cases**+- β **Step-by-step instructions**+- β **Interactive web interfaces**+- β **Best practices and tips**++## π Quick Start++1. **Clone the repository** and navigate to this directory+2. **Choose a tutorial** from the list above+3. **Follow the README** instructions for that tutorial+4. **Install dependencies**: `pip install -r requirements.txt`+5. **Set up environment**: Copy `env.example` to `.env` and add your API key+6. **Run the examples** and start learning!++## π§ Environment Setup++Each tutorial requires an OpenAI API key. Create a `.env` file in each tutorial directory:++```bash+OPENAI_API_KEY=sk-your_openai_key_here+```++Get your API key from: [https://platform.openai.com/api-keys](https://platform.openai.com/api-keys)++## π‘ Learning Tips++- **Start Sequential**: Follow tutorials in order for best learning experience+- **Experiment Freely**: Modify code and see what happens+- **Use Web Interfaces**: Interactive apps make learning more engaging+- **Read Error Messages**: They often contain helpful guidance+- **Join Community**: Engage with other learners and share experiences++## π¨ Common Issues++### API Key Problems+- Make sure your `.env` file is in the tutorial directory+- Verify your API key is valid and has sufficient credits+- Check for typos in the environment variable name++### Import Errors+- Ensure you've installed requirements: `pip install -r requirements.txt`+- Check that you're using Python 3.8 or higher+- Try creating a virtual environment if you have conflicts++### Rate Limiting+- OpenAI has rate limits based on your plan+- If you hit limits, wait a moment before trying again+- Consider upgrading your OpenAI plan for higher limits++## π Additional Resources++- [OpenAI Agents SDK Documentation](https://openai.github.io/openai-agents-python/)+- [OpenAI Platform](https://platform.openai.com/)+- [Pydantic Documentation](https://docs.pydantic.dev/)+- [Streamlit Documentation](https://docs.streamlit.io/)++## π€ Contributing++Feel free to contribute improvements, bug fixes, or additional tutorials. Each tutorial should:+- Be self-contained and runnable+- Include clear documentation+- Follow the established structure+- Use minimal, understandable code++## π Progress Tracking++Track your progress through the course:++- [ ] **Tutorial 1**: Basic agent creation β¨+- [ ] **Tutorial 2**: Structured outputs with Pydantic+- [ ] **Tutorial 3**: Tool integration and custom functions+- [ ] **Tutorial 4**: Execution methods mastery+- [ ] **Tutorial 5**: Context and state management+- [ ] **Tutorial 6**: Guardrails and validation+- [ ] **Tutorial 7**: Sessions and memory management+- [ ] **Tutorial 8**: Agent handoffs and delegation+- [ ] **Tutorial 9**: Multi-agent orchestration+- [ ] **Tutorial 10**: Tracing and observability+- [ ] **Tutorial 11**: Voice agents and real-time conversation π―++Happy learning! π