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
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 Customize where your traces go. Send alongside OpenAI to Langfuse or Datadog, or replace the backend entirely -- seamlessly integrate with your existing observability stack. Custom processors give you full control over trace routing, transformation, and filtering. 📌 Title: Tracing -- Custom processors / Ecosystem 🔗 URL: 🧩 Overview The OpenAI Agent SDK's tracing is fully extensible through custom processors. Use `add_trace_processor()` to add custom processing alongside the OpenAI backend, or `set_trace_processors()` to completely replace the destination with Langfuse, Datadog, MLflow, Arize, or Braintrust. Even when using non-OpenAI models, `set_tracing_export_api_key()` enables free trace visualization. 🛠 How to Use Import `add_trace_processor` and `TracingProcessor` from `agents`. Define a `MyProcessor` class extending `TracingProcessor` with `on_trace_start`, `on_trace_end`, `on_span_start`, `on_span_end`, and `shutdown` methods. Access ` `trace.duration_ms`, and ` for trace data. Register with `add_trace_processor(MyProcessor())` to run custom processing alongside the OpenAI backend. 🏗 Practical Usage Patterns **Parallel Export with add_trace_processor()** Keep the OpenAI Traces dashboard while also sending data to your own observability platform. Extend `TracingProcessor` to create a `DatadogProcessor`. In `on_trace_start`, call `dd_client.start_span(operation_name="agent.trace", resource= In `on_trace_end`, call `dd_client.finish_span(metadata={"duration_ms": trace.duration_ms})`. In `on_span_start`, use `operation_name=f"agent.{span.type}"`. In `shutdown`, call `dd_client.flush()`. Register with `add_trace_processor(DatadogProcessor(dd_client))` to send traces to Datadog in parallel with OpenAI. **Complete Backend Replacement with set_trace_processors()** When you don't want traces going to OpenAI, replace the processor entirely. Import `set_trace_processors` from `agents` to completely replace the trace destination. Use `set_trace_processors([LangfuseTracingProcessor()])` for Langfuse, `[MLflowTracingProcessor()]` for MLflow, `[ArizeTracingProcessor()]` for Arize, or `[BraintrustTracingProcessor()]` for Braintrust. This replaces all existing processors including the OpenAI backend. **Free Traces for Non-OpenAI Models with set_tracing_export_api_key()** Use trace visualization for free even when running non-OpenAI models (Gemini, Claude, etc.). Import `set_tracing_export_api_key` from `agents` and call `set_tracing_export_api_key("your-tracing-export-key")`. This enables free trace visualization even when using non-OpenAI models like Gemini or Claude. **Combining Multiple Processors** In production, it's common to send traces to multiple observability tools. Pass multiple processors as a list to `set_trace_processors`: `LangfuseTracingProcessor()` for detailed LLM analytics, `DatadogProcessor(dd_client)` for infrastructure monitoring integration, and `CustomAuditProcessor()` for internal audit logging -- all running simultaneously. 💡 Use Cases 📡 Use add_trace_processor() to send traces to Datadog in parallel while keeping the OpenAI dashboard 🔀 Switch destinations entirely to Langfuse/MLflow/Arize/Braintrust with set_trace_processors() 🆓 Visualize non-OpenAI model (Gemini, Claude) traces for free with set_tracing_export_api_key() 🔧 Build production observability pipelines combining multiple processors (Langfuse + Datadog + audit logs) ⚠️ Caveats - `set_trace_processors()` **replaces all** existing processors, including the OpenAI backend. Use `add_trace_processor()` if you want to keep it. - Always implement the `shutdown()` method in custom processors to flush any buffered data. - Multiple processors add overhead to trace delivery. Consider asynchronous sending to minimize impact. ✨ Custom processors let you pipe trace data directly into your existing observability stack. Start with add for parallel export, then optimize destinations with set once you're confident! #OpenAIAgentSDK# #AIAgent#
Show more
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 See what's happening inside your agents. Built-in tracing captures every LLM call, tool execution, handoff, and guardrail evaluation in your agent flow. Tracing is enabled by default. Visualize agent behavior in the Traces dashboard to accelerate debugging and quality improvement. 📌 Title: Tracing 🔗 URL: 🧩 Overview The OpenAI Agent SDK's built-in tracing automatically records every step of agent execution -- LLM calls, tool executions, handoffs, and guardrail evaluations. It's enabled by default and visualized in OpenAI's Traces dashboard. Group related runs with `with trace("name")`, ensure trace delivery in worker environments with `flush_traces()`, and control privacy with `RunConfig(trace_include_sensitive_data=False)` or environment variables. 🛠 How to Use Import `Agent`, `Runner`, and `trace` from `agents`. Create an `Agent` and run it with ` "What are the latest AI trends?")` -- tracing is automatically enabled by default, recording all LLM calls and tool executions. 🏗 Practical Usage Patterns **Grouping Related Runs with trace()** Bundle multiple agent runs into a single trace for a bird's-eye view of the entire workflow. Import `trace` from `agents` and wrap multiple ` calls inside a `with trace("Joke workflow"):` block. The joke generation, evaluation, and conditional improvement flow are grouped into a single trace for end-to-end visibility in the dashboard. **Reliable Trace Delivery with flush_traces()** In Celery/RQ/FastAPI background workers, flush traces before the process exits. Import `flush_traces` from `agents`. In Celery tasks, call `flush_traces()` after ` message))` to send traces. In FastAPI, call `flush_traces()` in the `@app.on_event("shutdown")` hook to guarantee trace delivery before process exit. **Privacy Controls for Sensitive Data** Control tracing in ZDR (Zero Data Retention) environments or when handling personal information. Pass `run_config=RunConfig(trace_include_sensitive_data=False)` to ` (the default is `True`) to omit LLM inputs/outputs and function call data from traces; the default can also be flipped with the `OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA` environment variable. To disable tracing entirely, set `OPENAI_AGENTS_DISABLE_TRACING=1` or pass `RunConfig(tracing_disabled=True)`. 💡 Use Cases 📊 Visualize LLM/tool/handoff/guardrail flows in the Traces dashboard with zero-config default tracing 🔗 Group multiple agent runs under with trace("Joke workflow") for end-to-end workflow visibility 🔄 Call flush_traces() in Celery/RQ/FastAPI workers to guarantee trace delivery before process exit 🔒 Protect medical/financial data privacy with trace_include_sensitive_data=False ⚠️ Caveats - Tracing is on by default, so sensitive data may inadvertently appear in traces. Review `trace_include_sensitive_data` settings for production environments. - `flush_traces()` is a blocking operation. Call it in shutdown hooks or task completion, not in the critical request path. - Trace data is sent to OpenAI. For compliance requirements, disable with `OPENAI_AGENTS_DISABLE_TRACING=1` or redirect with custom processors (see next section). ✨ Built-in tracing's greatest strength is "it just works with zero config." Start by checking the dashboard as-is, then add workflow grouping and privacy controls as needed! #OpenAIAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Struggling to keep track of your complex multi-agent setup in your head? draw_graph lets you visualize your agent architecture as a Graphviz diagram, giving you the full picture at a glance. 📌 Title: Agent Visualization with draw_graph 🔗 URL: 🧩 Overview Simply call `draw_graph(agent)` to render a Graphviz graph showing the relationships between agents, tools, and handoffs. Agents appear as yellow rectangles, tools as green ellipses, and MCP servers in grey. Handoffs are shown as solid arrows, tool connections as dotted lines, and MCP connections as dashed lines. Use `.view()` to open in a browser or `filename=` to save to a file. 🛠 How to use it ```python # Install with viz extras # pip install "openai-agents[viz]" from agents import Agent, function_tool from agents.extensions.visualization import draw_graph @function_tool def search(query: str) -> str: return "results" sub_agent = Agent(name="Researcher", tools=[search]) main_agent = Agent( name="Coordinator", handoffs=[sub_agent], ) # Draw and open in browser graph = draw_graph(main_agent) graph.view() # Save to file draw_graph(main_agent, filename="agent_graph") ``` 🏗 Building it into production ・Auto-generate graphs in CI/CD pipelines and store as documentation artifacts ・Use during code review to visually verify agent configuration changes ・Leverage for onboarding new team members with system architecture overviews ・Compare before/after graphs to detect unintended handoff additions or removals 💡 Use cases 🗺 Auto-generating architecture docs for multi-agent systems 👥 Sharing and reviewing agent configurations across teams 🐛 Detecting circular handoff references or orphaned tools 📊 Creating system diagrams for project proposals ⚠️ Watch out Requires `pip install "openai-agents[viz]"` for additional dependencies, and the Graphviz binary must also be installed on your system. For very large agent configurations, the resulting graph may become overly complex. ✨ Make your agent architecture visible and understandable with draw_graph. #OpenAIAgentSDK# #AIAgent#
Show more
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 Don't expose all MCP tools blindly -- use filters, prompts, and caching for smart control. From permission scoping to dynamic filtering, here are patterns for safe and fast MCP usage. Minimize permissions with tool filters, fetch dynamic instructions via prompts, and reduce latency with caching -- three features that take MCP operations to production grade. 📌 Title: MCP -- Tool filtering / Prompts / Caching 🔗 URL: 🧩 Overview Passing all MCP server tools directly to an agent risks unnecessary tool calls and permission overreach. Use `create_static_tool_filter` to statically restrict allowed tools, or dynamic filter functions to conditionally expose tools based on runtime context (role, tenant, etc.). Fetch dynamic instructions from MCP servers with `get_prompt`, improve latency by caching the tool list with `cache_tools_list=True`, and clear the cache with `invalidate_tools_cache()` when tools change. 🛠 How to Use Import `MCPServerStreamableHttp` and `create_static_tool_filter` from `agents.mcp`. Pass `create_static_tool_filter(allowed_tool_names=["read_file", "write_file"])` to the `tool_filter` parameter of `MCPServerStreamableHttp` to restrict the agent to only `read_file` and `write_file` tools. 🏗 Practical Usage Patterns **Permission Scoping with create_static_tool_filter** Restrict available tools to the minimum required for each agent's role. For a read-only agent, create a filter with `create_static_tool_filter(allowed_tool_names=["read_file", "search_docs", "list_files"])` and pass it to `MCPServerStreamableHttp`'s `tool_filter`. For full access, set `allowed_tool_names=["read_file", "write_file", "delete_file", "search_docs"]`. The same MCP server can expose different tool sets depending on the agent's role. **Dynamic Filter to Hide danger_ Tools** Dynamically hide dangerous tools based on agent role. Import `ToolFilterContext` from `agents.mcp` and define a `role_based_filter` function. When ` is `"CodeReviewer"` and `"danger_")`, return `False` to hide the tool; otherwise return `True`. Pass this function to `MCPServerStreamableHttp`'s `tool_filter` for dynamic role-based tool filtering. **Dynamic Instructions from MCP Server with get_prompt** Fetch prompts from the MCP server to dynamically compose agent instructions. Create an `MCPServerStreamableHttp` and use it in an `async with mcp:` context. Call `prompt_result = await mcp.get_prompt("operation_guidelines")` to fetch a prompt from the MCP server (an optional second argument takes a dict of prompt arguments), then embed `prompt_result.messages[0].content.text` into the agent's `instructions` to dynamically compose agent behavior. **Latency Improvement with cache_tools_list** Cache the tool list to reduce unnecessary requests to the MCP server. Set `cache_tools_list=True` on `MCPServerStreamableHttp` to cache the tool list and reduce unnecessary requests to the MCP server. When tools are added or changed, call `await mcp.invalidate_tools_cache()` to clear the cache. 💡 Use Cases 🔒 Enforce least-privilege with create_static_tool_filter allowing only read_file/write_file 🎭 Hide danger_ tools from CodeReviewer with dynamic filters for role-based access control 📜 Fetch latest operational guidelines from MCP server via get_prompt for dynamic agent instructions ⚡ Enable cache_tools_list=True to reduce repeated tool-list fetch latency ⚠️ Caveats - Typos in `allowed_tool_names` won't raise errors -- the non-existent tool name is simply ignored. Double-check your tool names. - Dynamic filters run on every tool list retrieval, so avoid heavy logic that could impact latency. - With `cache_tools_list=True`, changes to tools won't be reflected until you call `invalidate_tools_cache()`. ✨ Combine filters, prompts, and caching to improve MCP tool safety, flexibility, and performance simultaneously. Start with static filters for permission scoping, then add dynamic filters and caching as needed! #OpenAIAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Are massive tool outputs eating up your context window? ToolOutputTrimmer automatically trims older tool outputs, keeping your context lean and efficient. 📌 Title: Tool Output Trimmer Extension 🔗 URL: 🧩 Overview `ToolOutputTrimmer` works as a `CallModelInputFilter`, trimming tool outputs in conversation history using a sliding window approach. Recent turns (default 2) are preserved as-is, while older turns with outputs exceeding `max_output_chars` (default 500) are truncated to just the first `preview_chars` (default 200). It operates non-destructively using shallow copies, leaving the original messages untouched. 🛠 How to use it ```python from agents import RunConfig from agents.extensions.tool_output_trimmer import ToolOutputTrimmer # Use with defaults trimmer = ToolOutputTrimmer() # Custom configuration trimmer = ToolOutputTrimmer( recent_turns=3, # Keep last 3 turns intact max_output_chars=1000, # Trim outputs over 1000 chars preview_chars=300, # Keep first 300 chars as preview trimmable_tools=["search", "fetch_page"], # Only trim specific tools ) # Apply via RunConfig config = RunConfig(call_model_input_filter=trimmer) result = await "question", run_config=config) ``` 🏗 Building it into production ・Apply to tools that return large text payloads (search, web fetch, etc.) ・Use `trimmable_tools` to selectively target tools while preserving critical outputs ・Tune `recent_turns` based on how much recent context your agent needs for reasoning ・Non-destructive design allows inspecting original messages during debugging 💡 Use cases 🔍 Optimizing context in RAG pipelines with large search results 📄 Managing long web page fetch outputs efficiently 🔄 Reducing token consumption in multi-turn conversations 💰 Cutting API costs through effective context window utilization ⚠️ Watch out Trimming removes detail from older turns, so if your agent needs to reference past tool outputs, set `recent_turns` high enough. When `trimmable_tools` is not specified, all tools are subject to trimming. ✨ Keep your context window lean and your agents sharp with ToolOutputTrimmer. #OpenAIAgentSDK# #AIAgent#
Show more
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 No need to host your own MCP server -- OpenAI-hosted MCP tools get you started immediately. From repo investigation with DeepWiki to Google Calendar integration, all with minimal code. Hosted MCP server tools are managed by OpenAI, so you can integrate MCP capabilities into your agents without building any infrastructure. 📌 Title: MCP -- Hosted MCP server tools 🔗 URL: 🧩 Overview Hosted MCP server tools let you use OpenAI-hosted MCP servers directly as agent tools. Simply specify the server URL via `HostedMCPTool` and your agent gains access to external services like DeepWiki (repository documentation search) or Google Calendar. Use `require_approval` to control pre-execution approval flows, and `on_approval_request` to combine auto-approval with human escalation. 🛠 How to Use Import `Agent`, `Runner`, and `HostedMCPTool` from `agents`. Pass a `HostedMCPTool` to the agent's `tools`, setting `tool_config` with `type` as `"mcp"`, `server_label` as `"deepwiki"`, `server_url` as `""`, and `require_approval` as `"never"`. Run with ` "What are the key features of openai/openai-agents-python?")` and retrieve the result via ` 🏗 Practical Usage Patterns **Repo Investigation with DeepWiki in Minimal Code** No need to manually ingest OSS documentation -- investigate repository structure and features through DeepWiki MCP. Create an `Agent` with `name="OSSAnalyzer"` and investigation-focused `instructions`, passing a `HostedMCPTool` in `tools` with `server_label="deepwiki"`, `server_url=""`, and `require_approval="never"`. This gives you a repo investigation agent with minimal setup. **Safe Auto-Approval with require_approval + on_approval_request** Auto-approve read operations while escalating write operations to humans. Import `HostedMCPTool`, `MCPToolApprovalRequest`, and `MCPToolApprovalFunctionResult` from `agents`. Define a `smart_approval(request: MCPToolApprovalRequest) -> MCPToolApprovalFunctionResult` function that checks ` against a set of safe tools like `{"read_file", "search", "list_events", "get_event"}` -- returning `{"approve": True}` for auto-approval, or calling `ask_human_via_slack` for write tools and returning `{"approve": False, "reason": "..."}` when denied. Set `require_approval="always"` in the `tool_config` and pass `on_approval_request=smart_approval` to `HostedMCPTool`, creating a flow where reads are auto-approved and writes escalate to humans. **Authenticated Service Connection with connector_id** For services requiring authentication like Google Calendar, pass connector_id and auth tokens. Pass a `HostedMCPTool` to the agent's `tools` with `server_label="google_calendar"` in the `tool_config`. For connector-backed servers, use `connector_id="connector_googlecalendar"` instead of `server_url`, and supply the access token via `authorization=os.environ["GOOGLE_CALENDAR_AUTHORIZATION"]`. This builds an OAuth-authenticated Google Calendar integration agent. 💡 Use Cases 🔍 Investigate OSS repo structure and features with DeepWiki + HostedMCPTool in minimal code 🛡 Auto-approve reads, escalate writes to humans with require_approval="always" + on_approval_request 📅 Build a scheduling assistant with connector_id + OAuth tokens for Google Calendar integration 🤖 Combine multiple Hosted MCP tools in a single agent for multi-service orchestration ⚠️ Caveats - Hosted MCP servers are hosted by OpenAI, so latency depends on network conditions. Configure timeouts appropriately. - Use `require_approval="never"` only for read-only services. Always implement approval flows for services with write capabilities. - OAuth token expiry management is your responsibility. Build in refresh token mechanisms. ✨ With Hosted MCP tools, you can start integrating external services without worrying about MCP server infrastructure. Try repo investigation with DeepWiki first, then gradually add approval flows and auth integrations! #OpenAIAgentSDK# #AIAgent#
Show more
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 Make your agent's token spending visible. Track usage at every level -- from total cost per tenant to per-step breakdown monitoring. The Usage API lets you capture total token consumption for an entire run and drill down into per-step breakdowns for tool calls, handoffs, and guardrails. 📌 Title: Usage 🔗 URL: 🧩 Overview The OpenAI Agent SDK's Usage feature tracks token consumption across agent runs. `result.context_wrapper.usage` gives you total tokens for the entire run, while `result.context_wrapper.usage.request_usage_entries` provides per-step breakdowns (tool calls, handoffs, guardrails). You can use RunHooks' `on_agent_end` for real-time logging, and enable usage reporting for third-party model adapters with `ModelSettings(include_usage=True)`. 🛠 How to Use Create an agent with `Agent(name="Assistant", instructions="Answer user questions.")` and run `result = await "Tell me about quantum computing")`. Access total, input, and output tokens via ` `result.context_wrapper.usage.input_tokens`, and `result.context_wrapper.usage.output_tokens`. Loop through `result.context_wrapper.usage.request_usage_entries` to see per-request breakdowns with `entry.input_tokens` and `entry.output_tokens`. 🏗 Practical Usage Patterns **Per-Tenant/User Cost Calculation** Record "how much each tenant spent" for billing and budget management in SaaS applications. In a `handle_request(tenant_id, user_id, message)` function, run `result = await message)`, compute cost with `calculate_cost(model="gpt-4.1", input_tokens=result.context_wrapper.usage.input_tokens, output_tokens=result.context_wrapper.usage.output_tokens)`, and record it with `await billing_db.record(tenant_id=tenant_id, user_id=user_id, total_tokens= cost_usd=cost, timestamp= **Per-Step Monitoring** Use `request_usage_entries` to identify which tool calls or handoffs consume the most tokens. After `result = await "Generate a sales report")`, loop through `result.context_wrapper.usage.request_usage_entries` with `enumerate` to check each step's `entry.input_tokens` and `entry.output_tokens`. Flag steps where `entry.input_tokens > 5000` with a warning to identify token-heavy operations. **Real-time Logging with RunHooks** Use `on_agent_end` hook to log usage when each agent completes. Create a `UsageLoggingHooks` class extending `RunHooks` with an `on_agent_end(self, context: RunContextWrapper, agent: Agent, output)` method that reads `context.usage` and logs with `"agent_completed", agent_name= total_tokens= ...)`. Pass it via `await "question", hooks=UsageLoggingHooks())`. **Enabling Usage for Third-party Models** When using non-OpenAI model adapters, explicitly enable usage reporting. For third-party models, explicitly enable usage reporting with `Agent(name="ThirdPartyAgent", instructions="...", model=my_custom_model_adapter, model_settings=ModelSettings(include_usage=True))`. 💡 Use Cases 💰 Record per-tenant/user token consumption in a database to build usage-based billing 📊 Visualize per-step token consumption with request_usage_entries to identify cost optimization bottlenecks 🔔 Log usage via RunHooks on_agent_end for real-time dashboard monitoring 🔌 Enable ModelSettings(include_usage=True) for third-party models to ensure usage tracking coverage ⚠️ Caveats - ` includes retries and guardrail re-executions, so it may be higher than the visible step count suggests. - Third-party models may return zero usage without `include_usage=True`. Check your adapter's documentation. - Cost calculations depend on model pricing. Ensure you accurately reflect per-model input/output token rates. ✨ Track token usage at three levels -- total, per-step, and via hooks -- and you'll have cost management and quality monitoring fully covered. Start with result.context_wrapper.usage, then add step-level and hook-based tracking as needed! #OpenAIAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Does your agent's conversation history contain sensitive data stored in plaintext? EncryptedSession protects conversation data with Fernet encryption and supports TTL-based auto-expiration. 📌 Title: Encrypted Session (EncryptedSession) 🔗 URL: 🧩 Overview `EncryptedSession` is a drop-in wrapper that encrypts conversation data for any session backend passed as `underlying_session`. It uses Fernet encryption with HKDF per-session key derivation (info string `"agents.session-store.hkdf.v1"`, session ID as salt), ensuring cryptographic isolation between sessions. Items older than `ttl` (default 600 seconds) are silently skipped on retrieval. Provide a high-entropy master key such as `Fernet.generate_key()` output — raw strings are still accepted for compatibility, but passwords and other low-entropy secrets are unsuitable. 🛠 How to use it ```python import os from cryptography.fernet import Fernet from agents import SQLiteSession from agents.extensions.memory import EncryptedSession # Wrap a base session with encryption base_session = SQLiteSession("chat-001", "sessions.db") # Use a high-entropy master key, e.g. generated with Fernet encryption_key = Fernet.generate_key().decode("ascii") encrypted = EncryptedSession( session_id="chat-001", underlying_session=base_session, encryption_key=encryption_key, ttl=3600, # Expire after 1 hour (default is 600 seconds) ) # For persistent storage, load and reuse the same stored key encrypted = EncryptedSession( session_id="chat-001", underlying_session=base_session, encryption_key=os.environ["SESSION_ENCRYPTION_KEY"], ttl=7200, ) # Use the same interface as any other session items = await encrypted.get_items() ``` 🏗 Building it into production ・Meet compliance requirements in regulated industries like healthcare and finance ・HKDF derives unique keys per session, so one session's compromise doesn't affect others ・Use TTL for "cryptographic data erasure" — data becomes unrecoverable after expiration ・Wraps existing SQLiteSession / RedisSession with zero migration cost 💡 Use cases 🏥 Encrypted storage for conversations containing medical information 🏦 Security hardening for agents handling financial data 🔐 GDPR "right to be forgotten" compliance via TTL expiration 🛡 Inter-session data isolation in multi-tenant environments ⚠️ Watch out Install the `encrypt` extra first: `pip install 'openai-agents[encrypt]'`. Content search methods like `find_turns_by_content()` don't work on encrypted data. If search is needed, maintain a separate search index. Also, losing the encryption key makes data permanently unrecoverable — secure key management (e.g., Secret Manager) is essential. Changing `encryption_key` does not re-encrypt stored records, so existing data still requires the original key. ✨ With EncryptedSession, protect conversation data with just one line of code. #OpenAIAgentSDK# #AIAgent#
Show more
# Practical and Useful Patterns for OpenAI Agent SDK 🌍 Inject what your agent needs with type safety! Local context lets you pass user info, loggers, and data fetchers like dependency injection. 📌 Title: Context management – Local context 🔗 URL: 🧩 Overview The OpenAI Agent SDK's local context feature provides type-safe dependency injection for agents and tools. By passing a Pydantic model or dataclass via the `context` parameter, tool functions can access user information, loggers, and external service clients. The generic type `Agent[UserInfo]` enables compile-time detection of context type mismatches. 🛠 Usage Define a `UserInfo` dataclass with `uid`, `name`, and `is_premium` fields, then use `@tool`-decorated functions that accept `ToolContext[UserInfo]`. For example, `get_recommendations(wrapper: ToolContext[UserInfo], category: str)` accesses user info via `wrapper.context` and returns premium or regular recommendations based on ` A `debug_tool` can access `wrapper.tool_name`, `wrapper.tool_call_id`, and `wrapper.tool_arguments` for debugging. Define the agent with the generic type `Agent[UserInfo]` as `Agent(name="personal_assistant", instructions="Personalize responses for the user", tools=[get_recommendations, debug_tool])`. At runtime, create `UserInfo(uid="u_12345", name="Alice", is_premium=True)` and pass it via `await "Recommend some books", context=user)`. For a more practical setup, bundle dependencies into an `AppContext` dataclass with `user: UserInfo`, `logger: logging.Logger`, `db: DatabaseClient`, and `feature_flags: dict[str, bool]`. In `fetch_order_history(wrapper: ToolContext[AppContext], limit: int = 10)`, access context via `ctx = wrapper.context`, log with ` branch on `ctx.feature_flags.get("new_order_api")`, and query with `ctx.db.get_orders(ctx.user.uid, limit)`. Define the agent as `Agent[AppContext]` with `Agent(name="order_assistant", tools=[fetch_order_history])`. 🏗 Practical Patterns The greatest value of local context is keeping tool functions as pure business logic. Instead of referencing user info or DB clients through global variables, injecting them via context dramatically improves testability — just pass a mock context in tests. `ToolContext`'s `tool_name`, `tool_call_id`, and `tool_arguments` are essential for structured logging. You can trace exactly which tool was called with which arguments, making production debugging straightforward. Using the generic type `Agent[UserInfo]` lets type checkers (mypy, etc.) detect context type mismatches. For example, passing an `AppContext` to an `Agent[UserInfo]` triggers a compile error, preventing runtime failures. Passing feature flags and configuration values through context is also effective. You can control environment-specific behavior through context values without changing code. 💡 Use Cases 👤 Personalization based on premium/free user tiers 📝 Structured logging and tracing with tool_call_id 🧪 Unit testing with mock context injection 🚩 Feature flag-driven tool behavior switching ⚠️ Caveats - Including secrets (API keys, etc.) in context risks leakage during state serialization - Context objects are shared during execution — be careful with mutable state and thread safety - `Agent[T]` generic type checking depends on static analysis tools; it's not enforced at runtime - Putting large objects (bulk data, etc.) in context degrades memory efficiency ✨ Local context enables clean-architecture, testable agents with proper dependency injection! #OpenAIAgentSDK# #AIAgent#
Show more
# Useful but Little-Known Features of OpenAI Agent SDK 🌍 Ever wished you could go back in a conversation and try "what if I'd said something different?" AdvancedSQLiteSession's conversation branching lets you fork from any point in the history and explore alternative paths. 📌 Title: AdvancedSQLiteSession Conversation Branching 🔗 URL: 🧩 Overview `AdvancedSQLiteSession` supports branching conversations from specific turns or content matches. `create_branch_from_turn(turn_number)` forks from a specific turn, while `create_branch_from_content(search_term)` forks from a turn containing the search term. You can manage branches with `list_branches()`, `switch_to_branch()`, and `delete_branch()`. 🛠 How to use it ```python from agents.extensions.memory import AdvancedSQLiteSession session = AdvancedSQLiteSession( session_id="chat-001", db_path="sessions.db", create_tables=True, # Defaults to False; required to create the branch tables ) # Create a branch from turn 3 branch_id = await session.create_branch_from_turn(turn_number=3) # Create a branch from a turn containing specific content branch_id = await session.create_branch_from_content("API design discussion") # Manage branches branches = await session.list_branches() await session.switch_to_branch(branch_id) await session.delete_branch(branch_id, force=True) # force=True to delete the current branch ``` 🏗 Building it into production ・When users want to retry, create a branch from the previous turn for a fresh attempt ・In agent evaluation, compare multiple response paths for the same input ・In customer support, explore different solutions in parallel and pick the best one ・Use branches as conversation checkpoints to record important decision points 💡 Use cases 🔀 "What-if" analysis on conversations 🧪 A/B testing agent response quality 🎯 Parallel exploration of multiple solution paths 📝 Checkpoint management for conversation history ⚠️ Watch out Storage usage grows as branches accumulate. Regularly clean up unused branches with `delete_branch()` (pass `force=True` to delete the current branch; `main` cannot be deleted). Branch IDs are unique for the lifetime of a session ID and are not released by deleting a branch or clearing the session, so use a new name for each new branch. Also, manage branch labels carefully to avoid context confusion when switching between branches. ✨ With conversation branching, add time-travel capabilities to your agent interactions. #OpenAIAgentSDK# #AIAgent#
Show more