How to Build AI Agents Using OpenAI Agent SDK with Python
What is OpenAI Agents SDK?
The OpenAI Agents SDK is a lightweight Python framework that helps developers build AI agents and Agentic AI applications.
In simple words, an AI agent is a program that can understand a task, decide what to do, use tools, and complete the task with less human intervention.
The Agents SDK is designed to make agent development simple and easy to understand. It provides a small number of important building blocks instead of adding many complex features.
- Agents, which are LLMs equipped with instructions and tools
- Agents as tools / Handoffs, which allow agents to delegate to other agents for specific tasks
- Guardrails, which enable validation of agent inputs and outputs
Why use the Agents SDK
One of the main benefits of the Agents SDK is its simplicity. Developers do not need to learn a large number of abstractions before creating an AI agent. Instead, the SDK provides a small set of core primitives that can be combined to create different types of agentic applications.
The SDK has two driving design principles:
- Enough features to be worth using, but few enough primitives to make it quick to learn.
- Works great out of the box, but you can customize exactly what happens.
Here are the main features of the SDK:
- Agents: Build agents with instructions, tools, guardrails, handoffs, and a built-in loop that continues until the task is complete.
- Realtime agents: Build powerful voice agents with
gpt-realtime-2.1, automatic interruption detection, context management, guardrails, and more. - Agents as tools / Handoffs: A powerful mechanism for coordinating and delegating work across multiple agents.
- Guardrails: Run input validation and safety checks in parallel with agent execution, and fail fast when checks do not pass.
- Function tools: Turn any Python function into a tool with automatic schema generation and Pydantic-powered validation.
- MCP server tool calling: Built-in integration that exposes remote MCP tools to agents alongside function tools.
- Sessions: A persistent memory layer for maintaining working context within an agent loop.
- Human in the loop: Built-in mechanisms for involving humans during agent runs.
- Tracing: Built-in tracing for visualizing, debugging, and monitoring workflows, with support for the OpenAI suite of evaluation, fine-tuning, and distillation tools.
What Is an Agent Loop?
An Agent Loop is the repeated process an AI agent follows to understand a task, decide what to do, take an action, check the result, and continue until the task is completed.
In simple words, an agent does not always give an answer after just one step. Instead, it can perform multiple steps to complete a task.
The basic Agent Loop looks like this:
Understand → Decide → Act → Observe → Repeat → Complete
How Does an Agent Loop Work?
Let’s understand the Agent Loop with a simple example.
Suppose you ask an AI agent:
“Find the weather in Mumbai and tell me whether I should carry an umbrella.”
The agent may follow these steps:
Step 1: Understand the request
First, the agent understands what you are asking.
It identifies two requirements:
- Find the weather in Mumbai.
- Decide whether an umbrella may be useful.
Step 2: Decide what to do
Next, the agent decides that it needs current weather information.
Therefore, it selects a weather tool to get the required information.
Step 3: Take action
The agent calls the weather tool.
For example:
get_weather("Mumbai")
Step 4: Observe the result
The weather tool returns information such as:
Rain is expected in Mumbai today.
The agent then reads and understands this result.
Step 5: Decide the next action
Based on the result, the agent decides that an umbrella recommendation can now be provided.
Step 6: Complete the task
Finally, the agent gives the user an answer:
“Rain is expected in Mumbai today, so you may want to carry an umbrella.”
This complete process is called an Agent Loop.
Agent Loop in Simple Terms
You can think of an Agent Loop like a person solving a problem.
For example, imagine you want to repair a computer.
You might:
- Understand the problem.
- Check the possible cause.
- Try a solution.
- Check whether the solution worked.
- If it did not work, try another solution.
- Continue until the problem is solved.
An AI agent can follow a similar process.
Agent Loop Flow
User Request
↓
Understand the Task
↓
Plan / Decide
↓
Use Tool or Take Action
↓
Check the Result
↓
Task Complete?
↓
No → Continue the Loop
↓
Yes → Return Final Answer
Why Is the Agent Loop Important?
The Agent Loop is important because many real-world tasks cannot be completed with a single AI response.
For example, an AI agent may need to:
- Search for information.
- Call an API.
- Query a database.
- Use a calculator.
- Read a file.
- Ask another agent for help.
- Check the result.
- Perform another action.
Therefore, the Agent Loop allows an AI agent to perform multiple actions and make decisions based on the results.
Agent Loop Implementation
import os
import requests
from dotenv import load_dotenv
from openai.types.responses import ResponseTextDeltaEvent
from agents import Agent, Runner, trace, function_tool, SQLiteSession
load_dotenv(override=True)
# Agent with name, instructions, model
agent = Agent(name="Jokester", instructions="You are a joke teller", model="gpt-5.4-mini")
# Run with Runner.run(agent, prompt)
result = await Runner.run(agent, "Tell a joke about Autonomous AI Agents")
print(result.final_output)
#detail of the LLM calls
result.to_input_list()
with trace("Telling a joke"):
result = await Runner.run(agent, "Tell a joke about Autonomous AI Agents")
print(result.final_output)
# Streaming
result = Runner.run_streamed(agent, input="Please tell me 11 jokes about AI Agents.")
async for event in result.stream_events():
if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
print(event.data.delta, end="", flush=True)
Explanation of above code line by line
import os
os is a built-in Python module.
It allows Python to work with the operating system, for example:
- Environment variables
- File paths
- Operating-system settings
In this particular code, os is imported but not directly used
import requests
requests is a Python library used to make HTTP/API calls.
Load environment variables
from dotenv import load_dotenv
python-dotenv allows Python to read environment variables from a .env file.
load_dotenv(override=True)
This loads the variables from your .env file into the application’s environment.
What does override=True mean?
Suppose an environment variable already exists:
OPENAI_API_KEY=old-key
and your .env file contains:
OPENAI_API_KEY=new-key
the value from .env can override the existing environment variable.
Import OpenAI Agents SDK classes
from openai.types.responses import ResponseTextDeltaEvent
This imports ResponseTextDeltaEvent , It is important for streaming responses.
from agents import Agent, Runner, trace, function_tool, SQLiteSession
Here we import several components from the Agents SDK. Used to create an AI agent.
agent = Agent(...)
Runner:
Runner executes the agent.
result = await Runner.run(agent, "Tell me a joke")
trace:
trace helps you monitor and inspect what happens during an agent execution.
with trace("Telling a joke"):
You are basically giving the execution a trace name , This becomes useful when debugging and observing agent workflows.
function_tool:
This is used to convert a Python function into a tool that an agent can call.
@function_tool
def get_weather(city):
return "Sunny"
The agent can then potentially use that function as a tool. However, your current code does not use function_tool.
SQLiteSession:
This can be used to maintain conversation/session state using SQLite.
For example, an agent can maintain context across multiple interactions. Again, your current code imports it but doesn’t use it.
Create an Agent
agent = Agent(
name="Agent Rakesh",
instructions="You are a joke teller",
model="gpt-5.4-mini"
)
This is one of the most important parts of the code. You are creating an AI agent named.
Agent Rakesh
Let’s break it down.
name:
name="Agent Rakesh"
This gives your agent a name.
instructions:
instructions="Agent Rakesh are a joke teller"
These are the instructions given to the agent , You are telling the model .
"Your job is to tell jokes."
This is similar to a system instruction or agent behavior definition.
model:
model="gpt-5.4-mini"
Run the Agent
result = await Runner.run(
agent,
"Tell a joke about Autonomous AI Agents"
)
This executes the agent.
await Runner.run(...)
Runner.run() is an asynchronous operation. The program may need to wait for the model/API response.
await means approximately:
"Wait for this operation to finish before continuing."
Print the final answer:
print(result.final_output)
The result contains information about the agent execution.final_output gives you the final response generated by the agent.
See the LLM input details:
result.to_input_list()
Complete Flow:
our code demonstrates three important ways of working with an Agent:
