OpenAI Agents SDK Guide (2026) | Build Production AI Agents with the OpenAI Agents SDK
Introductionβ
OpenAI's Agents SDK is a lightweight, production-ready framework for building AI agents that can use tools, hand off tasks to other agents, apply guardrails, keep workflow state, and expose traces for debugging. Released in 2025 as the production successor to OpenAI's earlier Swarm prototype, the SDK has quickly become one of the most popular agent frameworks, with approximately 22,000 GitHub stars as of 2026.
The OpenAI Agents SDK occupies a specific niche in the agent framework landscape: production-grade single-agent loops with handoffs. Where CrewAI is role-based and LangGraph is graph-based, the OpenAI Agents SDK is the OpenAI-native production framework for ReAct-style loops with delegation.
This guide explains what the OpenAI Agents SDK is, how its architecture works, what core concepts it provides, and how to use it for building production AI agents. It also covers the SDK's relationship to the broader OpenAI ecosystem, practical workflows, comparisons with other frameworks, and guidance for choosing the right tools for your project.
What Is the OpenAI Agents SDK?β
The OpenAI Agents SDK is an open-source MIT-licensed Python and TypeScript framework from OpenAI for building agent applications. It is a lightweight yet powerful framework for building multi-agent workflows, and it is provider-agnostic, supporting the OpenAI Responses and Chat Completions APIs, as well as 100+ other LLMs from other providers.
The Evolution from Swarmβ
The SDK is the production successor to Swarm, an experimental prototype OpenAI released in October 2024. Swarm demonstrated the conceptual model of agents with handoffs but lacked tracing, guardrails, and production guarantees. The OpenAI Agents SDK brought the same conceptual model plus the production primitives teams needed: built-in tracing, input and output guardrails, structured outputs, sessions, and a clear runner abstraction.
A Code-First Frameworkβ
The OpenAI Agents SDK is a code-first framework. It is best suited for developers building multi-step agent workflows, not for teams looking for a purely visual no-code agent builder. It is closer to an agent runtime and orchestration framework for developers.
Core Primitivesβ
The SDK is built around a small, opinionated set of primitives:
| Primitive | Purpose |
|---|---|
| Agent | An LLM configured with instructions, tools, guardrails, and handoffs |
| Handoff | Delegation to another agent |
| Guardrail | An input or output validator |
| Runner | The execution loop |
| Session | A persistent conversation |
| Tools | Functions, MCP servers, and hosted tools |
| Tracing | Built-in tracking of agent runs |
Why the OpenAI Agents SDK Existsβ
The Agent Framework Warsβ
The 2024 agent framework wars produced a long list of frameworks with overlapping primitives and confusing APIs. The OpenAI Agents SDK landed with a small, opinionated surface: agents, handoffs, guardrails, runner, session. The simplicity is the value proposition.
First-Party Tracingβ
OpenAI shipped first-party tracing with the SDK. The default Traces dashboard renders agent runs as nested span trees with model calls, tool calls, and handoff transitions visible at a glance. For teams that already pay for OpenAI, the trace surface is includedβno separate observability vendor required. For teams that prefer their own backend, the SDK accepts a custom trace processor.
The Responses APIβ
The Responses API gave OpenAI's newest features a coherent path into agent applications: Reasoning models with deep thinking, the Computer Use tool, the File Search built-in tool, the Web Search built-in tool. The SDK is the recommended way to use these features.
OpenAI Agents SDK Architectureβ
The OpenAI Agents SDK provides a clean separation between the agent harness and the compute environment. The architecture is organized around a small set of core components that work together to orchestrate agent workflows.
Architecture Overviewβ
User Input
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Runner β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β Agent β β
β β βββββββββββββ βββββββββββββ βββββββββββ β β
β β β Model β β Tools β β Handoffsβ β β
β β β + β β + β β + β β β
β β βInstructionsβ β Guardrailsβ βSessions β β β
β β βββββββββββββ βββββββββββββ βββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
β β Tracing β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
Final Output
Component Layersβ
- Input Layer: User request enters the system
- Runner Layer: Orchestrates the agent loop, manages state, and handles streaming
- Agent Layer: The core unit containing model, instructions, tools, and runtime behavior
- Tool Layer: Functions, MCP servers, and hosted tools that agents can call
- Orchestration Layer: Handoffs and agent-as-tool patterns for multi-agent workflows
- Guardrail Layer: Input and output validation
- Tracing Layer: Built-in observability and debugging
Core Conceptsβ
Agentsβ
An agent is the core unit of an SDK-based workflow. It packages a model, instructions, and optional runtime behavior such as tools, guardrails, MCP servers, handoffs, and structured outputs.
Key agent properties:
| Property | Purpose |
|---|---|
name | Human-readable identity in traces |
instructions | The job, constraints, and style for that agent |
model | Choosing the model and tuning behavior |
tools | Capabilities the agent can call directly |
handoffs | Delegating to another agent |
handoffDescription | Hinting when another agent should delegate here |
outputType | Returning structured output instead of plain text |
guardrails | Validation, blocking, and review flows |
Best practice: Start with one focused agent. Define the smallest agent that can own a clear task. Add more agents only when you need separate ownership, different instructions, different tool surfaces, or different approval policies.
Tool Callingβ
Tools let agents take actions. The SDK supports three primary tool types:
| Tool Type | Description |
|---|---|
| Custom tools | Python functions you define and register as tools |
| Managed tools | Built-in, hosted tools provided by OpenAI (Code Interpreter, Web Search, File Search) |
| MCP servers | Model Context Protocol servers for external capabilities |
Tool configuration example:
const getWeather = tool({
name: "get_weather",
description: "Return the weather for a given city.",
parameters: z.object({ city: z.string() }),
async execute({ city }) {
return `The weather in ${city} is sunny.`;
},
});
const agent = new Agent({
name: "Weather bot",
instructions: "You are a helpful weather bot.",
model: "gpt-5.6",
tools: [getWeather],
});
Handoffsβ
Handoffs are a specialized tool call used by the Agents SDK for transferring control between agents. They are the clearest fit when a specialist should own the next response rather than merely helping behind the scenes.
Two orchestration patterns:
| Pattern | When to Use | What Happens |
|---|---|---|
| Handoffs | A specialist should take over the conversation | Control moves to the specialist agent |
| Agents as tools | A manager should stay in control | The manager keeps ownership of the reply |
Handoff example:
const billingAgent = new Agent({ name: "Billing agent" });
const refundAgent = new Agent({ name: "Refund agent" });
const triageAgent = Agent.create({
name: "Triage agent",
handoffs: [billingAgent, handoff(refundAgent)],
});
When to add specialists: Add specialists only when they materially improve capability isolation, policy isolation, prompt clarity, or trace legibility. Splitting too early creates more prompts, more traces, and more approval surfaces without necessarily making the workflow better.
Guardrailsβ
Guardrails are configurable safety checks for input and output validation. They can run in parallel to the agent or block execution until they complete.
Types of guardrails:
| Use Case | Start With |
|---|---|
| Block disallowed user requests before the main model runs | Input guardrails |
| Validate or redact the final output before it leaves the system | Output guardrails |
| Check arguments or results around a function tool call | Tool guardrails |
| Pause before side effects like cancellations, edits, shell commands | Human-in-the-loop approvals |
Key behaviors:
- Input guardrails run only for the first agent in the chain
- Output guardrails run only for the agent that produces the final output
- Guardrails can run in parallel (for speed) or block execution (for safety)
Input guardrail example:
const agent = new Agent({
name: "Customer support",
inputGuardrails: [{
name: "Math homework guardrail",
runInParallel: false,
async execute({ input, context }) {
const result = await run(guardrailAgent, input, { context });
return {
outputInfo: result.finalOutput,
tripwireTriggered: result.finalOutput?.isMathHomework === true,
};
},
}],
});
Human-in-the-Loopβ
Human-in-the-loop approvals pause the run so a person or policy can approve or reject a sensitive action. The model can still decide that an action is needed, but the run pauses until you approve or reject it.
Approval example:
const cancelOrder = tool({
name: "cancel_order",
description: "Cancel a customer order.",
parameters: z.object({ orderId: z.number() }),
needsApproval: true,
async execute({ orderId }) {
return `Cancelled order ${orderId}`;
},
});
Sessionsβ
Sessions provide automatic conversation history management across agent runs. They enable agents to maintain context across multiple turns and interactions.
Tracingβ
Tracing is a built-in tracking of agent runs, allowing you to view, debug, and optimize your workflows. The default Traces dashboard renders agent runs as nested span trees with model calls, tool calls, and handoff transitions visible at a glance.
Sandbox Agentsβ
Sandbox agents are preconfigured to work with a container to perform work over long time horizons. OpenAI's April 2026 update specifically framed this as a way for agents to handle longer-horizon tasks inside controlled sandbox environments.
How the OpenAI Agents SDK Worksβ
The Execution Flowβ
1. User Request
β
2. Runner Initializes
β
3. Agent Processes Request
- Applies input guardrails
- Calls model with instructions and tools
β
4. Model Reasons and Decides
- May call tools
- May hand off to another agent
β
5. Tool Execution (if applicable)
- Functions, MCP servers, or hosted tools
- May require human approval
β
6. Handoff (if applicable)
- Control transfers to specialist agent
β
7. Response Generation
- Applies output guardrails
- Returns structured or unstructured output
β
8. Tracing Records the Run
β
9. Final Output Returned
Running Agentsβ
The SDK supports three primary ways to run agents:
- Standard run: One agent, one turn
- Multi-turn run: Agent with session state
- Sandbox run: Agent in a containerized environment
Parallel Executionβ
The SDK supports parallel agent execution using Python asyncio, enabling you to "fan out" multiple specialized agents at the same time and then "fan in" their outputs to a final "meta" agent.
Parallel execution example:
responses = await asyncio.gather(
*(run_agent(agent, review_text) for agent in parallel_agents)
)
labeled_summaries = [
f"### {resp.last_agent.name}\n{resp.final_output}"
for resp in responses
]
collected_summaries = "\n".join(labeled_summaries)
final_summary = await run_agent(meta_agent, collected_summaries)
Key Featuresβ
Agent Orchestrationβ
The SDK manages the full agent lifecycle: model calls, tool execution, handoffs, guardrails, and sessions. The Runner handles the execution loop, managing turns, tools, safety measures, handoffs, and sessions.
Native Tool Callingβ
The SDK provides native support for three tool types:
- Custom Python functions registered as tools
- Managed tools hosted by OpenAI (Code Interpreter, Web Search, File Search)
- MCP servers for external capabilities
Multi-Agent Workflowsβ
The SDK supports two primary patterns for multi-agent collaboration:
| Pattern | Use Case |
|---|---|
| Handoffs | Specialists take over the conversation for their domain |
| Agents as tools | A manager stays in control and calls specialists as bounded capabilities |
Safety & Guardrailsβ
The SDK provides configurable safety checks:
- Input guardrails for user requests
- Output guardrails for final responses
- Tool guardrails for function arguments and results
- Human-in-the-loop approvals for sensitive actions
Structured Outputsβ
Agents can return structured output using Zod schemas (TypeScript) or Pydantic models (Python):
const calendarEvent = z.object({
name: z.string(),
date: z.string(),
participants: z.array(z.string()),
});
const agent = new Agent({
name: "Calendar extractor",
instructions: "Extract calendar events from text.",
outputType: calendarEvent,
});
Observabilityβ
Built-in tracing provides:
- Nested span trees of agent runs
- Model calls, tool calls, and handoff transitions
- Debugging and optimization visibility
Sessionsβ
Automatic conversation history management across agent runs enables:
- Multi-turn conversations
- Persistent context
- Stateful workflows
Sandbox Agentsβ
Containerized execution for long-running tasks enables:
- File inspection and manipulation
- Command execution
- Controlled compute environments
Realtime Voice Agentsβ
The SDK supports building powerful voice agents with gpt-realtime-2.1 and full agent features.
Provider-Agnosticβ
The SDK supports the OpenAI Responses and Chat Completions APIs, as well as 100+ other LLMs. This means you can use non-OpenAI models (including Hugging Face models) with the same agent framework.
Common Workflowsβ
Customer Support Agentβ
A support triage agent that classifies issues, looks up account data, and escalates complex cases.
Customer Request
β
Triage Agent
- Input guardrail: Block inappropriate requests
- Routes to appropriate specialist
β
Billing Agent / Technical Agent / Refund Agent
- Each with specialized tools and instructions
- May require human approval for sensitive actions
β
Final Response
Research Assistantβ
An agent that searches internal documents, summarizes findings, and hands off legal or finance-specific tasks to specialist agents.
User Question
β
Research Agent
- Uses File Search tool
- Summarizes findings
β
Specialist Handoff (if needed)
- Legal Agent for policy questions
- Finance Agent for budget questions
β
Final Synthesis
Parallel Analysisβ
Fanning out multiple specialized agents at the same time and then fanning in their outputs to a final meta-agent.
Content Input
β
ββββββββββββββββ¬βββββββββββββββ¬βββββββββββββββ
β Features β Pros/Cons β Sentiment β
β Agent β Agent β Agent β
ββββββββββββββββ΄βββββββββββββββ΄βββββββββββββββ
β β β
ββββββββββββββββ΄βββββββββββββββ
β
Meta Agent (Combines)
β
Executive Summary
Enterprise Assistantβ
An enterprise agent that accesses internal knowledge bases, business systems, and provides responses to employees.
Employee Query
β
Enterprise Agent
- Input guardrail: Validate query
- Uses File Search for internal docs
- Calls MCP servers for business systems
β
Response with Citations
Enterprise Use Casesβ
AI Customer Supportβ
Automate tier-1 support with agents that can classify issues, access knowledge bases, and escalate complex cases. Handoffs enable routing to billing, technical, or refund specialists.
Internal Knowledge Assistantsβ
Enterprise employees can query internal documentation, policies, and knowledge bases through conversational agents with RAG capabilities.
Software Engineering Automationβ
Agents that can inspect files, run commands, and work in controlled sandbox environments for code review, testing, and automation.
Business Process Automationβ
Agents that review incoming requests, prepare suggested actions, and route work through approval workflows.
Enterprise Searchβ
Semantic search across internal documents, emails, and data sources using agents with File Search and MCP integrations.
AI Research Assistantsβ
Agents that search, analyze, and synthesize information across multiple sources with handoffs to specialist agents for domain-specific tasks.
Advantagesβ
1. Official OpenAI Frameworkβ
The SDK is OpenAI's official production framework for agents, making it the natural choice for OpenAI-first stacks.
2. Lightweight and Simpleβ
The SDK has a small, opinionated surface with very few abstractions. The simplicity is the value proposition.
3. Native Tool Callingβ
First-class support for custom tools, managed tools (Code Interpreter, Web Search, File Search), and MCP servers.
4. Multi-Agent Supportβ
Two patterns for multi-agent workflows: handoffs and agents as tools. Both are built into the SDK.
5. Built-in Guardrailsβ
Configurable safety checks for input validation, output validation, and tool behavior.
6. First-Party Tracingβ
Included observability with no separate vendor required. Traces dashboard renders agent runs with model calls, tool calls, and handoff transitions.
7. Provider-Agnosticβ
Supports 100+ LLMs beyond OpenAI, including Hugging Face models.
8. Sandbox Supportβ
Containerized execution for long-running tasks and controlled compute environments.
9. Sessionsβ
Automatic conversation history management across agent runs.
10. Production-Readyβ
The SDK is the production-ready upgrade of OpenAI's previous experimentation for agents.
Limitationsβ
1. Primarily Optimized for OpenAIβ
While provider-agnostic, the SDK is most deeply integrated with OpenAI's ecosystem and the Responses API.
2. Requires Thoughtful Workflow Designβ
The SDK is a code-first framework that requires deliberate design of agents, tools, and handoffs.
3. External Memory Implementationβ
Long-term memory is not built inβit requires external storage implementation.
4. Model API Costsβ
All agent runs consume tokens and incur API costs. Multi-agent workflows can increase costs significantly.
5. Production Monitoring Remains Essentialβ
While tracing is built in, production monitoring, alerting, and evaluation require additional tooling.
6. Not Every Application Needs Multiple Agentsβ
For simple tasks, a direct API call may be more appropriate than an agent framework.
7. Learning Curveβ
Understanding handoffs, guardrails, and agent orchestration requires time and practice.
8. Limited Visual Toolingβ
The SDK is code-firstβit does not provide a visual no-code agent builder.
Pricing Overviewβ
The OpenAI Agents SDK itself is open-source and free (MIT-licensed). However, using the SDK incurs costs for:
API Usage Costsβ
- Token consumption: Every agent run consumes tokens for prompts, completions, and tool calls
- Model selection: More capable models (GPT-5.6, o-series) cost more per token
- Managed tools: Tools like Code Interpreter and Web Search may have additional usage costs
Infrastructure Considerationsβ
- Compute: Sandbox agents may require container infrastructure
- Storage: Sessions and traces may require storage
- Observability: Custom trace processors may require infrastructure
Note: For current pricing, always refer to the official OpenAI pricing page.
OpenAI Agents SDK vs Other Agent Frameworksβ
Framework Comparisonβ
| Framework | Primary Focus | Best For | Key Differentiator |
|---|---|---|---|
| OpenAI Agents SDK | Production-grade single-agent loops with handoffs | OpenAI-first stacks | Native tool calling, first-party tracing |
| LangGraph | Graph-based state machines | Complex stateful workflows | Checkpoints, cyclic workflows, human-in-the-loop |
| CrewAI | Role-based multi-agent crews | Role-based pipelines | Clean mental model of collaboration |
| AutoGen | Conversational multi-agent | Multi-agent debate and consensus | β οΈ Maintenance mode |
| Google ADK | Google-stack agent runtime | GCP-native teams | Vertex AI integration |
OpenAI Agents SDK vs LangGraphβ
| Aspect | OpenAI Agents SDK | LangGraph |
|---|---|---|
| Architecture | Lightweight, minimal boilerplate | Graph-based orchestration |
| State Management | Session-based | Checkpoint-based with time travel |
| Workflow Control | Handoffs and agents as tools | Explicit graph reasoning |
| Learning Curve | Lower | Steeper |
| Best For | Structured runtime with handoffs and tracing | Complex state machines, cyclic workflows |
When to Use Eachβ
Use the OpenAI Agents SDK when:
- You want a structured runtime with handoffs, guardrails, tracing, and tool calling out of the box
- You're building on the OpenAI ecosystem
- You need a lightweight, minimal-boilerplate framework
Use LangGraph when:
- You need complex state machines with checkpoints
- You need cyclic workflows and explicit graph reasoning
- You're already in the LangChain ecosystem
Use CrewAI when:
- You want role-based multi-agent pipelines
- You need rapid prototyping with a clean mental model
Who Should Use the OpenAI Agents SDK?β
AI Engineersβ
The SDK provides a production-ready framework for building agent applications with minimal boilerplate.
Backend Developersβ
The code-first approach integrates naturally with existing backend systems and workflows.
AI Startupsβ
The lightweight framework and built-in tracing enable rapid development and iteration.
Enterprise Teamsβ
The SDK's guardrails, human-in-the-loop approvals, and tracing support enterprise compliance and observability requirements.
Software Architectsβ
The SDK's simple primitives make it easy to design and communicate agent architectures.
Platform Engineersβ
The provider-agnostic design and MCP support enable building flexible agent platforms.
Best Practicesβ
1. Start with One Focused Agentβ
Define the smallest agent that can own a clear task. Add more agents only when you need separate ownership, different instructions, different tool surfaces, or different approval policies.
2. Add Specialists Only When the Contract Changesβ
Add specialists only when they materially improve capability isolation, policy isolation, prompt clarity, or trace legibility.
3. Keep Handoff Descriptions Short and Concreteβ
Make it clear when another agent should delegate to this specialist.
4. Use Structured Outputsβ
Return typed data rather than free-form prose when downstream code needs structured data.
5. Design Safe Guardrailsβ
- Use input guardrails to block disallowed requests before the main model runs
- Use output guardrails to validate final output before it leaves the system
- Use human-in-the-loop approvals for sensitive actions like cancellations or shell commands
6. Use Parallel Execution When Appropriateβ
"Fan out" multiple specialized agents at the same time and "fan in" their outputs to a final meta-agent to reduce latency.
7. Log and Monitor All Tool Callsβ
Tracing is built inβuse it to debug and optimize workflows.
8. Choose the Right Orchestration Patternβ
- Use handoffs when a specialist should take over the conversation
- Use agents as tools when a manager should stay in control and call specialists as bounded capabilities
9. Validate Before and Afterβ
Use guardrails both before and after agent execution to ensure safe, reliable behavior.
10. Combine with RAGβ
For applications requiring external knowledge, combine the SDK with retrieval-augmented generation using the File Search tool.
Frequently Asked Questionsβ
What is the OpenAI Agents SDK?β
The OpenAI Agents SDK is an open-source MIT-licensed Python and TypeScript framework from OpenAI for building agent applications. It provides a lightweight, production-ready framework for building AI agents that can use tools, hand off tasks to other agents, apply guardrails, and keep workflow state.
Is the OpenAI Agents SDK open source?β
Yes. The SDK is open-source under the MIT license.
Does the SDK support Tool Calling?β
Yes. The SDK supports custom Python functions, managed tools (Code Interpreter, Web Search, File Search), and MCP servers.
What are Handoffs?β
Handoffs are a specialized tool call used by the Agents SDK for transferring control between agents. They are the clearest fit when a specialist should own the next response.
What are Guardrails?β
Guardrails are configurable safety checks for input and output validation. They can run in parallel to the agent or block execution until they complete.
Can it build multi-agent systems?β
Yes. The SDK supports two primary patterns for multi-agent collaboration: handoffs (specialists take over the conversation) and agents as tools (a manager stays in control).
How does it compare with LangGraph?β
The OpenAI Agents SDK is a lightweight, minimal-boilerplate framework. LangGraph is a graph-based orchestration framework for complex state machines and cyclic workflows. Choose the SDK for structured runtime with handoffs and tracing; choose LangGraph for complex state machines.
Is it suitable for enterprise applications?β
Yes. The SDK includes guardrails, human-in-the-loop approvals, tracing, and sessionsβall supporting enterprise compliance and observability requirements.
Related OpenAI Agents SDK Guidesβ
- OpenAI Agents SDK Tutorial β Step-by-step guide to building your first agent
- Tool Calling Guide β Deep dive into tools, MCP, and managed tools
- Handoffs Guide β Multi-agent orchestration with handoffs
- Guardrails Guide β Safety and validation for production agents
- Deployment Guide β Production deployment and scaling
Related AI Tool Guidesβ
Related Categoriesβ
Related Foundationsβ
Conclusionβ
The OpenAI Agents SDK has established itself as one of the leading frameworks for building production AI agents. With approximately 22,000 GitHub stars and growing adoption across startups and enterprises, it offers a lightweight, production-ready foundation for agent applications.
The SDK's key strengthsβlightweight simplicity, native tool calling, multi-agent support, built-in guardrails, first-party tracing, and provider-agnostic designβmake it particularly well-suited for OpenAI-first stacks and teams that need a structured runtime with handoffs and tracing out of the box.
The framework's primitives are small and clearly named: Agent, Handoff, Guardrail, Runner, Session, Tools, and Tracing. The simplicity is the value proposition.
The most effective approach combines the SDK's agent orchestration with:
- RAG for external knowledge (via File Search or MCP)
- Guardrails for safety and compliance
- Human-in-the-loop approvals for sensitive actions
- Tracing for observability and debugging
- Parallel execution for latency reduction
Whether you're building a customer support agent, a research assistant, an enterprise knowledge system, or a complex multi-agent workflow, the OpenAI Agents SDK provides the framework, tools, and production infrastructure needed to succeed.