
Constructing an AI agent in Python is now a lot easier than it was once. With the OpenAI Brokers SDK, you possibly can create brokers, join instruments, keep dialog state, and run multi-step workflows with out constructing your personal tool-calling loop from scratch.
On this tutorial, we’ll construct a sensible analysis agent that may search the net, name a customized Python perform, keep in mind earlier messages, and resolve when to make use of every functionality.
What Is an AI Agent?
A normal massive language mannequin (LLM) utility often follows a easy movement:
Immediate — Mannequin — Response
The mannequin receives a immediate, generates a solution, and stops.
An AI agent provides instruments and an execution loop:
Consumer — Agent — Software if wanted — Agent — Remaining Response
As an alternative of solely producing textual content, the agent can resolve whether or not it must take an motion first, similar to looking the net, calling a Python perform, or retrieving info from reminiscence.
With the OpenAI Brokers SDK, the Runner manages this course of mechanically. It sends the request to the mannequin, executes any requested instruments, passes the outcomes again to the agent, and continues till the agent produces a remaining reply.
This potential to cause, use instruments, and proceed working throughout a number of steps is what makes an agent completely different from a primary LLM utility.
Set Up the Undertaking
Earlier than we construct the agent, let’s create a clear Python surroundings and set up every thing we’d like.
Create a Python undertaking with uv:
mkdir first-ai-agent
cd first-ai-agent
uv init
uv add openai-agents
Or set up the package deal with pip:
pip set up openai-agents
Set your OpenAI API key:
export OPENAI_API_KEY="your-api-key"
On Home windows, export works in Git Bash. In Command Immediate or PowerShell, you should utilize:
setx OPENAI_API_KEY "your-api-key"
Construct Your First Agent
Now we will flip just a few strains of Python into an agent that decides when it wants contemporary info from the net.
Create essential.py:
from brokers import Agent, Runner, WebSearchTool
agent = Agent(
title="Analysis Assistant",
directions=(
"You're a concise analysis assistant. "
"Use net search when present info is required."
),
instruments=[WebSearchTool()],
)
end result = Runner.run_sync(
agent,
"What are the most recent developments in Python?"
)
print(end result.final_output)
Run it:
uv run essential.py
Output:
As of **September 14, 2026**, the main Python developments are:
- **Python 3.14 is the most recent steady function collection**; the latest upkeep
launch is **3.14.7**. It provides formally supported free-threaded builds,
deferred annotation analysis, template string literals (`t""`), ...
- **Python 3.15 is nearing launch**: the ultimate launch is scheduled for
**October 1, 2026**. ...
For brand new tasks, **Python 3.14.7** is at present the most secure default.
WebSearchTool() is a hosted OpenAI device, so the mannequin can resolve when it wants present info as a substitute of you manually calling a search API.
For instance, our run appropriately recognized Python 3.14.7 as the present steady launch.
Add Your Personal Python Software
Net search is beneficial, however brokers develop into far more highly effective once they can even work together with your personal Python code.
Add a calculation device:
from brokers.decorators import device
@device
def calculate_total(
worth: float,
amount: int
) -> float:
"""Calculate the full price of an order."""
return worth * amount
Then give it to the agent:
agent = Agent(
title="Assistant",
directions="Assist with analysis and calculations.",
instruments=[
WebSearchTool(),
calculate_total,
],
)
Check it:
end result = Runner.run_sync(
agent,
"I want 14 GPUs costing $2.49 every per hour. "
"What is going to they price per hour?"
)
print(end result.final_output)
Output:
14 GPUs x $2.49/hour = **$34.86 per hour**.
The SDK mechanically makes use of the perform title, arguments, kind hints, and docstring to create a device schema the mannequin can perceive. You don’t want to manually outline JSON schemas or write the tool-calling loop your self.
Tip: Write clear docstrings as a result of they assist the mannequin perceive what a device does and when it ought to use it.
Including Dialog Reminiscence
A helpful agent mustn’t overlook every thing the second the subsequent message arrives, so let’s give it dialog reminiscence.
To make the agent conversational, add a session:
from brokers import SQLiteSession
session = SQLiteSession(
"user_1",
"conversations.db"
)
Then cross it into every run:
whereas True:
message = enter("You: ")
if message.decrease() in {"exit", "stop"}:
break
end result = Runner.run_sync(
agent,
message,
session=session,
)
print("Agent:", end result.final_output)
Now strive:

