OpenAI Agents SDK Tutorial: Handoffs, Guardrails, and Tracing in Python
TL;DR
- The OpenAI Agents SDK is an open-source framework for building AI agents in Python (
pip install openai-agents), with a TypeScript version for JavaScript projects. It replaced OpenAI's experimental Swarm framework. - It is built on a few primitives: agents (an LLM with instructions and tools), handoffs (one agent passing work to another), guardrails (checks on inputs and outputs), and tracing (a record of every step).
- It also supports sessions for conversation memory, MCP servers as tools, human approval for sensitive tool calls, and realtime voice agents.
- It isn't limited to OpenAI models. Any provider with an OpenAI-compatible endpoint, like Gemini, works, and LiteLLM covers most others.
Note: We first published this guide when the Agents SDK launched in March 2025. The SDK has grown a lot since then, so we've updated every code example to the current release and added sections on sessions, MCP servers, and human approvals.
In the ever-evolving landscape of artificial intelligence, AI agents have emerged as a groundbreaking approach to building more sophisticated and autonomous systems. These agents represent a significant leap forward in AI development, offering capabilities beyond traditional static models.
What makes AI assistants particularly powerful is their ability to orchestrate complex tasks and continuously self-assess their operations. This self-monitoring capability ensures higher-quality outputs and more reliable performance.
To facilitate the development of these intelligent agents, OpenAI introduced its OpenAI Agents SDK, which replaces its previous Swarm framework. The open-source SDK provides developers a robust toolkit for building and deploying AI agents.
In this article, we'll explore the practical aspects of this SDK, diving into its core functionalities, examining how to build basic and advanced applications, and even looking at integrating external Large Language Model (LLM) providers for enhanced flexibility.
Principles
The OpenAI Agents SDK is built upon four fundamental principles that work together to create robust, reliable AI systems. Let's explore how these principles form the foundation of agent-based development:
At the heart of the system are Agents - the primary actors that drive the execution process. These specialized components handle LLM interactions, utilize tools, and generate responses based on their designated tasks.
The system enables smooth transitions between agents through handoffs. A recommended approach is implementing a triaging agent that intelligently routes tasks to the most appropriate specialized agent.
Guardrails serve as crucial safety mechanisms, performing two essential functions: screening user inputs for potential malicious content and validating agent outputs to ensure quality and appropriateness.
The tracing system provides detailed visibility into the agent's operations. Through the OpenAI dashboard, developers can monitor tool usage and track generated outputs, enabling thorough analysis and optimization.
These four principles work together to create a robust framework that enables developers to build sophisticated, reliable AI agent systems while maintaining control and visibility throughout the process.
Building our first system
Install the SDK and set your OpenAI API key:
pip install openai-agents
export OPENAI_API_KEY=sk-...We start with a simple example to understand the core principles of building an Agent system. As a very minimal thing, we need to define an agent and give it instructions on what it should do. We can give it a tool, such as the built-in WebSearchTool, so that it can automatically use it.
from agents import Agent, Runner, WebSearchTool
research_agent = Agent(
name="Research Agent",
instructions="You are a helpful research assistant.",
tools=[WebSearchTool()],
)
result = Runner.run_sync(
research_agent,
"Are AI agents sentient already?",
)
print(result.final_output)
# Output: No, AI agents are not sentient. They do not have consciousness, self-awareness, emotions, or subjective experiences. AI processes information and makes decisions based on data and algorithms. Sentience involves having thoughts, feelings, and an awareness of one's own existence, which AI lacks.Finally, we use a Runner to provide the research_agent with a query and can get the result (in this case synchronously).
We can also create our own tools and provide an agent with them like this:
from agents import Agent, function_tool
@function_tool
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
return f"It's always sunny in {city}."
weather_agent = Agent(
name="Weather Agent",
instructions="You are a helpful weather assistant.",
tools=[get_weather],
)The SDK turns the function's signature and docstring into the tool schema the model sees. Of course, this is a simplified example, but we could also call a weather API inside the get_weather function.
The real power comes in when we use multiple agents simultaneously. We can then define handoffs to select which agent to use. Let's look at an example and create a third agent, call it triage_agent, and make it choose between using the research_agent and the weather_agent:
triage_agent = Agent(
name="Triage Agent",
instructions="You decide which agent to handoff to work with.",
handoffs=[weather_agent, research_agent],
)
result = Runner.run_sync(
triage_agent,
"What is the weather in San Francisco?",
)
print(result.final_output)
# Output: It's always sunny in San Francisco! There you have it!Now that we understand how the system generally works, let's dive deeper into the different functionalities.
Options for creating agents
Agents can have different roles. With that, they have a lot of customization options. The only necessary properties an agent must have are:
- A
name: indicates what the agent is used for. instructions: are similar to a system prompt and should be used to describe the task the agent should fulfill clearly.
There are many other options that we can set, and some of them are relevant. One of the more common ones is the model, which can be any model OpenAI offers or a model from an external provider (see later in the article for an example using Gemini). If you don't set one, the SDK falls back to its default model, which you can override with the OPENAI_DEFAULT_MODEL environment variable.
Also, we can pass context to an Agent to add custom data from our database (or any other source). This can be done using the context type. We can provide any Python object that we want for it, so for example, a ChatContext could look like this:
from dataclasses import dataclass
from agents import Agent
@dataclass
class ChatContext:
channels: list[Channel]
users: list[User]
async def fetch_channels(self) -> list[Channel]:
return ...
agent = Agent[ChatContext](
...
)Usually, the output of an agent will be plain text (so a str object). However, we can change that by adding the output_type option to an agent. With that, we can define a Pydantic object we expect as output.
We first need to define the object and then hand it to the agent upon initialization:
from pydantic import BaseModel
from agents import Agent
class WeatherEvent(BaseModel):
forecast: str
temperature: float
hourly_temperature: list[float]
agent = Agent(
name="Weather agent",
instructions="Get the weather for a certain location",
output_type=WeatherEvent,
)The last interesting parameter we want to cover is handoffs. As mentioned, they can be considered sub-agents to whom the primary agent can hand tasks. Let's assume we have an e-commerce app where people want to either shop for something or ask for a refund. We can create a triage_agent that delegates the initial task to whatever agents fit best:
from agents import Agent
shopping_agent = Agent(...)
refund_agent = Agent(...)
triage_agent = Agent(
name="Triage agent",
instructions=(
"Help the user with their questions."
"If they ask about shopping, handoff to the shopping agent."
"If they ask about refunds, handoff to the refund agent."
),
handoffs=[shopping_agent, refund_agent],
)A handoff passes the whole conversation to the other agent, which then answers the user directly. If you want the triage agent to stay in charge and only borrow another agent's answer, use as_tool() instead:
triage_agent = Agent(
name="Triage agent",
instructions="Help the user. Use the refund tool for refund questions.",
tools=[
refund_agent.as_tool(
tool_name="handle_refund",
tool_description="Answer questions about refunds and returns.",
),
],
)Using an external LLM provider
When we specify the model for the Agent objects, we can select from the variety of OpenAI models. By default, the SDK calls OpenAI models through the Responses API.
However, we can also use models from other providers, at least if they offer an OpenAI-compatible API endpoint (which has become an industry standard by now). So, let's look at an example of integrating the Gemini API from Google (integrating other providers like Anthropic, DeepSeek, or even local models is very similar).
We can take different approaches, but we'll go over the one that specifically sets the provider for a single agent so that we can mix and match as we like.
We need to define a client using the AsyncOpenAI type (the regular OpenAI version works as well) and provide it with a BASE_URL (in the case of Gemini, this is https://generativelanguage.googleapis.com/v1beta/openai/). In addition, an API key is required, and then we can initialize the client like this:
import os
from openai import AsyncOpenAI
BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
API_KEY = os.getenv("GOOGLE_API_KEY")
client = AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY)Next, we can define the model using the OpenAIChatCompletionsModel object from the agents SDK. We can hand this model conveniently to an Agent object:
from agents import Agent, OpenAIChatCompletionsModel
model = OpenAIChatCompletionsModel(
model="gemini-2.5-flash",
openai_client=client,
)
agent = Agent(
name="Assistant",
instructions="Help the user with their research",
model=model,
)We use the Chat Completions model here because many providers don't support OpenAI's Responses API yet. Note that hosted tools like WebSearchTool only work with OpenAI models through the Responses API, so give non-OpenAI agents your own function tools instead.
For providers without an OpenAI-compatible endpoint, the SDK has a LiteLLM integration (pip install "openai-agents[litellm]") that accepts model names like litellm/anthropic/....
The same principle applies to other providers as well. Just a note that it might be necessary to disable tracing when using external providers as this requires calls to the OpenAI dashboard, which will fail if we don't have an OPENAI_API_KEY defined:
from agents import set_tracing_disabled
set_tracing_disabled(disabled=True)If you'd rather keep tracing, set an OpenAI key used only for uploading traces with set_tracing_export_api_key(...), or send traces to your own processor.
With this technique, we can incorporate any other provider into our system.
Guardrails
Another principle that the Agents SDK is built upon is guardrails. They are intended for one of two use cases (or both):
- Input guardrails: verify the user input before handing it into a more complex flow
- Output guardrails: check the output of an agent before handing it to the user
The idea is that we can check for a condition, and in case a guardrail is activated, we can signal a tripwire. This is equal to raising either an InputGuardrailTripwireTriggered or an OutputGuardrailTripwireTriggered exception.
Let's assume we want to check if a user is trying to solve their math homework using our system. We can use an input guardrail for that. The first thing we define is an output type and a guardrail_agent:
from pydantic import BaseModel
from agents import Agent
class MathHomeworkOutput(BaseModel):
is_math_homework: bool
reasoning: str
guardrail_agent = Agent(
name="Guardrail check",
instructions="Check if the user is asking you to do their math homework.",
output_type=MathHomeworkOutput,
)Then, we can create a function that takes the context (through the RunContextWrapper from the agents SDK) and returns a GuardrailFunctionOutput object. We hand this through an agent using the input_guardrails parameter and are done:
from agents import (
Agent,
GuardrailFunctionOutput,
InputGuardrailTripwireTriggered,
RunContextWrapper,
Runner,
TResponseInputItem,
input_guardrail,
)
@input_guardrail
async def math_guardrail(
ctx: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]
) -> GuardrailFunctionOutput:
result = await Runner.run(guardrail_agent, input, context=ctx.context)
return GuardrailFunctionOutput(
output_info=result.final_output,
tripwire_triggered=result.final_output.is_math_homework,
)
agent = Agent(
name="Customer support agent",
instructions="You help customers with their questions.",
input_guardrails=[math_guardrail],
)
async def main():
try:
await Runner.run(agent, "Can you solve 2x + 3 = 11 for me?")
except InputGuardrailTripwireTriggered:
print("Math homework guardrail tripped")By default, input guardrails run in parallel with the agent to keep latency low, so the agent may already have started (and used tokens) when the tripwire fires. Pass run_in_parallel=False to the decorator if the agent should only start once the check passes.
Output guardrails work the same way, but they check the agent's final answer. They use the @output_guardrail decorator, receive the agent's output instead of the user's input, and are attached with output_guardrails=[...]. The SDK also has tool guardrails, which check the arguments and results of individual function tool calls.
Sessions: giving agents memory
Each Runner.run call starts fresh unless you pass in the earlier conversation. Sessions handle that for you: the runner loads the history before each turn and saves the new messages after it.
from agents import Agent, Runner, SQLiteSession
agent = Agent(name="Assistant", instructions="Reply very concisely.")
session = SQLiteSession("conversation_123")
result = await Runner.run(agent, "What city is the Golden Gate Bridge in?", session=session)
result = await Runner.run(agent, "What state is it in?", session=session)
print(result.final_output) # The agent remembers we're talking about San FranciscoSQLiteSession is good for local development. For production, the SDK ships backends for Redis, SQLAlchemy-supported databases, MongoDB, and OpenAI's Conversations API, plus an EncryptedSession wrapper.
Connecting MCP servers
Agents can use tools from any Model Context Protocol (MCP) server alongside their own function tools. Here's an agent connected to an MCP server over Streamable HTTP:
import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp
async def main():
async with MCPServerStreamableHttp(
name="My MCP Server",
params={"url": "http://localhost:8000/mcp"},
) as server:
agent = Agent(
name="Assistant",
instructions="Use the MCP tools to answer questions.",
mcp_servers=[server],
)
result = await Runner.run(agent, "Add 7 and 22.")
print(result.final_output)
asyncio.run(main())Use MCPServerStdio to launch a local MCP server as a subprocess, or HostedMCPTool to let OpenAI's API call a public MCP server for you. To see how MCP fits with other agent protocols, read our A2A vs. MCP comparison.
Human-in-the-loop approvals
Some tools shouldn't run without a person signing off, like issuing a refund or deleting data. Mark them with needs_approval=True, and the run pauses when the model tries to call them:
from agents import Agent, Runner, function_tool
@function_tool(needs_approval=True)
async def cancel_order(order_id: int) -> str:
return f"Cancelled order {order_id}"
agent = Agent(name="Support agent", instructions="Help with orders.", tools=[cancel_order])
result = await Runner.run(agent, "Cancel order 42")
while result.interruptions:
state = result.to_state()
for item in result.interruptions:
state.approve(item) # In a real app, ask a reviewer, or call state.reject(item)
result = await Runner.run(agent, state)
print(result.final_output)Tracing
The last important part of the entire system is first-class support for tracing. We can go far with it, but I want to quickly demonstrate how much we're getting out of the box.
By default tracing is enabled and will give us a ton of detail in the Traces dashboard. It supports information about each workflow you define. Inside you can determine which agents were called, which handoffs happened. Per agent we see the tools being used as well as the queries and responses they have given.
Here's a short walkthrough of all the features:
Traces aren't locked to OpenAI's dashboard: you can add your own trace processors to send the same data to other observability tools.
Agents SDK vs. OpenAI's Agents API
OpenAI also offers a managed Agents API, and the names are easy to mix up:
- Agents SDK (this article): a library that runs inside your application. You control deployment, storage, approvals, and which models it calls.
- Agents API: a hosted runtime where OpenAI runs the agent loop for you, including context compaction, multi-agent orchestration, and MCP support. It suits long-running tasks where you don't want to manage the infrastructure.
Choose the SDK when you need to own the runtime or mix model providers. Choose the API when you'd rather OpenAI host it.
How the Agents SDK compares to other frameworks
The Agents SDK is deliberately small: a handful of primitives and plain Python for everything else. That makes it quick to learn, but frameworks like LangGraph give you more explicit control over complex, branching workflows, and CrewAI is built around role-based teams of agents. For a side-by-side look, see our guide to the best multiagent AI frameworks and our roundup of AI orchestration tools.
Summary
In summary, the OpenAI Agents SDK is a great, intuitive framework. It makes entering the whole Agent field straightforward and supports more complex use cases.
The guardrails feature is cumbersome to set up but very powerful if done well. The out-of-the-box support for traces is excellent and helps you reason about your system and analyze usage, bottlenecks, and more.
We're excited about the SDK's potential and would like to give OpenAI huge kudos for making the entire framework open-source. Since launch it has grown sessions, MCP support, human approvals, and voice agents, and integrating external providers remains a welcome part of it.
Taking your agent into a live call
The Agents SDK handles reasoning and orchestration, but it doesn't put your agent on a live audio or video call. Vision Agents, Stream's open-source framework, does that part: it joins the call over Stream's edge network and runs the model in real time. Switching it to OpenAI's speech-to-speech Realtime model is one line:
from vision_agents.core import Agent, User
from vision_agents.plugins import getstream, openai
agent = Agent(
edge=getstream.Edge(),
agent_user=User(name="Voice Assistant", id="agent"),
instructions="You are a friendly voice assistant. Keep answers short.",
llm=openai.Realtime(), # speech-to-speech, so no separate STT or TTS needed
)To build the full thing step by step, follow our AI voice agent tutorial, or browse the Voice AI docs.
FAQ
What is the OpenAI Agents SDK?
It's an open-source framework from OpenAI for building AI agents in Python or TypeScript. You define agents with instructions and tools, connect them with handoffs, protect them with guardrails, and inspect each run with tracing.
Is the OpenAI Agents SDK free?
The SDK itself is free and open source. You pay for the model calls it makes, at the normal rates of OpenAI or whichever provider you use.
Can I use the OpenAI Agents SDK with other AI models?
Yes. Any provider with an OpenAI-compatible endpoint, such as Gemini, works through OpenAIChatCompletionsModel, and the LiteLLM integration covers most others. You can also run it with local models. Hosted tools like web search only work with OpenAI models.
Is there a TypeScript version of the OpenAI Agents SDK?
Yes. The TypeScript SDK has the same core concepts (agents, handoffs, guardrails, and tracing) for Node.js and other JavaScript runtimes.
Should I use the OpenAI Agents SDK or PydanticAI?
Both are lightweight Python frameworks. The Agents SDK is the better fit if you want built-in handoffs, OpenAI's tracing dashboard, and hosted tools like web search. PydanticAI leans further into type-safe, validated outputs and is provider-neutral from the start.
What replaced OpenAI Swarm?
The Agents SDK. Swarm was an experimental, educational project; the Agents SDK is its production-ready successor and keeps the same ideas of agents and handoffs.
