# Practical and Useful Patterns for OpenAI Agent SDK
🌍 Same agent, different experience for every user. Dynamic instructions let you build prompts on the fly based on runtime context.
Pass a function to instructions that receives RunContextWrapper and Agent, and dynamically generate system prompts at runtime.
📌 Title: Agents -- Dynamic instructions
🔗 URL:
🧩 Overview
The `instructions` parameter of an Agent accepts not just strings but also functions. The function receives a `RunContextWrapper` and an `Agent`, returning a string. This lets you inject information only available at runtime -- logged-in user details, current time, user plan, locale, and more. Async functions are also supported, enabling database lookups before prompt construction.
🛠 How to Use
Define a function `dynamic_instructions(context: RunContextWrapper[UserContext], agent: Agent) -> str` that accesses user details from `context.context` and builds a prompt string with the user's name, plan, and current time. Pass this function as `instructions=dynamic_instructions` to the `Agent` for runtime-dynamic system prompts.
🏗 Practical Usage Patterns
**Runtime Injection of User Name, Plan, and Datetime**
Reflect logged-in user information in prompts for personalized responses.
Define a `
@dataclass` called `UserContext` with `name: str`, `plan: str`, and `timezone: str`. In the `personalized_instructions(context: RunContextWrapper[UserContext], agent: Agent) -> str` function, access `context.context` for user details and ` for the current time, then branch the prompt based on `user.plan` (`"pro"`, `"enterprise"`, or free). Set `instructions=personalized_instructions` on the `Agent` and pass `context=UserContext(name="Alice", plan="pro", timezone="US/Eastern")` to ` at execution time.
**Multi-language Switching by Locale**
Automatically switch instruction language based on the user's locale setting.
Store locale-specific system prompts in an `INSTRUCTIONS_BY_LOCALE` dictionary keyed by `"ja"`, `"en"`, and `"zh"`. In the `locale_instructions(context: RunContextWrapper[UserContext], agent: Agent) -> str` function, read `context.context.locale` and look up the matching prompt with `INSTRUCTIONS_BY_LOCALE.get(locale, INSTRUCTIONS_BY_LOCALE["en"])`, falling back to English.
**Async Function to Fetch Data from DB into Prompt**
Retrieve the user's recent purchase history from a database to provide context-aware support.
Define `async def instructions_with_history(context: RunContextWrapper[UserContext], agent: Agent) -> str` that calls `await db.fetch_recent_orders( limit=5)` to fetch recent purchase history from the database. Format the orders into a summary string and embed it in the prompt for context-aware support. Set `instructions=instructions_with_history` on the `Agent` to use this async function.
💡 Use Cases
👤 Inject logged-in user's name, plan, and datetime at runtime for personalized responses
💎 Branch behavior by plan -- advanced feature guidance for Pro, upgrade suggestions for Free
🌐 Auto-switch instruction language based on user locale for seamless multi-language support
📦 Fetch recent purchase history from DB via async function for context-aware customer support
⚠️ Caveats
- Heavy DB queries in async instruction functions delay agent response start. Consider caching or query optimization.
- Exceptions inside instruction functions cause the entire agent to fail. Implement proper error handling and fallbacks.
- Watch out for dynamically generated prompts growing too long -- this increases token consumption.
✨ Dynamic instructions let you deliver diverse user experiences from a single agent definition. Leverage runtime information to build truly personalized agents!
#
OpenAIAgentSDK# #
AIAgent#