Register and share your invite link to earn from video plays and referrals.

Search results for OpenAIAgentSDK
OpenAIAgentSDK community
One keyword maps to one global community path.
Create community
People
Not Found
Tweets including OpenAIAgentSDK
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Want to manage and version your prompts on the platform instead of hardcoding them? With Prompt Templates, you can reference prompts created on the OpenAI platform from the SDK, injecting variables dynamically. 📌 Title: Prompt Templates 🔗 URL: 🧩 Overview Instead of `instructions`, you can use the `prompt` parameter to reference prompt templates created and managed on the OpenAI platform. For static usage, pass a dict like `{"id": "pmpt_123", "version": "1", "variables": {...}}`. For dynamic usage, pass an async function that returns a prompt dict at runtime, enabling context-dependent variable injection. 🛠 How to use it ```python from agents import Agent, RunContextWrapper # Static template reference agent_static = Agent( name="support", prompt={ "id": "pmpt_abc123", "version": "1", "variables": { "company_name": "Acme Corp", "support_level": "premium", }, }, ) # Dynamic template reference async def dynamic_prompt( context: RunContextWrapper[UserContext], agent: Agent, ) -> dict: user = context.context return { "id": "pmpt_abc123", "version": "2", "variables": { "company_name": "support_level": user.plan, "language": user.language, }, } agent_dynamic = Agent( name="dynamic-support", prompt=dynamic_prompt, ) ``` 🏗 Building it into production ・Manage prompts on the platform for updates and rollbacks without code deployment ・Use version pinning for stable behavior while gradually rolling out new versions ・Inject user-attribute-based variables with dynamic templates ・Share and reuse prompts across teams for quality standardization 💡 Use cases 📝 Prompt version management and staged rollouts 🏢 Cross-organization prompt sharing and standardization 🔄 Prompt updates without code deployment 👤 Dynamic variable injection based on user attributes ⚠️ Watch out `prompt` and `instructions` are mutually exclusive; specifying both causes an error. If the referenced prompt doesn't exist on the platform, you'll also get an error. Verify prompt IDs and versions before deployment, and watch for variable name typos. ✨ With Prompt Templates, move prompt management from "inside the code" to "the platform dashboard." #OpenAIAgentSDK# #AIAgent#
Show more
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 Want to filter what goes into the model or gracefully handle errors without crashing? Input filters and error handlers give you fine-grained control over agent behavior at the edges. 📌 Title: Running agents – Hooks and customization / Error handlers 🔗 URL: 🧩 Overview `call_model_input_filter` is a hook that transforms model input just before it's sent — perfect for trimming history, masking secrets, or injecting dynamic system instructions. `error_handlers` lets you catch specific errors (tool failures, model refusals, max turns) and return app-specific fallback output instead of raising exceptions. Together, they enable production-grade resilient agents. 🛠 Usage Import `Agent`, `Runner`, and `ErrorHandlers` from `agents`. Define `trim_history(input_data)` to keep only the last 10 messages via `input_data.messages = input_data.messages[-10:]`, and `mask_secrets(input_data)` to replace secrets with `msg.content.replace(os.environ.get("API_KEY", ""), "***")`. Define `handle_refusal(ctx, error)` to return a domain-specific fallback on model refusal. Configure the agent with `Agent(name="chef", instructions="You are a recipe assistant.", call_model_input_filter=trim_history, error_handlers=ErrorHandlers(model_refusal=handle_refusal, max_turns=lambda ctx, err: FallbackOutput(message="Processing did not complete. Try shorter input.", include_in_history=False)))`. 🏗 Practical Patterns **History Trimming for Cost Control** Use `call_model_input_filter` to keep only the last N messages, reducing token consumption in long conversations. A practical pattern: always preserve the system prompt at the top while pruning older user messages. **Secret Masking** When tool outputs contain API keys or tokens, mask them before they reach the model via the input filter. This reduces the risk of the model memorizing or echoing sensitive information. **Dynamic System Instruction Injection** Inside the filter, inject context-aware system instructions based on user permissions or state. For example: "This customer is on the Premium plan" — letting the model tailor its responses dynamically. **Graceful max_turns Fallback** When a looping agent hits the turn limit, return a user-friendly message instead of an exception. Setting `include_in_history=False` keeps the fallback out of future turns, so retries start clean. **App-Specific Model Refusal Handling** Instead of catching `ModelRefusalError` and returning a generic error, return a structured fallback matching your domain model. A recipe app returns an empty Recipe with `refusal_reason`; a chat app suggests alternative topics. 💡 Use Cases 🔒 Prevent API keys and tokens from reaching the model 📏 Auto-trim long chat history to optimize token costs 🔄 Guide users to next actions when max_turns is reached 🛡 Return structured domain-specific fallbacks on model refusal ⚠️ Caveats - Over-pruning messages in `call_model_input_filter` causes the model to lose context and degrade response quality. Always preserve critical system prompts. - Ensure fallback outputs from `error_handlers` match the agent's `output_type`. Type mismatches cause runtime errors. - Fallback outputs with `include_in_history=False` won't be available in subsequent turns. Use this only for display-only information. - Exceptions thrown inside filters or handlers will halt the entire agent. Write defensive logic within these hooks. ✨ Combine input filters and error handlers to build agents that handle edge cases gracefully in production! #OpenAIAgentSDK# #AIAgent#
Show more
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 Control agent input and output safely with guardrails! Use cheap, fast models for pre-checks to block inappropriate requests and reduce costs. 📌 Title: Guardrails 🔗 URL: 🧩 Overview Guardrails run checks on agent inputs and outputs. Input guardrails validate user input, while output guardrails validate agent responses. By using cheap, fast models as guardrails to prevent unnecessary execution of expensive models, you achieve cost optimization. The tripwire mechanism immediately halts execution when a problem is detected. 🛠 Usage Import `Agent`, `InputGuardrail`, `OutputGuardrail`, and `GuardrailFunctionOutput` from `agents`. Define a guardrail function `check_homework_request(context, agent, input_data)` that calls ` input_data)` and returns `GuardrailFunctionOutput(output_info= tripwire_triggered= Create the agent with `Agent(name="TutorBot", instructions="You are a tutoring assistant.", input_guardrails=[InputGuardrail(guardrail_function=check_homework_request)])`. 🏗 Practical Patterns **Pre-filtering with Cheap Models (Cost Reduction)** Before running the expensive main model, use a cheap fast model to detect and block "homework requests" or "abuse." When the tripwire triggers, the main model execution is skipped, reducing costs. Define a cheap classifier `Agent(name="Classifier", model="gpt-4o-mini", output_type=ClassificationResult)` and an `abuse_check` function that runs ` input_data)` with `tripwire_triggered= Attach it to the main agent via `Agent(name="Assistant", model="gpt-4o", input_guardrails=[InputGuardrail(guardrail_function=abuse_check)])`. **Output Guardrails for Content Checking** Verify that agent responses don't contain sensitive or inappropriate content. Define an output guardrail function `check_sensitive_output(context, agent, output)` that runs ` f"Check this output for sensitive content: {output}")` and returns `GuardrailFunctionOutput(output_info= tripwire_triggered= Attach it with `Agent(name="SupportBot", output_guardrails=[OutputGuardrail(guardrail_function=check_sensitive_output)])`. **Relevance Check for Support Bots** Pre-determine whether user questions fall within scope, handling out-of-scope queries early. Define `relevance_check(context, agent, input_data)` which runs ` input_data)` and sets `tripwire_triggered=not to catch out-of-scope questions. Apply it with `Agent(name="SupportBot", instructions="Answer customer support questions about our product.", input_guardrails=[InputGuardrail(guardrail_function=relevance_check)])`. 💡 Use Cases 🛡 Block homework completion and abuse requests (cost reduction) 🔍 Prevent sensitive data in output (PII, internal information leak prevention) 📋 Control support bot response scope ⚡ Optimize API costs with cheap model pre-screening ⚠️ Considerations - When a guardrail tripwire triggers, an `InputGuardrailTripwireTriggered` exception is raised — catch and handle it appropriately - Input guardrails run **in parallel** with the main model by default, so the main execution may proceed if the guardrail doesn't finish in time - Factor in the model call cost of the guardrails themselves - Multiple guardrails can be set — execution halts if any one triggers ✨ Use guardrails to build agents that balance safety and cost efficiency! #OpenAIAgentSDK# #AIAgent#
Show more
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 Add guardrails to tool inputs and outputs for enhanced security! Check tool arguments and mask outputs to prevent sensitive data leaks and unauthorized operations. 📌 Title: Guardrails – Tool guardrails 🔗 URL: 🧩 Overview Tool guardrails enable security checks before tool execution (argument checking) and after execution (output checking). They prevent API key injection, mask sensitive data, and block specific operations at the tool level. Even in complex workflows using manager patterns, Handoffs, or delegation, you can apply fine-grained checks to individual tools. 🛠 Usage Import `Agent` and `function_tool` from `agents`. Decorate a tool function with `@function_tool` such as `search_api(query: str) -> str`, then configure the agent with `Agent(name="SecureAgent", tools=[search_api], tool_guardrails=[check_tool_args])` to attach tool-level guardrails. 🏗 Practical Patterns **Block API Key Injection (reject_content)** Check if tool arguments contain API keys starting with `sk-` and block tool execution when detected. Import `re` and `GuardrailFunctionOutput`. Define `reject_api_keys(context, agent, tool_call)` which checks ` str(tool_call.arguments))` to detect API key injection, returning `GuardrailFunctionOutput(output_info={"checked": "api_key_presence"}, tripwire_triggered=has_api_key)`. Attach it with `Agent(name="SecureAgent", tools=[search_api, call_external_service], tool_guardrails=[reject_api_keys])`. **Mask Sensitive Data in Tool Output** Automatically mask sensitive information (email addresses, phone numbers, etc.) in tool execution output. Define `mask_sensitive_output(context, agent, tool_call, tool_output)` which applies `re.sub(r'[\w.+-]+@[\w-]+\.[\w.]+', '[MASKED_EMAIL]', str(tool_output))` for emails and `re.sub(r'\d{3}-\d{4}-\d{4}', '[MASKED_PHONE]', masked)` for phone numbers. Return `GuardrailFunctionOutput(output_info={"masked": True}, tripwire_triggered=False, modified_output=masked)` to pass the sanitized output. Configure with `Agent(name="DataAgent", tools=[query_customer_db], tool_guardrails=[mask_sensitive_output])`. **Per-Tool Checks in Complex Workflows** Apply fine-grained guardrails to specific tools even in complex workflows combining manager patterns, Handoffs, and delegation. Define `check_delete_permission(context, agent, tool_call)` which checks ` == "delete_record"` and verifies `context.get("user_role", "viewer")` is in `["admin", "editor"]`, triggering the tripwire for unauthorized users. Non-delete tools return `tripwire_triggered=False`. Combine multiple guardrails with `Agent(name="Manager", tools=[query_db, update_record, delete_record], tool_guardrails=[check_delete_permission, reject_api_keys])`. 💡 Use Cases 🔑 Prevent API key/secret injection in tool arguments 🎭 Automatic PII masking in tool outputs 🚫 Block specific tool operations based on permissions 🔒 Security control in complex multi-agent workflows ⚠️ Considerations - Tool guardrails are invoked per tool execution — consider performance impact - Regex-based checks are not exhaustive — use multiple defense layers for critical security requirements - Masking may change the original data type — verify it doesn't affect downstream processing - When multiple tool guardrails are set, all execute sequentially ✨ Use tool guardrails for fine-grained control over agent tool operations and enhanced security! #OpenAIAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Want the tool's output to be the final answer, but the model keeps adding unnecessary summaries? With `tool_use_behavior`, you can make tool output the final result directly, stop at specific tools, or customize output handling with fine-grained control. 📌 Title: tool_use_behavior 🔗 URL: 🧩 Overview `tool_use_behavior` controls what happens after an agent calls a tool. Setting `"stop_on_first_tool"` makes the first tool's output the final result. `StopAtTools(stop_at_tool_names=[...])` limits this behavior to specific tools. You can also pass a custom function that returns `ToolsToFinalOutputResult(is_final_output=True, final_output=...)` to transform the output before finalizing it. 🛠 How to use it ```python from agents import Agent, StopAtTools, ToolsToFinalOutputResult # First tool output becomes the final result agent_direct = Agent( name="direct", tools=[search_tool], tool_use_behavior="stop_on_first_tool", ) # Stop only on specific tools agent_selective = Agent( name="selective", tools=[search_tool, format_tool, send_tool], tool_use_behavior=StopAtTools( stop_at_tool_names=["format_tool"] ), ) # Custom function for output control def custom_behavior(context, tool_results): result = tool_results[0] if result.tool_name == "get_answer": return ToolsToFinalOutputResult( is_final_output=True, final_output=f"Answer: {result.output}", ) return ToolsToFinalOutputResult(is_final_output=False) agent_custom = Agent( name="custom", tools=[get_answer, search_tool], tool_use_behavior=custom_behavior, ) ``` 🏗 Building it into production ・Use `"stop_on_first_tool"` for proxy-style agents that return API results directly ・Finalize output at specific pipeline steps to reduce unnecessary LLM calls ・Standardize output format with custom functions for stable downstream integration ・Pass structured data (JSON, etc.) directly to subsequent processing without model summarization 💡 Use cases 🔌 Proxy agents returning API results as-is 📊 Direct output of database query results 🔄 Output finalization at pipeline intermediate steps 🎯 Selective control to use only specific tool results as final output ⚠️ Watch out With `"stop_on_first_tool"`, the model won't interpret or supplement results. If user-friendly output is needed, use a custom function. Also verify behavior when multiple tools are called in parallel. ✨ With `tool_use_behavior`, take agent output from "model decides" to "by design." #OpenAIAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Want to stream progress in real time while a nested agent tool is running? With the `on_stream` callback, you can receive events from child agent executions in real time on the parent side. 📌 Title: Streaming Nested Agent Runs 🔗 URL: 🧩 Overview When converting an agent to a tool with `as_tool()`, you can set a callback function on the `on_stream` parameter. This callback receives `AgentToolStreamEvent` and can process events in real time during child agent execution, including `raw_response_event` and `run_item_stream_event`. The event types mirror the standard streaming format, so you can reuse existing streaming handlers. 🛠 How to use it ```python from agents import Agent, Runner research_agent = Agent( name="researcher", instructions="Research the topic in detail", ) # Streaming callback async def handle_stream(event): # raw_response_event: model responses # run_item_stream_event: tool calls, etc. if hasattr(event, 'data'): print(f"[Researching] {") parent = Agent( name="coordinator", tools=[ research_agent.as_tool( tool_name="research", tool_description="Research a topic", on_stream=handle_stream, ), ], ) # Streamed execution async for event in "Research the latest AI trends"): print(event) ``` 🏗 Building it into production ・Display child agent processing progress in the UI in real time so users never feel stuck waiting ・Use `raw_response_event` to incrementally display generated text ・Log tool execution status via `run_item_stream_event` ・Reuse existing streaming UI components as-is 💡 Use cases 🖥 Real-time UI display of multi-agent processing progress 📝 Typewriter-style incremental display of child agent responses 🔍 Visualizing a research agent's search and analysis process 📊 Providing users with intermediate feedback during long-running tasks ⚠️ Watch out The `on_stream` callback runs within the child agent's execution thread, so heavy processing will impact overall agent performance. Keep event handlers lightweight and consider offloading to an async queue if needed. Add guard clauses to ignore unknown event types for forward compatibility. ✨ With streaming, give users a transparent "see inside" experience for multi-agent workflows. #OpenAIAgentSDK# #AIAgent#
Show more
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 Can you see what is happening inside your agent? Lifecycle hooks let you transparently embed logging, auditing, and performance optimization into agent behavior. RunHooks and AgentHooks let you inject custom logic at agent start/end, LLM calls, tool execution, and handoff events. 📌 Title: Agents -- Lifecycle events (hooks) 🔗 URL: 🧩 Overview The OpenAI Agent SDK provides a hook mechanism for executing custom code at each stage of an agent's lifecycle. `RunHooks` apply to the entire workflow, while `AgentHooks` apply to specific agents. Available hooks include `on_agent_start`/`on_agent_end`, `on_llm_start`/`on_llm_end`, `on_tool_start`/`on_tool_end`, and `on_handoff`. Use them to implement logging, metrics collection, audit trails, and data prefetching. 🛠 How to Use Define a `LoggingHooks` class extending `RunHooks`, overriding `async def on_agent_start(self, context, agent)` and `async def on_agent_end(self, context, agent, output)` to log agent lifecycle events. Create an `Agent` and pass the hooks instance via ` "Hello", run_hooks=LoggingHooks())`. 🏗 Practical Usage Patterns **Output Item Count Logging with on_llm_end, Token Usage Logging with on_agent_end** Combine workflow-wide RunHooks with agent-specific AgentHooks for comprehensive monitoring. `MetricsRunHooks` extends `RunHooks` and logs `total_tokens` and `prompt_tokens` in `on_agent_end` for workflow-wide cost monitoring. `DetailedAgentHooks` extends `AgentHooks` and logs the output item count from `response.output` in `on_llm_end` for agent-specific monitoring. Apply agent-level hooks via `Agent(hooks=DetailedAgentHooks())` and workflow-level hooks via ` ..., run_hooks=MetricsRunHooks())` for comprehensive observability. **Audit Logging and Distributed Tracing with on_tool_start ToolContext** Record trace information before and after tool execution to simplify incident investigation. `AuditHooks` extends `AgentHooks` and implements `on_tool_start` to log `context.context.trace_id`, ` ` and a UTC timestamp for distributed tracing. In `on_tool_end`, it logs the same `trace_id` and ` along with a success check (`result is not None`) to complete the audit trail. **Data Prefetching on Handoff for Latency Reduction** Pre-fetch data needed by the target agent during handoff to improve response times. `PrefetchHooks` extends `RunHooks` and implements `on_handoff` to check if ` is `"OrderSupportAgent"`. When matched, it calls `await db.fetch_orders( and `await db.fetch_payment_methods( to pre-load data into the user context, reducing latency for the target agent. 💡 Use Cases 📊 Log LLM response output item counts with on_llm_end for output quality monitoring 💰 Log token usage with on_agent_end and feed into cost management dashboards 🔍 Automatically record audit logs and distributed traces with on_tool_start/end ⚡ Prefetch data on_handoff for the target agent to reduce response latency ⚠️ Caveats - Exceptions inside hooks can affect agent execution. Always wrap hook logic in try/except for reliable error handling. - Heavy processing in hooks increases overall agent latency. Consider async I/O or background tasks. - Be intentional about RunHooks vs AgentHooks. Use RunHooks for cross-workflow monitoring and AgentHooks for detailed monitoring of specific agents. ✨ Lifecycle hooks transform your agent from a "black box" into a fully observable system. Implement the monitoring, auditing, and optimization essential for production -- without polluting your agent logic! #OpenAIAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Too many tools eating up your token budget? There's a way to load tools only when needed. Combining `defer_loading` with `ToolSearchTool`, the model can search for and dynamically load only the tools it needs, dramatically reducing token consumption. 📌 Title: Hosted Tool Search / tool_namespace / defer_loading 🔗 URL: 🧩 Overview Tools decorated with `@function_tool(defer_loading=True)` are excluded from the tool list on the initial model call. By adding `ToolSearchTool()` to the agent, the model first searches for relevant tools and loads only the ones it needs. You can also group tools using `tool_namespace`. This is a powerful feature for optimizing token usage in agents with many tools. Note that this feature is only available with `OpenAIResponsesModel`. 🛠 How to use it ```python from agents import Agent, function_tool from agents.tool import ToolSearchTool @function_tool(defer_loading=True, tool_namespace="analytics") def run_report(report_type: str) -> str: return generate_report(report_type) @function_tool(defer_loading=True, tool_namespace="analytics") def export_csv(dataset: str) -> str: return create_csv(dataset) @function_tool(defer_loading=True, tool_namespace="admin") def manage_users(action: str) -> str: return user_management(action) agent = Agent( name="assistant", tools=[ ToolSearchTool(), # Enable tool search run_report, export_csv, manage_users, ], ) ``` 🏗 Building it into production ・Reduce token costs for agents with dozens to hundreds of tools ・Use `tool_namespace` to logically group tools and improve search accuracy ・Keep frequently used tools at `defer_loading=False` (default) and defer only rarely used ones ・Scale tool count without worrying about prompt size 💡 Use cases 🧰 Tool management for feature-rich SaaS agents 📊 On-demand loading of analytics and reporting tools 🔧 Showing admin tools only when needed 🚀 Ensuring tool count scalability ⚠️ Watch out This feature works only with `OpenAIResponsesModel` and is not available with other model providers. Deferred tools are unavailable on the first turn, so they're not suitable for tools that must respond immediately to the user's initial request. ✨ Load "only the right tools at the right time" with tool search for smarter agents. #OpenAIAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Want to dynamically toggle which tools are available based on user permissions or plan tier? The `is_enabled` parameter lets you conditionally control tool availability, providing context-appropriate toolsets. 📌 Title: Conditional Tool Enabling 🔗 URL: 🧩 Overview By passing a boolean `True`/`False` or a callback function `(ctx, agent) -> bool` to the `is_enabled` parameter on `as_tool()`, you can dynamically control whether a tool is enabled or disabled. Disabled tools don't appear in the model's tool list and consume no tokens. This is ideal for feature gating and permission-based access control. 🛠 How to use it ```python from agents import Agent, function_tool, RunContextWrapper @function_tool def admin_tool(command: str) -> str: return execute_admin(command) @function_tool def basic_tool(query: str) -> str: return basic_search(query) # Dynamic check via callback def is_admin(ctx: RunContextWrapper, agent: Agent) -> bool: return ctx.context.user_role == "admin" agent = Agent( name="assistant", tools=[ admin_tool.as_tool(is_enabled=is_admin), basic_tool, ], ) ``` 🏗 Building it into production ・Gate premium feature tools based on SaaS plan tiers ・Control tool access by user role (admin/member/viewer) ・Integrate with feature flags for A/B testing or canary releases of new capabilities ・Optimize toolsets based on context (region, time of day, etc.) 💡 Use cases 🔐 Restricting operational tools to administrators only 💎 Offering advanced tools exclusively to paid-plan users 🚀 Feature flag-driven gradual rollouts 🌏 Switching available services by region ⚠️ Watch out When `is_enabled` is `False`, the tool is not presented to the model at all, so the model has no awareness it exists. While effective for security, if you want to inform users that a feature is unavailable, you'll need a separate messaging mechanism. ✨ Deliver the optimal agent experience for each user with conditional tool enabling. #OpenAIAgentSDK# #AIAgent#
Show more
# 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#
Show more