Learn how to build modern AI agents with the OpenAI Agents SDK, which enables developers to construct agentic systems in Python through a production-grade framework. This guide walks through setting up the SDK, testing basic agents, integrating tools, enabling agent handoffs, adding guardrails, managing user context, and optimizing with tracing.
What You Need to Get Started
To begin, ensure you have the following:
prerequisites
- Python 3.8 or higher installed.
- Basic Python programming knowledge, including familiarity with OOP concepts and large language models (LLMs).
- SDK and dependencies installed via
pip. - An OpenAI API key for accessing LLMs.
Step-by-Step Guide to Setting Up the OpenAI Agents SDK
Follow these steps to install and initialize the OpenAI Agents SDK.
steps
Install the SDK using pip:
bashpip install openai-agents-sdkVerify the installation with a basic Python import:
pythonimport openai_agents_sdk print("SDK imported successfully!")Set up your environment variables:
- Create an
.envfile and include your OpenAI API key:OPENAI_API_KEY=<your-api-key> - Use
dotenvor any configuration library to load the key in your Python project.
- Create an
Creating Your First Basic Agent
Here, we define a simple agent that takes user input, processes it through an LLM, and returns a result.
steps
Import the necessary libraries and set up your API configuration:
pythonfrom openai_agents_sdk import AgentRunner, SimpleAgent agent = SimpleAgent( name="basic_agent", model="gpt-4", instructions="You are an assistant who writes haikus about programming." )Write a prompt and execute the agent:
pythondef main(): runner = AgentRunner() user_prompt = "Write a haiku about recursion." response = runner.run(agent, user_prompt) print(response) if __name__ == "__main__": main()
Structuring Agent Outputs
Agents can provide consistent, structured responses by using classes to define the output schema.
steps
Create a data class for structured outputs:
pythonfrom dataclasses import dataclass @dataclass class TravelPlan: destination: str duration: str budget: float activities: list notes: strConfigure the agent to use structured outputs:
pythontravel_agent = SimpleAgent( name="travel_assistant", model="gpt-4", instructions="Plan trips with a focus on activities, budget, and notes.", output_type=TravelPlan )Test structured responses:
pythondef test_agent(): runner = AgentRunner() query = "Plan a 5-day trip to Miami with a $2000 budget" result = runner.run(travel_agent, query) print(result) test_agent()
Implementing Tools for Agent Interactions
Add tools that allow your agent to interact with external resources, such as API calls or data retrieval.
steps
Define a mock weather forecast tool:
pythonfrom openai_agents_sdk.tools import tool @tool def get_weather(city: str, date: str): """ Fetch weather data for a city on a given date. """ weather_data = { "Miami": "Sunny, 25-35°C", "Paris": "Cloudy, 12-22°C" } return weather_data.get(city, "Weather data unavailable.")Integrate the tool into the agent:
pythontravel_agent_with_tools = SimpleAgent( name="travel_assistant_with_tools", model="gpt-4", instructions="Use weather data to suggest activities.", tools=[get_weather] )Test the tool integration:
pythonrunner = AgentRunner() query = "Suggest activities in Miami on 2023-12-01." response = runner.run(travel_agent_with_tools, query) print(response)
Setting Up Multi-Agent Systems with Handoffs
Enable sophisticated workflows by coordinating multiple specialized agents.
steps
Define specialized agents:
pythonflight_agent = SimpleAgent( name="flight_specialist", model="gpt-4", instructions="Provide flight options based on user preferences." ) hotel_agent = SimpleAgent( name="hotel_specialist", model="gpt-4", instructions="Recommend hotels within user budget." )Configure handoffs in the main travel agent:
pythontravel_agent = SimpleAgent( name="travel_assistant", model="gpt-4", instructions="Coordinate flights and hotels for user trips.", handoffs=[flight_agent, hotel_agent] )Test inter-agent collaboration:
pythonqueries = ["Find flights from NYC to London.", "Find Paris hotels under $300."] for q in queries: response = runner.run(travel_agent, q) print(response)
Guardrails and Context Management
Use guardrails to validate agent inputs and manage metadata-rich context for agent behavior.
steps
Add input guardrails:
python@tool def budget_guardrail(destination: str, duration: int, budget: float): if budget < 500 or duration > 14: return f"Budget unrealistic for {destination} with a stay duration of {duration} days." return "Budget is feasible."Create contextual user preferences:
python@dataclass class UserContext: preferred_airlines: list hotel_amenities: list max_budget: floatApply guardrails and context:
pythontravel_agent_with_context = SimpleAgent( name="travel_assistant", model="gpt-4", instructions="Use context and guardrails to plan trips.", input_guardrails=[budget_guardrail], user_context=UserContext(preferred_airlines=["Delta"], hotel_amenities=["WiFi"], max_budget=2000) )
Tracing and Monitoring Agent Operations
Set up tracing for debugging and monitoring production-ready agents.
FAQ
How do I add OpenAI Agents SDK handoffs between multiple agents?
Simply define specialized agents and add them to the handoffs list in the primary agent. At runtime, requests automatically forward to appropriate agents.
Can the OpenAI Agents SDK use custom LLMs?
Yes, the SDK supports integration with OpenAI-compatible third-party APIs like OpenRouter or local models such as Alpaca. Configure custom clients as needed.
What are guardrails in OpenAI Agents SDK?
Guardrails validate inputs or outputs to prevent unrealistic or unsafe agent behavior, enhancing robustness for production.
How can I monitor agent performance?
Use tracing with OpenAI's dashboard or external monitoring tools like Logflare to analyze execution sequences, flags, and outputs.
Official reference: OpenAI Agents SDK documentation.