AI Workflows

How to Build AI Agents with the OpenAI Agents SDK

Learn to develop agentic systems using OpenAI's Agents SDK, covering setup, structured outputs, tools, handoffs, guardrails, and tracing.

5 min read

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

  1. Install the SDK using pip:

    bash
    pip install openai-agents-sdk
  2. Verify the installation with a basic Python import:

    python
    import openai_agents_sdk
    print("SDK imported successfully!")
  3. Set up your environment variables:

    • Create an .env file and include your OpenAI API key:
      OPENAI_API_KEY=<your-api-key>
    • Use dotenv or any configuration library to load the key in your Python project.

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

  1. Import the necessary libraries and set up your API configuration:

    python
    from openai_agents_sdk import AgentRunner, SimpleAgent
    
    agent = SimpleAgent(
        name="basic_agent",
        model="gpt-4",
        instructions="You are an assistant who writes haikus about programming."
    )
  2. Write a prompt and execute the agent:

    python
    def 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

  1. Create a data class for structured outputs:

    python
    from dataclasses import dataclass
    
    @dataclass
    class TravelPlan:
        destination: str
        duration: str
        budget: float
        activities: list
        notes: str
  2. Configure the agent to use structured outputs:

    python
    travel_agent = SimpleAgent(
        name="travel_assistant",
        model="gpt-4",
        instructions="Plan trips with a focus on activities, budget, and notes.",
        output_type=TravelPlan
    )
  3. Test structured responses:

    python
    def 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

  1. Define a mock weather forecast tool:

    python
    from 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.")
  2. Integrate the tool into the agent:

    python
    travel_agent_with_tools = SimpleAgent(
        name="travel_assistant_with_tools",
        model="gpt-4",
        instructions="Use weather data to suggest activities.",
        tools=[get_weather]
    )
  3. Test the tool integration:

    python
    runner = 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

  1. Define specialized agents:

    python
    flight_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."
    )
  2. Configure handoffs in the main travel agent:

    python
    travel_agent = SimpleAgent(
        name="travel_assistant",
        model="gpt-4",
        instructions="Coordinate flights and hotels for user trips.",
        handoffs=[flight_agent, hotel_agent]
    )
  3. Test inter-agent collaboration:

    python
    queries = ["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

  1. 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."
  2. Create contextual user preferences:

    python
    @dataclass
    class UserContext:
        preferred_airlines: list
        hotel_amenities: list
        max_budget: float
  3. Apply guardrails and context:

    python
    travel_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.