The second request mechanically receives the sooner dialog, so the agent understands what “the most recent model” refers to.
As a result of we used a file-backed SQLite database, the historical past can even persist after restarting this system.
For bigger functions, the SDK additionally supplies session backends for programs similar to Redis, SQLAlchemy, and MongoDB.
How the Full Agent Works
At this level, all of the items come collectively:

The agent decides what motion to take, the Runner executes the agent loop and any requested instruments, and the session preserves dialog historical past between requests.
Right here is the whole essential.py:
import os
import sys
from brokers import Agent, Runner, SQLiteSession, WebSearchTool
from brokers.decorators import device
@device
def calculate_total(
worth: float,
amount: int
) -> float:
"""Calculate the full price of an order."""
return worth * amount
def essential() -> None:
if not os.environ.get("OPENAI_API_KEY"):
sys.exit(
"Error: set the OPENAI_API_KEY surroundings variable first."
)
agent = Agent(
title="Assistant",
directions="""
Assist the person with analysis and calculations.
Use the obtainable instruments when crucial.
""",
instruments=[
WebSearchTool(),
calculate_total,
],
)
session = SQLiteSession(
"user_1",
"conversations.db"
)
strive:
whereas True:
strive:
message = enter("You: ")
besides (EOFError, KeyboardInterrupt):
print()
break
command = message.strip().decrease()
if command in {"exit", "stop"}:
break
if not command:
proceed
strive:
end result = Runner.run_sync(
agent,
message,
session=session,
)
besides Exception as exc:
print(
f"Agent error "
f"({kind(exc).__name__}): {exc}"
)
proceed
print("Agent:", end result.final_output)
lastly:
session.shut()
if __name__ == "__main__":
essential()
This provides us a small however full conversational agent with net search, a customized Python device, persistent reminiscence, primary error dealing with, and a steady chat interface.
The Brokers SDK additionally allows tracing by default, which is particularly helpful as soon as your workflows develop into extra advanced. Traces allow you to examine the mannequin calls, device utilization, handoffs, and different steps taken throughout an agent run.

You may examine these traces within the OpenAI dashboard to grasp how the agent reached its reply, which instruments it chosen, and the place issues occurred. This makes tracing notably helpful for debugging tool-calling conduct and bettering agent directions.
Remaining Ideas
Constructing your first AI agent is much less about creating a posh autonomous system and extra about giving a mannequin the flexibility to take helpful actions.
On this information, we began with a easy agent, added net search, linked a customized Python device, launched persistent dialog reminiscence, and introduced every thing collectively in a whole utility with tracing and error dealing with.
That basis is sufficient to construct surprisingly succesful workflows. From right here, you possibly can step by step add APIs, MCP servers, guardrails, handoffs, extra specialised instruments, and extra brokers as your utility grows.
The sample stays the identical: give the agent the best instruments, let it resolve when to make use of them, and let the Brokers SDK deal with the execution loop.
Begin small, make one workflow helpful, and increase solely while you really need extra complexity.
Abid Ali Awan (@1abidaliawan) is a licensed information scientist skilled who loves constructing machine studying fashions. At the moment, he’s specializing in content material creation and writing technical blogs on machine studying and information science applied sciences. Abid holds a Grasp’s diploma in know-how administration and a bachelor’s diploma in telecommunication engineering. His imaginative and prescient is to construct an AI product utilizing a graph neural community for college kids scuffling with psychological sickness.

