0

๐Ÿง  Tutorial 5: Context Management

awesome-llm-apps5_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.

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 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:

    pip install openai-agents
    
  2. Set up environment:

    cp env.example .env
    # Edit .env and add your OpenAI API key
    
  3. 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

  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:

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)