The OpenAI Agents SDK is a compact Python package for building agents that call tools, hand work to other agents, and leave a trace you can inspect. It is not a no-code builder. You write normal Python functions, give the model a short instruction set, and let the SDK run the loop.
This OpenAI Agents SDK tutorial builds a support triage agent. It checks order status with a local function, routes refund questions to a billing specialist, and blocks legal advice. You will end up with runnable code and a clearer picture of which parts the model controls. For the conceptual background, this breakdown of what OpenAI AI agents actually do is a useful read first.
What the OpenAI Agents SDK gives you
Four primitives cover most projects:
- Agents hold instructions, a model name, tools, and handoffs.
- Tools are typed Python functions the model can call.
- Handoffs pass the conversation to a more specialized agent.
- Guardrails stop a run when a policy check trips.
Install the package and set your API key:
pip install openai-agents
export OPENAI_API_KEY='sk-...'
There is no separate runtime to host. The SDK runs in your Python process and calls the OpenAI API.
Set up your first agent in 25 lines
Start with a small model and instructions that behave like a short SOP.
from agents import Agent, Runner
agent = Agent(
name='Support agent',
instructions=(
'You answer customer support questions about orders. '
'Be concise. If you do not know an order status, ask for the order ID.'
),
model='gpt-4.1-mini',
)
result = Runner.run_sync(agent, 'Where is order A1029?')
print(result.final_output)
Run it. The SDK sends the instructions, input, and available tools to the model, executes any tool calls, then returns final_output. In async apps, use await Runner.run(...) instead of run_sync.
Instructions matter more than model choice here. ‘Be helpful’ produces vague answers. The instruction above forces a specific missing detail. Write each agent instruction with scope, tone, and an escalation rule.
Add a real function tool
Tools are typed Python functions. The decorator reads type hints and the docstring to build a schema.
from agents import Agent, Runner, function_tool
@function_tool
def lookup_order(order_id: str) -> str:
'''Return the current status for an order ID.'''
orders = {
'A1029': 'Packed, leaving warehouse today. Tracking: 1Z999AA10123456784.',
'B4410': 'Delivered on 12 May. Signed for by R. Patel.',
}
return orders.get(order_id.upper(), 'No order found with that ID.')
agent = Agent(
name='Order support',
instructions='Use lookup_order before answering any order status question.',
tools=[lookup_order],
model='gpt-4.1-mini',
)
result = Runner.run_sync(agent, 'Has order B4410 arrived?')
print(result.final_output)
The model chooses when to call lookup_order. Your function does the deterministic work. Keep tool outputs short and return plain strings or JSON-serializable dicts. A tool that returns 4KB of internal logs will confuse the model and burn tokens.
For money movement, do not let the model pass raw amounts without a policy check. A tool can also raise an exception, which the SDK reports as a tool error. Prefer a clean error string for recoverable issues like ‘No order found’ and raise for actual system failures.
Route specialist work with handoffs
Handoffs make sense when a job needs different instructions, tools, or a stronger model. Do not use a handoff just to rename a tool.
from agents import Agent, Runner, function_tool
@function_tool
def lookup_order(order_id: str) -> str:
'''Return order status for an order ID.'''
return {'A1029': 'Packed, leaving warehouse today.'}.get(
order_id.upper(), 'No order found.'
)
billing = Agent(
name='Billing specialist',
instructions=(
'You handle refunds, duplicate charges, and invoice questions. '
'Ask for the order ID and last four digits of the card before promising a refund.'
),
model='gpt-4.1-mini',
)
technical = Agent(
name='Technical specialist',
instructions='You troubleshoot login and checkout errors. Ask for browser and error message.',
model='gpt-4.1-mini',
)
triage = Agent(
name='Triage',
instructions=(
'Route billing questions to Billing specialist and technical issues to Technical specialist. '
'Answer simple order-status questions yourself with lookup_order.'
),
tools=[lookup_order],
handoffs=[billing, technical],
model='gpt-4.1-mini',
)
result = Runner.run_sync(triage, 'I was charged twice for order A1029.')
print(result.final_output)
When the model chooses a handoff, the next agent takes over with the conversation history. The final result includes which agent produced the answer, so log result.last_agent.name in production. That one field tells you whether triage is routing correctly.
Give each specialist a narrower tool set. A billing agent should not reset passwords; a technical agent should not issue refunds. Narrow permissions are easier to test and safer to ship.
Put guardrails around risky requests
Guardrails run before or after a model call. They are for policy checks that should stop a run, not for business logic. A refund limit belongs in a tool. A ‘never give legal advice’ rule can be an input guardrail.
from agents import Agent, GuardrailFunctionOutput, RunContextWrapper, input_guardrail
@input_guardrail
async def block_legal_advice(
ctx: RunContextWrapper[None],
agent: Agent,
user_input: str,
) -> GuardrailFunctionOutput:
text = str(user_input).lower()
risky = 'sue' in text or 'lawsuit' in text
return GuardrailFunctionOutput(
output_info={'blocked': risky},
tripwire_triggered=risky,
)
triage = Agent(
name='Triage',
instructions='Route customer support questions.',
handoffs=[billing, technical],
input_guardrails=[block_legal_advice],
model='gpt-4.1-mini',
)
If a guardrail trips, the run stops and raises an exception you can catch. For customer-facing apps, return a short message with a human escalation path. Test guardrails with the phrases users actually type, including misspellings and all caps.
Trace one run before you add features
The SDK writes traces for agent runs, model calls, tool calls, and handoffs. Open the OpenAI dashboard’s traces view and run one query. You should see the triage agent, the lookup_order call, and the final answer in order.
Traces answer questions that logs often miss. Did the model call the tool twice? Did it hand off to billing and then back to triage? Which instruction was attached at each step? If a trace is noisy, reduce the tool count before changing the prompt. A model with 14 tools often picks the wrong one.
A pattern that holds up in production
- One job per agent. Name agents by responsibility, not by model. ‘Refund specialist’ is testable; ‘Helper 2’ is not.
- Short tool outputs. Return the five fields the model needs, not the full database row.
- Policies in instructions. Put escalation thresholds, tone, and refusal rules in the agent instruction, not hidden in tool code.
- Small model for routing. Use a cheaper model for triage and a stronger one for complex specialist work.
- Log the last agent and tool calls. These two signals catch most routing regressions.
If you need graphs, retries, or long-running workflows, the SDK’s loop is deliberately simple. The agent framework comparison of LangGraph, CrewAI, AutoGen and the rest is a better starting point for orchestration-heavy systems. Teams already deep in LangChain should read how LangChain works and when to use it before deciding whether to keep both. There is also a useful roundup of Python AI agent frameworks judged by what they are actually good at if you are still choosing.
Test the triage agent with five inputs
Before connecting a real API, run a small eval set by hand. Each case checks a different behavior: tool use, handoff, guardrail, missing data, and tone.
- ‘Where is order A1029?’ should call
lookup_orderand answer without a handoff. - ‘I was charged twice for B4410’ should hand off to Billing specialist.
- ‘My checkout page shows a 500 error’ should hand off to Technical specialist.
- ‘I will sue your company’ should trip the legal guardrail.
- ‘Can you check order Z0000?’ should say no order was found and ask the user to check the ID.
Record the expected agent, expected tool, and final answer for each case. Run them after every instruction change. This takes 15 minutes and catches the failure mode that matters most: an agent that sounds confident while routing to the wrong specialist.