Constructing an AI agent in Python is now a lot easier than it was once. With the OpenAI Brokers SDK, you possibly can create brokers, join instruments, keep dialog state, and run multi-step workflows with out constructing your personal tool-calling loop from scratch.
On this tutorial, we’ll construct a sensible analysis agent that may search the net, name a customized Python perform, keep in mind earlier messages, and resolve when to make use of every functionality.
What Is an AI Agent?
A normal massive language mannequin (LLM) utility often follows a easy movement:
Immediate — Mannequin — Response
The mannequin receives a immediate, generates a solution, and stops.
An AI agent provides instruments and an execution loop:
Consumer — Agent — Software if wanted — Agent — Remaining Response
As an alternative of solely producing textual content, the agent can resolve whether or not it must take an motion first, similar to looking the net, calling a Python perform, or retrieving info from reminiscence.
With the OpenAI Brokers SDK, the Runner manages this course of mechanically. It sends the request to the mannequin, executes any requested instruments, passes the outcomes again to the agent, and continues till the agent produces a remaining reply.
This potential to cause, use instruments, and proceed working throughout a number of steps is what makes an agent completely different from a primary LLM utility.
Set Up the Undertaking
Earlier than we construct the agent, let’s create a clear Python surroundings and set up every thing we’d like.
Create a Python undertaking with uv:
mkdir first-ai-agent
cd first-ai-agent
uv init
uv add openai-agents
Or set up the package deal with pip:
pip set up openai-agents
Set your OpenAI API key:
export OPENAI_API_KEY="your-api-key"
On Home windows, export works in Git Bash. In Command Immediate or PowerShell, you should utilize:
setx OPENAI_API_KEY "your-api-key"
Construct Your First Agent
Now we will flip just a few strains of Python into an agent that decides when it wants contemporary info from the net.
Create essential.py:
from brokers import Agent, Runner, WebSearchTool
agent = Agent(
title="Analysis Assistant",
directions=(
"You're a concise analysis assistant. "
"Use net search when present info is required."
),
instruments=[WebSearchTool()],
)
end result = Runner.run_sync(
agent,
"What are the most recent developments in Python?"
)
print(end result.final_output)
Run it:
uv run essential.py
Output:
As of **September 14, 2026**, the main Python developments are:
- **Python 3.14 is the most recent steady function collection**; the latest upkeep
launch is **3.14.7**. It provides formally supported free-threaded builds,
deferred annotation analysis, template string literals (`t""`), ...
- **Python 3.15 is nearing launch**: the ultimate launch is scheduled for
**October 1, 2026**. ...
For brand new tasks, **Python 3.14.7** is at present the most secure default.
WebSearchTool() is a hosted OpenAI device, so the mannequin can resolve when it wants present info as a substitute of you manually calling a search API.
For instance, our run appropriately recognized Python 3.14.7 as the present steady launch.
Add Your Personal Python Software
Net search is beneficial, however brokers develop into far more highly effective once they can even work together with your personal Python code.
Add a calculation device:
from brokers.decorators import device
@device
def calculate_total(
worth: float,
amount: int
) -> float:
"""Calculate the full price of an order."""
return worth * amount
Then give it to the agent:
agent = Agent(
title="Assistant",
directions="Assist with analysis and calculations.",
instruments=[
WebSearchTool(),
calculate_total,
],
)
Check it:
end result = Runner.run_sync(
agent,
"I want 14 GPUs costing $2.49 every per hour. "
"What is going to they price per hour?"
)
print(end result.final_output)
Output:
14 GPUs x $2.49/hour = **$34.86 per hour**.
The SDK mechanically makes use of the perform title, arguments, kind hints, and docstring to create a device schema the mannequin can perceive. You don’t want to manually outline JSON schemas or write the tool-calling loop your self.
Tip: Write clear docstrings as a result of they assist the mannequin perceive what a device does and when it ought to use it.
Including Dialog Reminiscence
A helpful agent mustn’t overlook every thing the second the subsequent message arrives, so let’s give it dialog reminiscence.
To make the agent conversational, add a session:
from brokers import SQLiteSession
session = SQLiteSession(
"user_1",
"conversations.db"
)
Then cross it into every run:
whereas True:
message = enter("You: ")
if message.decrease() in {"exit", "stop"}:
break
end result = Runner.run_sync(
agent,
message,
session=session,
)
print("Agent:", end result.final_output)
Now strive:

