Build Your First Agent with the OpenAI Agents SDK
The OpenAI Agents SDK is a small Python library built around a few ideas: an Agent with instructions and tools, a Runner that executes the loop, and optional handoffs, guardrails and sessions. You can build a working tool-using agent in about fifteen lines. This post walks through installation, a first agent, and what the runner returns.
Install
pip install openai-agents python-dotenv
The package is named openai-agents, but you import it as agents. Set OPENAI_API_KEY in your environment. The SDK uses the OpenAI API by default; it can also be pointed at other providers, which a later post touches on.
A minimal agent
from dotenv import load_dotenv
from agents import Agent, Runner
load_dotenv()
agent = Agent(
name="Helper",
instructions="You are a friendly assistant. Keep answers short.",
)
result = Runner.run_sync(agent, "Give me one tip for learning Python.")
print(result.final_output)
Runner.run_sync runs the agent and blocks until it finishes. result.final_output holds the answer. There is also await Runner.run(...) for async code. The model is a default chosen by the SDK; to choose one yourself, pass model= to the agent, preferably read from an environment variable so you can change it without editing code.
Add a function tool
Decorate a Python function with @function_tool and pass it in the tools list. The SDK builds the schema from the type hints and docstring.
import os
from dotenv import load_dotenv
from agents import Agent, Runner, function_tool
load_dotenv()
@function_tool
def get_stock_level(sku: str) -> str:
"""Return the stock level for a product SKU."""
stock = {"A100": "42 units", "B200": "out of stock"}
return stock.get(sku, "unknown SKU")
agent = Agent(
name="Inventory assistant",
instructions="Answer stock questions. Always use the tool for stock facts.",
tools=[get_stock_level],
model=os.environ.get("OPENAI_MODEL", "gpt-4.1-mini"),
)
result = Runner.run_sync(agent, "Do we have SKU A100 and SKU B200 in stock?")
print(result.final_output)
Set OPENAI_MODEL to a model your account can use; the fallback string here is only an example. The agent calls the tool twice, once per SKU, then answers that A100 has 42 units and B200 is out of stock.
What the loop does
The runner repeats these steps until it has a final output:
- Call the model with the instructions, input and tool definitions.
- If the model produced a final answer, stop.
- If it asked for tools, run them and add the results to the input.
- If it asked for a handoff, switch to the other agent and continue.
- Stop with an error if the turn limit is reached.
Control the limit with max_turns: Runner.run_sync(agent, text, max_turns=5). If the agent exceeds it, the SDK raises a MaxTurnsExceeded error that you can catch.
Inspect the result
The result object has more than the final text. result.new_items lists the messages, tool calls and tool outputs created during the run, and result.to_input_list() gives you a list you can feed into the next run to continue the conversation. A later post covers sessions, which do this for you.
Tips for beginners
- Write instructions as direct rules, such as "always use the tool for stock facts".
- Name agents clearly; names appear in traces and in handoffs.
- Keep one responsibility per agent; add more agents only when instructions start to conflict.
- Look at the trace in the OpenAI dashboard, which the SDK records by default, to see each call.
Writing good instructions
Instructions are the main lever you have. Good ones state the agent's job, the tools it should prefer, the format of the answer and the limits of its authority. Avoid long lists of unrelated rules; the model weighs them all, and conflicts produce odd behavior. If an agent needs different behavior for different tasks, that is usually a sign to split it into two agents and let one hand off to the other, which a later post covers in detail.
Typed outputs
If you want the final answer as an object rather than text, give the agent an output_type. The SDK then asks the model for structured output and final_output becomes an instance of your class:
from pydantic import BaseModel
from agents import Agent, Runner
class Tip(BaseModel):
title: str
steps: list[str]
tip_agent = Agent(
name="Tip writer",
instructions="Write a short how-to tip.",
output_type=Tip,
)
result = Runner.run_sync(tip_agent, "How do I create a Python virtual environment?")
print(result.final_output.title)
print(result.final_output.steps)
Typed outputs make the result safe to pass to the rest of your program, since a malformed answer is rejected instead of silently accepted.
Comments
No comments yet. Have a question or a tip? Be the first to share it.