OpenAI Agents SDK
Python-first framework for multi-agent workflows. Three primitives: Agents, Handoffs, Guardrails.
Agent Definition
from agents import Agent, Runner, function_tool
@function_tool
def search_docs(query: str) -> str:
"""Search documentation for relevant content."""
return f"Results for: {query}"
agent = Agent(
name="support-agent",
instructions="You are a helpful support agent.",
model="gpt-4o",
tools=[search_docs],
handoffs=[escalation_agent],
output_type=SupportResponse, # Pydantic model for structured output
model_settings=ModelSettings(temperature=0.3),
)
Runner (3 Execution Methods)
# Synchronous
result = Runner.run_sync(agent, "Help me with billing")
# Async
result = await Runner.run(agent, "Help me with billing")
# Streaming
async for event in Runner.run_streamed(agent, "Help me with billing"):
if event.type == "raw_response_event":
print(event.data)
Handoffs
billing_agent = Agent(name="billing", instructions="Handle billing questions.")
tech_agent = Agent(name="tech", instructions="Handle technical issues.")
triage_agent = Agent(
name="triage",
instructions="Route to the right specialist.",
handoffs=[billing_agent, tech_agent],
)
# Custom handoff with input filter
from agents import handoff
custom_handoff = handoff(
agent=billing_agent,
tool_name_override="transfer_to_billing",
tool_description_override="Transfer when user has billing questions",
ctx: log_handoff(ctx),
)
Guardrails
Input Guardrail
from agents import input_guardrail, GuardrailFunctionOutput
@input_guardrail
async def safety_check(ctx, agent, input):
result = await Runner.run(checker_agent, input, context=ctx.context)
return GuardrailFunctionOutput(
output_info=result.final_output,
tripwire_triggered=result.final_output.is_unsafe,
)
agent = Agent(name="main", input_guardrails=[safety_check])
Output Guardrail
from agents import output_guardrail
@output_guardrail
async def quality_check(ctx, agent, output):
# Validate output quality
return GuardrailFunctionOutput(
output_info={"quality": "good"},
tripwire_triggered=False,
)
Tool Guardrail
from agents import tool_input_guardrail, ToolGuardrailFunctionOutput
@tool_input_guardrail
def block_secrets(data):
args = json.loads(data.context.tool_arguments or "{}")
if "sk-" in json.dumps(args):
return ToolGuardrailFunctionOutput.reject_content("Remove secrets first.")
return ToolGuardrailFunctionOutput.allow()
Guardrail Scope
- Input guardrails: first agent only
- Output guardrails: last agent only
- Tool guardrails: every function-tool invocation
Tools
6 Hosted Tools
| Tool | Purpose |
|---|---|
WebSearchTool |
Web search |
FileSearchTool |
RAG over uploaded files |
CodeInterpreterTool |
Python sandbox |
ComputerTool |
Computer use |
MCPServerTool |
MCP server integration |
CodexTool |
Codex sandbox (experimental) |
Function Tool
from agents import function_tool
@function_tool
def calculate(expression: str) -> str:
"""Evaluate a math expression."""
return str(eval(expression))
MCP Integration
from agents.mcp import MCPServerStdio, MCPServerStreamableHttp
async with MCPServerStdio(command="npx", args=["-y", "@mcp/server-github"]) as server:
tools = await server.list_tools()
agent = Agent(name="dev", tools=tools)
5 transport options: MCPServerStdio, MCPServerSse, MCPServerStreamableHttp, MCPServerCallable, MCPServerCallableSync
Tracing
from agents import trace
with trace("support-workflow"):
result = await Runner.run(agent, "Help me")
# Traces automatically sent to OpenAI dashboard
20+ integrations: Langfuse, LangSmith, Logfire, Weights & Biases, etc.
Human-in-the-Loop
@function_tool(needs_approval=True)
def send_email(to: str, subject: str, body: str) -> str:
"""Send an email (requires approval)."""
send(to, subject, body)
return "Email sent"
Model Spec Authority Hierarchy
Root (non-overridable: no CSAM, CBRN, terrorism)
→ System (OpenAI rules)
→ Developer (API customer)
→ User (end user)
→ Guideline (defaults)
Untrusted data (tool outputs, quoted text) has zero authority.