OpenAI Agents SDK: Building Multi-Agent Systems with Handoffs and Guardrails
Hey everyone, today we cover the OpenAI Agents SDK, a lightweight framework for building agent based applications. If you have tried LangChain or CrewAI and found the abstractions too thick to debug, this SDK offers a much simpler approach with few concepts that still cover what you need.
What I like about it is that it has only four core primitives. There is no pile of abstract classes to memorize. You write ordinary Python functions, wrap them into agents, and the system runs. Because there is so little abstraction, when something goes wrong you can see the cause directly instead of tracing through five layers of wrappers.
We will cover those four primitives, installation, your first agent, tools, structured output, handoffs between agents, guardrails for safety, tracing for debugging, and finally a complete multi-agent customer service system.
Introduction
The Four Primitives
Agents are language models equipped with instructions and a set of tools. This is the base unit.
Handoffs let one agent transfer the conversation to another, more specialized agent. This is how the SDK does multi-agent orchestration, and I find it more elegant than other frameworks because a handoff is itself treated as a tool.
Guardrails are checks that run alongside the agent, typically validating input or output. If a check fails, execution stops early before you burn budget or produce something undesirable.
Sessions handle conversation history automatically so you do not have to manage message lists by hand between turns.
On top of all this sits tracing, enabled by default, which I consider the most underrated feature here. Every agent run is recorded in full, making debugging far more humane.
When to Use It
This SDK fits when you want production agents with minimal abstraction, when you need flows where several specialists handle different request types, or when you value debuggability over feature richness.
Note that despite the OpenAI name, the SDK supports many model providers through compatible interfaces, so you are not permanently locked in.
Installation
python -m venv venv
source venv/bin/activate # Linux / Mac
venv\Scripts\activate # Windows
pip install openai-agents
Set your API key:
export OPENAIAPIKEY="sk-..."
Your First Agent
from agents import Agent, Runner
agent = Agent(
name="Research Assistant",
instructions=(
"You are a careful research assistant. Answer concisely and factually. "
"If you are unsure, say so rather than inventing an answer."
),
model="gpt-4o-mini",
)
result = Runner.runsync(agent, "Explain the difference between SATA SSDs and NVMe in three points.")
print(result.finaloutput)
For async environments, which you will normally use in production:
import asyncio
from agents import Agent, Runner
async def main():
agent = Agent(name="Assistant", instructions="You are a helpful assistant.")
result = await Runner.run(agent, "Hello, how are you?")
print(result.finaloutput)
asyncio.run(main())
Instructions are your agent's system prompt. Write them specifically, including what is and is not allowed. Vague instructions produce agents with inconsistent behavior.
Adding Tools
Tools are how your agent interacts with the real world.
from agents import Agent, Runner, functiontool
@functiontool
def checkstock(productcode: str) -> dict:
"""Check warehouse stock availability for a product.
Args:
productcode: the product SKU, for example 'SKU-1234'
"""
# In the real world this queries a database
warehouse = {
"SKU-1234": {"name": "Mechanical Keyboard", "stock": 42, "location": "Jakarta"},
"SKU-5678": {"name": "Wireless Mouse", "stock": 0, "location": "Surabaya"},
}
return warehouse.get(productcode, {"error": "product not found"})
@functiontool
def calculateshipping(origin: str, destination: str, weightkg: float) -> dict:
"""Estimate shipping cost between two cities.
Args:
origin: sender city name
destination: recipient city name
weightkg: package weight in kilograms
"""
baserate = 12000
cost = baserate * max(1, round(weightkg))
return {"cost": cost, "estimateddays": 3}
agent = Agent(
name="Sales Assistant",
instructions=(
"You are a sales assistant. Use the tools to check stock and compute shipping. "
"Never invent stock numbers or prices."
),
tools=[checkstock, calculateshipping],
)
result = Runner.runsync(
agent,
"I want to buy SKU-1234 shipped to Bandung, it weighs 2 kg. Is it in stock? What is shipping?",
)
print(result.finaloutput)
As with FastMCP, docstrings and type hints are the interface the model reads. Write them clearly, state expected formats, and use specific types.
Note the instruction "never invent stock numbers". This matters. Without an explicit rule, models sometimes answer from general knowledge instead of calling the tool.
Structured Output
For integration with other systems you need parseable output, not free text.
from pydantic import BaseModel
from typing import Literal
from agents import Agent, Runner
class TicketAnalysis(BaseModel):
category: Literal["billing", "technical", "account", "other"]
urgency: Literal["low", "medium", "high", "critical"]
summary: str
needsescalation: bool
reason: str
agent = Agent(
name="Ticket Analyzer",
instructions="Analyze support tickets and classify them accurately.",
outputtype=TicketAnalysis,
)
result = Runner.runsync(
agent,
"Production server has been down for 20 minutes, all transactions are failing, "
"the client has called three times.",
)
analysis = result.finaloutput
print(analysis.category) # technical
print(analysis.urgency) # critical
print(analysis.needsescalation) # True
print(type(analysis)) # TicketAnalysis
The result is a validated Pydantic object rather than a string you must parse yourself. That makes integration into a ticketing system or database far safer.
Handoffs: Multi-Agent Orchestration
This is the feature that makes the SDK interesting. Instead of one giant agent with thirty tools, you build several specialists plus a triage agent.
from agents import Agent, Runner, functiontool
@function
tool
def checkinvoice(customerid: str) -> dict:
"""Fetch a customer's invoice status."""
return {"id": customerid, "amount": 450000, "status": "unpaid",
"duedate": "2026-09-20"}
@functiontool
def restartservice(serviceid: str) -> dict:
"""Restart a customer's malfunctioning service."""
return {"id": serviceid, "status": "restart successful", "duration": "12 seconds"}
billingagent = Agent(
name="Billing Specialist",
handoffdescription="Handles invoice, payment, and billing questions.",
instructions=(
"You are a billing specialist. Help customers with invoices and payments. "
"Always check invoice data before quoting any amount."
),
tools=[checkinvoice],
)
technicalagent = Agent(
name="Technical Specialist",
handoffdescription="Handles technical issues, service outages, and errors.",
instructions=(
"You are a technical specialist. Help customers resolve service disruptions. "
"Ask for symptom details before taking action."
),
tools=[restartservice],
)
triageagent = Agent(
name="Customer Service",
instructions=(
"You are a first line customer service agent. "
"Greet the customer warmly, understand the issue, then hand off to the right "
"specialist. Do not try to solve technical or billing problems yourself."
),
handoffs=[billingagent, technicalagent],
)
result = Runner.runsync(
triageagent,
"Hi, my internet has been down since this morning even though I paid this month's bill.",
)
print(result.finaloutput)
print("final agent:", result.lastagent.name)
handoffdescription is the text the triage agent reads to decide where to route. Write it clearly and make specialists distinct, because overlapping descriptions make routing effectively random.
Importantly, a handoff is a genuine transfer of control. The destination agent takes over the conversation entirely, with its own instructions and tools. That differs from calling another agent as a tool, which we cover next.
Agents as Tools
Sometimes you do not want to transfer control, you just want help and then to continue yourself.
translator = Agent(
name="Translator",
instructions="Translate the given text into English accurately.",
)
summarizer = Agent(
name="Summarizer",
instructions="Summarize text into at most three sentences.",
)
orchestrator = Agent(
name="Orchestrator",
instructions=(
"You manage a document processing flow. "
"Translate first, then summarize the result, then present both."
),
tools=[
translator.astool(
toolname="translate",
tooldescription="Translate text into English",
),
summarizer.astool(
toolname="summarize",
tooldescription="Summarize text into three sentences",
),
],
)
result = Runner.runsync(orchestrator, "Process this document: [long document text]")
print(result.finaloutput)
The distinction matters. Use a handoff when another agent should take over the conversation with the user. Use astool when you only need a result for the main agent to process further.
Guardrails: Keeping Agents on Track
Guardrails are checks that run before or after the main agent.
from pydantic import BaseModel
from agents import (
Agent, Runner, GuardrailFunctionOutput,
inputguardrail, RunContextWrapper,
InputGuardrailTripwireTriggered,
)
class RelevanceCheck(BaseModel):
relevant: bool
reason: str
checkeragent = Agent(
name="Relevance Checker",
instructions=(
"Decide whether the user message relates to our company's internet service, "
"billing, or technical support."
),
outputtype=RelevanceCheck,
model="gpt-4o-mini",
)
@inputguardrail
async def relevanceguardrail(ctx: RunContextWrapper, agent: Agent, inputdata):
result = await Runner.run(checkeragent, inputdata, context=ctx.context)
check = result.finaloutput
return GuardrailFunctionOutput(
outputinfo=check,
tripwiretriggered=not check.relevant,
)
mainagent = Agent(
name="Customer Service",
instructions="Help customers with questions about our services.",
inputguardrails=[relevanceguardrail],
)
try:
result = Runner.runsync(mainagent, "Please give me a beef rendang recipe.")
print(result.finaloutput)
except InputGuardrailTripwireTriggered:
print("Request is outside the scope of our service.")
Note that I use a cheap model for the guardrail. That matters, because guardrails run on every request. Using an expensive model for filtering inflates costs without commensurate benefit.
Output guardrails are available too through the @outputguardrail decorator, useful for ensuring the agent does not leak sensitive information or make promises it should not.
Sessions: Automatic Conversation History
from agents import Agent, Runner, SQLiteSession
agent = Agent(name="Assistant", instructions="You are a helpful assistant.")
session = SQLiteSession("conversationuser123", "history.db")
result = Runner.runsync(agent, "My name is Ruby and I work in AI.", session=session)
print(result.finaloutput)
result = Runner.runsync(agent, "Do you remember my name?", session=session)
print(result.finaloutput) # The model remembers because the session tracks history
Without sessions you must manage the message list yourself and pass it on every turn. With sessions, history is stored automatically in SQLite and survives a process restart.
Tracing: Humane Debugging
Tracing is on by default and records every execution step.
from agents import Runner, trace
async def handlerequest(message: str, customerid: str):
with trace("Customer Service Flow", groupid=customerid):
result = await Runner.run(triageagent, message)
return result.finaloutput
With groupid, all turns from one customer are grouped together so you can follow a whole conversation in the dashboard.
You can also inspect the run programmatically:
result = Runner.runsync(triageagent, "My internet is down.")
for item in result.newitems:
print(type(item).name)
print("turn count:", len(result.rawresponses))
print("final agent:", result.lastagent.name)
For sensitive data you can disable tracing:
export OPENAIAGENTSDISABLETRACING=1
Limiting Turns
An agent looping on tool calls forever is the fastest way to burn budget. Always set a bound.
from agents import Runner, MaxTurnsExceeded
try:
result = Runner.runsync(
agent,
"Find every possible piece of information about our products.",
maxturns=10,
)
print(result.finaloutput)
except MaxTurnsExceeded:
print("Agent exceeded the turn limit, it is probably stuck in a loop.")
Tips and Best Practices
Write specific instructions including explicit prohibitions. "Never promise a refund without supervisor approval" is far more effective than hoping the model infers it.
Split agents by domain rather than building one agent with thirty tools. An agent with five clear tools is far more reliable than one with thirty confusing ones.
Use cheap models for guardrails and simple classification, expensive models only for the main reasoning. This is the single biggest cost optimization available.
Always set maxturns. No exceptions.
Use structured output whenever the result feeds another system. Parsing free text is a never-ending source of bugs.
Keep traces and evaluation results. When you change instructions, you need a way to tell whether the change made the system better or worse.
For tools with serious side effects such as sending email or processing payments, add a human confirmation step. An agent that mistakenly sends a hundred emails is a story you do not want to live through.
Conclusion
The OpenAI Agents SDK is a strong choice when you value simplicity and debuggability. The summary:
There are only four primitives to master: Agents, Handoffs, Guardrails, and Sessions.
Tools are ordinary Python functions with a decorator, and docstrings plus type hints are the interface the model reads.
Structured output with Pydantic makes integration into other systems safe and validated.
Handoffs transfer conversational control to specialists, while as_tool requests help without transferring control. Choose based on need.
Guardrails backed by cheap models keep agents on track efficiently while saving money.
Built-in tracing makes debugging multi-agent systems far more tractable than guessing from logs.
Build one real flow at work, perhaps routing support tickets to three specialists. Start with two agents and two tools, then add a guardrail. In one afternoon you will have a demoable prototype, and from there the decision to continue usually becomes much easier. Happy building.