What is OpenAI Agent SDK with Examples

The OpenAI Agent SDK is a Python framework designed to simplify the creation of AI agents while providing powerful features for production use. Let’s explore what makes this SDK special and see it in action.

Understanding the OpenAI Agent SDK

The OpenAI Agent SDK follows two core design principles:

  1. Simplicity with Power: Enough features to be genuinely useful, but few enough primitives to learn quickly
  2. Customizable Defaults: Works great out of the box, but allows deep customization when needed

This approach makes it accessible for beginners while remaining powerful enough for complex production systems.

Key Features Overview

1. Built-in Agent Loop

The SDK handles the complete agent execution cycle automatically:

  • Calls tools when needed
  • Sends results back to the LLM
  • Continues looping until the task is complete

2. Python-First Design

Instead of learning new abstractions, you use familiar Python features to orchestrate agents:

from agents import Agent, Runner
# Create an agent using standard Python
agent = Agent(
name="DataAnalyst",
instructions="You analyze data and provide insights"
)
# Run it with simple function calls
result = Runner.run_sync(agent, "Analyze this dataset...")

3. Handoffs Between Agents

Coordinate multiple specialized agents seamlessly:

# Agent A can hand off to Agent B
def transfer_to_specialist():
return specialist_agent
agent_a.tools = [transfer_to_specialist]

4. Automatic Session Management

No manual conversation history handling - the SDK manages it all:

# Sessions automatically track conversation history
session = Session()
result1 = Runner.run_sync(agent, "Hello", session=session)
result2 = Runner.run_sync(agent, "What did I just say?", session=session)
# Agent remembers the previous "Hello"

5. Function Tools with Auto-Schema

Turn any Python function into an agent tool:

def get_weather(city: str, country: str = "US") -> str:
"""Get current weather for a city."""
# Implementation here
return f"Weather in {city}: Sunny, 72°F"
# Automatically becomes a tool with proper schema
agent = Agent(
name="WeatherBot",
instructions="Help users with weather information",
tools=[get_weather]
)

6. Built-in Guardrails

Run validation checks in parallel with your agents:

def content_filter(message: str) -> bool:
"""Check if content is appropriate."""
return not any(word in message.lower() for word in ["spam", "inappropriate"])
agent = Agent(
name="ChatBot",
instructions="Be helpful and appropriate",
guardrails=[content_filter]
)

7. Comprehensive Tracing

Built-in monitoring and debugging capabilities:

  • Visualize agent workflows
  • Debug complex interactions
  • Monitor performance metrics
  • Integration with OpenAI’s evaluation tools

Installation and Setup

Getting started is straightforward:

Terminal window
pip install openai-agents

Set your OpenAI API key:

Terminal window
export OPENAI_API_KEY=sk-your-api-key-here

Hello World Example

Let’s start with the simplest possible agent:

from agents import Agent, Runner
# Create a basic assistant agent
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant"
)
# Run the agent with a simple query
result = Runner.run_sync(
agent,
"Write a haiku about recursion in programming."
)
print(result.final_output)
# Output:
# Code within the code,
# Functions calling themselves,
# Infinite loop's dance.

Practical Example: Calculator Agent

Here’s a more practical example with custom tools:

from agents import Agent, Runner
def add_numbers(a: float, b: float) -> float:
"""Add two numbers together."""
return a + b
def multiply_numbers(a: float, b: float) -> float:
"""Multiply two numbers together."""
return a * b
def divide_numbers(a: float, b: float) -> float:
"""Divide first number by second number."""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# Create calculator agent with math tools
calculator_agent = Agent(
name="Calculator",
instructions="""You are a helpful calculator assistant.
Use the provided tools to perform mathematical operations.
Always show your work and explain the steps.""",
tools=[add_numbers, multiply_numbers, divide_numbers]
)
# Test the calculator
result = Runner.run_sync(
calculator_agent,
"What is (15 + 25) * 3, then divide that result by 4?"
)
print(result.final_output)
# The agent will use tools step by step:
# 1. add_numbers(15, 25) = 40
# 2. multiply_numbers(40, 3) = 120
# 3. divide_numbers(120, 4) = 30
# Final answer: 30

Here’s a more advanced example that demonstrates real-world utility:

import requests
from agents import Agent, Runner
def search_web(query: str, num_results: int = 3) -> str:
"""Search the web for information about a topic."""
# Simplified example - in practice, use a proper search API
return f"Search results for '{query}': [Mock results would go here]"
def summarize_text(text: str, max_length: int = 200) -> str:
"""Summarize a piece of text to a specified length."""
# Simplified - in practice, you might use another LLM call
words = text.split()
if len(words) <= max_length:
return text
return " ".join(words[:max_length]) + "..."
research_agent = Agent(
name="ResearchAssistant",
instructions="""You are a research assistant that helps users find and
summarize information. Use web search to find relevant information,
then provide clear, concise summaries.""",
tools=[search_web, summarize_text]
)
# Use the research assistant
result = Runner.run_sync(
research_agent,
"Research the latest developments in quantum computing and provide a summary"
)
print(result.final_output)

Understanding Agent Responses

When you run an agent, you get a comprehensive result object:

result = Runner.run_sync(agent, "Hello world")
# Access different parts of the response
print(result.final_output) # The final response text
print(result.usage) # Token usage information
print(result.tool_calls) # Tools that were called
print(result.conversation) # Full conversation history

Error Handling and Validation

The SDK provides robust error handling:

from agents import Agent, Runner
from agents.exceptions import AgentError
def risky_operation(value: int) -> str:
"""An operation that might fail."""
if value < 0:
raise ValueError("Value must be positive")
return f"Processed: {value}"
agent = Agent(
name="RiskyAgent",
instructions="Use the risky operation tool carefully",
tools=[risky_operation]
)
try:
result = Runner.run_sync(agent, "Process the value -5")
except AgentError as e:
print(f"Agent error: {e}")
# The agent will handle the tool error gracefully

Next Steps

Now that you understand what the OpenAI Agent SDK is and have seen basic examples, you’re ready to dive deeper. In the next part of this series, we’ll explore:

  • Advanced agent configuration options
  • Working with sessions and conversation history
  • Streaming responses for real-time applications
  • Debugging and monitoring your agents
  • Best practices for production deployment

The foundation you’ve learned here - understanding agents, tools, and basic execution - will serve as the building blocks for more sophisticated systems.

Key Takeaways

  • The OpenAI Agent SDK simplifies AI agent creation while providing powerful features
  • Agents can use custom Python functions as tools with automatic schema generation
  • The built-in agent loop handles complex tool calling and conversation management
  • Sessions provide automatic conversation history management
  • The SDK is designed for both rapid prototyping and production use

Ready to build more sophisticated agents? Let’s continue to Part 2!

Share Feedback