Build Your First AI Agent Step by Step (Python)
A hands-on tutorial with the OpenAI Agents SDK: create an agent, give it a tool, run the loop, require human approval for refunds, and test it offline.
This tutorial builds a small but real AI agent in Python: a customer-support helper that can look up orders and issue refunds, where every refund waits for a human to say yes. You will create the agent, give it a tool, watch the agent loop run, add an approval gate for the risky action, and write an offline test. Everything uses the OpenAI Agents SDK, and the code follows the patterns in its official quickstart, tools, human-in-the-loop and testing guides.
Why this SDK? It has only a handful of building blocks (agents, tools, handoffs, guardrails), and it ships human approval and test helpers out of the box, which is exactly what a first agent needs. If you want to weigh it against LangChain, CrewAI and others first, read our framework comparison.
What you will build
| Step | What you add | SDK feature |
|---|---|---|
| 1 | A project and an API key | openai-agents package |
| 2 | An agent that answers a question | Agent, Runner |
| 3 | An order lookup tool | @tool decorator |
| 4 | A refund tool that waits for approval | needs_approval, RunState |
| 5 | A test that never touches the network | agents.testing.ScriptedModel |
Step 1: set up the project
Create a folder, a virtual environment and install the SDK. These commands are the ones the quickstart uses on macOS or Linux (on Windows, activate with .venv\Scripts\activate and set the key with $env:OPENAI_API_KEY in PowerShell).
mkdir support_agent
cd support_agent
python -m venv .venv
source .venv/bin/activate
pip install openai-agents
export OPENAI_API_KEY=sk-...
Step 2: create and run an agent
An agent is a model plus instructions, a name and optional settings. Runner executes it and hands back a result whose final_output holds the answer.
import asyncio
from agents import Agent, Runner
agent = Agent(
name="Support agent",
instructions="You help customers with questions about their orders.",
)
async def main():
result = await Runner.run(agent, "What can you help me with?")
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
You did not pick a model, so the SDK uses its built-in default, which the Models guide currently lists as gpt-5.6-luna, tuned for cheap, high-volume work. For harder tasks, pass model="gpt-5.6-sol" to Agent, or set OPENAI_DEFAULT_MODEL in your environment to change the default for every agent that does not name one.
Step 3: add a tool
So far the agent can only talk. A tool lets it act. With the SDK’s @tool decorator, a plain Python function becomes a tool: its name becomes the tool name, the docstring becomes the description, and the argument types become the input schema. Here the “database” is a dictionary so you can run it without any setup.
import asyncio
from agents import Agent, Runner
from agents.decorators import tool
ORDERS = {
1001: {"status": "shipped", "total": 42.00},
1002: {"status": "delivered", "total": 18.50},
}
@tool
def lookup_order(order_id: int) -> str:
"""Return the status and total for an order."""
order = ORDERS.get(order_id)
if order is None:
return f"No order {order_id} found."
return f"Order {order_id}: {order['status']}, total ${order['total']:.2f}"
agent = Agent(
name="Support agent",
instructions="Answer order questions. Check the order with lookup_order before replying.",
tools=[lookup_order],
)
async def main():
result = await Runner.run(agent, "Where is order 1001?")
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
What the loop is doing
When you call Runner.run, the SDK repeats a simple cycle. It sends the input to the model. If the model replies with plain text of the expected type and asks for no tools, that reply is the final output and the run ends. If the model asks for a tool, the runner executes it, adds the tool’s result to the conversation and calls the model again. A handoff to another agent swaps the active agent and loops again. If the cycle goes past max_turns, the SDK raises MaxTurnsExceeded, which protects you from an agent that never stops.
For “Where is order 1001?” that means two model calls: one that requests lookup_order with order_id=1001, and one that turns the tool’s answer into a sentence for the customer. The mechanics of how a model asks for a tool are covered in function calling vs tool use.
Step 4: put a human in front of refunds
Looking up an order is harmless. Refunding one moves money, so a person should confirm it. The SDK handles this with needs_approval. When the model calls a tool marked this way, the run pauses instead of executing it, and the pending call shows up in result.interruptions. You turn the result into a RunState, approve or reject each item, then pass the state back to Runner.run to continue from where it stopped.
@tool(needs_approval=True)
async def refund_order(order_id: int) -> str:
"""Refund an order in full."""
# A real app would call your payments API here.
return f"Refunded order {order_id}."
agent = Agent(
name="Support agent",
instructions=(
"Answer order questions. Check the order with lookup_order first. "
"Use refund_order only when the customer asks for a refund."
),
tools=[lookup_order, refund_order],
)
async def main():
result = await Runner.run(agent, "Please refund order 1002.")
while result.interruptions:
state = result.to_state()
for interruption in result.interruptions:
answer = input(f"Approve {interruption.name} with {interruption.arguments}? [y/N]: ")
if answer.strip().lower() in {"y", "yes"}:
state.approve(interruption)
else:
state.reject(interruption)
result = await Runner.run(agent, state)
print(result.final_output)
Answer n and the refund function never runs. The model receives a rejection notice and tells the customer it could not complete the refund. You can replace that notice with your own text by passing rejection_message= to state.reject().
The input() call blocks, which is fine for a terminal demo. The SDK’s own example wraps it in run_in_executor, and in a web app you would store the state and wait for a reviewer.
Approve only the risky cases
Asking a human about every refund gets tedious. needs_approval also accepts an async function that receives the run context, the parsed tool arguments and the call ID, and returns True when a person must decide. This version only asks about refunds over 25 dollars or unknown orders:
async def large_refund(_ctx, params, _call_id) -> bool:
order = ORDERS.get(params.get("order_id"))
return order is None or order["total"] > 25
@tool(needs_approval=large_refund)
async def refund_order(order_id: int) -> str:
"""Refund an order in full."""
return f"Refunded order {order_id}."
If the arguments are malformed or missing, the SDK does not call your function at all and falls back to asking a human, so a bad tool call cannot slip past the policy.
Other guardrails worth knowing
Approval is one kind of control. The SDK has three more:
- Input guardrails check the user’s first message. They run in parallel with the agent by default. Use
run_in_parallel=Falseif the agent must not start (or call tools) until the check passes. - Output guardrails check the final answer of the last agent.
- Tool guardrails wrap a single function tool and can block or rewrite a call before it runs, or its result afterwards. The docs’ example rejects any tool argument that looks like an API key.
When a guardrail’s tripwire fires, the runner stops and raises an exception such as InputGuardrailTripwireTriggered for your code to handle.
Step 5: test it without calling the model
Agent tests that hit a live model are slow, cost money and give different answers each run. The SDK’s agents.testing module replaces the model with a ScriptedModel that returns responses you write in advance. Nothing goes over the network, but your real tools still run through the SDK’s normal tool pipeline. Install pytest and pytest-asyncio, then:
import pytest
from agents import RunConfig, Runner
from agents.testing import ScriptedModel, assistant_message, function_call
from support_agent import agent # the Agent from step 4
@pytest.mark.asyncio
async def test_lookup_runs_the_tool() -> None:
model = ScriptedModel(
[
[function_call("lookup_order", {"order_id": 1001}, call_id="call_1")],
[assistant_message("Order 1001 has shipped.")],
]
)
result = await Runner.run(
agent.clone(model=model),
"Where is order 1001?",
run_config=RunConfig(tracing_disabled=True),
)
assert result.final_output == "Order 1001 has shipped."
assert any(
item.get("type") == "function_call_output" for item in model.last_call.input
)
model.assert_complete()
The first scripted step makes the “model” call your tool; the second gives the final answer. The assertion on last_call.input proves the tool’s output reached the model, and assert_complete() fails if the run stopped early and skipped a scripted step. You can script a refund_order call the same way and check that the run pauses with an interruption instead of refunding.
Calling lookup_order directly in a test would skip schema validation, guardrails and tracing, so go through Runner as shown.
Watch real runs in traces
Tracing is on by default. Each run records model calls, tool calls, handoffs and guardrail checks, and you can inspect them in the Traces dashboard on the OpenAI platform. That is the fastest way to see why the agent picked (or skipped) a tool. Set OPENAI_AGENTS_DISABLE_TRACING=1 to turn it off.
Next steps
- Swap the fake data for real systems. Replace the
ORDERSdictionary with calls to your order and payment APIs. Our guide to connecting agents to APIs covers auth, retries and MCP servers. - Make refunds safe to retry. The SDK’s human-in-the-loop guide points out that approval does not guarantee a tool runs exactly once. If the process crashes after a refund but before the state is saved, resuming can repeat it. Give each refund an idempotency key that your payment system enforces.
- Keep memory across turns with sessions, so the customer can ask a follow-up question.
- Split the work across several agents using handoffs once one agent has too many tools.
- Compare other stacks. To see how other frameworks approach the same job, look at LangChain Agents and CrewAI, or call the OpenAI API directly if you want to own the loop yourself.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.