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.
Sign in to save downloads to your library and vote.
Preview
๐ 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.
๐ฏ 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
RunResultStreamingobject 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
-
Install OpenAI Agents SDK:
pip install openai-agents -
Install dependencies:
pip install -r requirements.txt -
Set up environment variables:
cp env.example .env # Edit .env and add your OpenAI API key -
Test execution methods:
python -m 4_1_execution_methods.agent -
Try conversation management:
python -m 4_2_conversation_management.agent -
Explore run configuration:
python -m 4_3_run_configuration.agent -
Test streaming events:
python -m 4_4_streaming_events.agent -
Practice exception handling:
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
# 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
- Choose Right Method: Sync for scripts, async for apps, streaming for long responses
- Handle Exceptions: Always wrap Runner calls in proper exception handling
- Configure Appropriately: Use RunConfig for production settings
- Monitor Performance: Track execution time and resource usage
- Manage Conversations: Choose manual vs Sessions based on requirements
๐ Next Steps
After completing this tutorial, you'll be ready for:
- Tutorial 5: Context Management - Advanced state management
- Tutorial 6: Guardrails & Validation - Input/output safety
- Tutorial 7: Sessions - Memory and conversation management
๐จ Troubleshooting
- Async Issues: Always use
awaitwithRunner.run()andRunner.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 torunwhen 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
Ingestion metadata
- Source catalog
- awesome-llm-apps
- Repository
- Shubhamsaboo/awesome-llm-apps ยท main
- File path
- ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/README.md
- Last refreshed
- 7/23/2026, 10:39:09 PM (4h ago)
- Refresh schedule
- Daily ยท 03:00 UTC
- Dedupe status
- Unique ยท deduped by (source, url)