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.
Sign in to save downloads to your library and vote.
Preview
๐ง 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:
@dataclass
class UserInfo:
name: str
uid: int
preferences: dict = None
RunContextWrapper
Type-safe wrapper that provides access to context in tools:
@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:
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 contextupdate_user_preference(): Modify user settings in contextget_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
-
Install OpenAI Agents SDK:
pip install openai-agents -
Set up environment:
cp env.example .env # Edit .env and add your OpenAI API key -
Run the context example:
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
from dataclasses import dataclass
@dataclass
class UserInfo:
name: str
uid: int
preferences: dict = None
2. Context-Aware Tool
@function_tool
async def my_tool(wrapper: RunContextWrapper[UserInfo]) -> str:
user = wrapper.context
return f"Processing for {user.name}"
3. Running with Context
user_context = UserInfo(name="Alice", uid=123)
result = await Runner.run(agent, "message", context=user_context)
4. Context Updates
@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
- Use Dataclasses: Leverage Python dataclasses for clean context objects
- Type Safety: Always use generic typing for compile-time validation
- Immutable Where Possible: Consider frozen dataclasses for read-only context
- Validation: Add validation to context object initialization
- 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 - Input/output safety with context
- Tutorial 7: Sessions - Combining context with conversation memory
- Tutorial 8: Production Patterns - Scaling context in real applications
Ingestion metadata
- Source catalog
- awesome-llm-apps
- Repository
- Shubhamsaboo/awesome-llm-apps ยท main
- File path
- ai_agent_framework_crash_course/openai_sdk_crash_course/5_context_management/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)