The second request mechanically receives the sooner dialog, so the agent understands what “the most recent model” refers to.
As a result of we used a file-backed SQLite database, the historical past can even persist after restarting this system.
For bigger functions, the SDK additionally supplies session backends for programs similar to Redis, SQLAlchemy, and MongoDB.
How the Full Agent Works
At this level, all of the items come collectively:

The agent decides what motion to take, the Runner executes the agent loop and any requested instruments, and the session preserves dialog historical past between requests.
Right here is the whole essential.py:
import os
import sys
from brokers import Agent, Runner, SQLiteSession, WebSearchTool
from brokers.decorators import device
@device
def calculate_total(
worth: float,
amount: int
) -> float:
"""Calculate the full price of an order."""
return worth * amount
def essential() -> None:
if not os.environ.get("OPENAI_API_KEY"):
sys.exit(
"Error: set the OPENAI_API_KEY surroundings variable first."
)
agent = Agent(
title="Assistant",
directions="""
Assist the person with analysis and calculations.
Use the obtainable instruments when crucial.
""",
instruments=[
WebSearchTool(),
calculate_total,
],
)
session = SQLiteSession(
"user_1",
"conversations.db"
)
strive:
whereas True:
strive:
message = enter("You: ")
besides (EOFError, KeyboardInterrupt):
print()
break
command = message.strip().decrease()
if command in {"exit", "stop"}:
break
if not command:
proceed
strive:
end result = Runner.run_sync(
agent,
message,
session=session,
)
besides Exception as exc:
print(
f"Agent error "
f"({kind(exc).__name__}): {exc}"
)
proceed
print("Agent:", end result.final_output)
lastly:
session.shut()
if __name__ == "__main__":
essential()
This provides us a small however full conversational agent with net search, a customized Python device, persistent reminiscence, primary error dealing with, and a steady chat interface.
The Brokers SDK additionally allows tracing by default, which is particularly helpful as soon as your workflows develop into extra advanced. Traces allow you to examine the mannequin calls, device utilization, handoffs, and different steps taken throughout an agent run.

You may examine these traces within the OpenAI dashboard to grasp how the agent reached its reply, which instruments it chosen, and the place issues occurred. This makes tracing notably helpful for debugging tool-calling conduct and bettering agent directions.
Remaining Ideas
Constructing your first AI agent is much less about creating a posh autonomous system and extra about giving a mannequin the flexibility to take helpful actions.
On this information, we began with a easy agent, added net search, linked a customized Python device, launched persistent dialog reminiscence, and introduced every thing collectively in a whole utility with tracing and error dealing with.
That basis is sufficient to construct surprisingly succesful workflows. From right here, you possibly can step by step add APIs, MCP servers, guardrails, handoffs, extra specialised instruments, and extra brokers as your utility grows.
The sample stays the identical: give the agent the best instruments, let it resolve when to make use of them, and let the Brokers SDK deal with the execution loop.
Begin small, make one workflow helpful, and increase solely while you really need extra complexity.
Abid Ali Awan (@1abidaliawan) is a licensed information scientist skilled who loves constructing machine studying fashions. At the moment, he’s specializing in content material creation and writing technical blogs on machine studying and information science applied sciences. Abid holds a Grasp’s diploma in know-how administration and a bachelor’s diploma in telecommunication engineering. His imaginative and prescient is to construct an AI product utilizing a graph neural community for college kids scuffling with psychological sickness.















