Skip to content
Learni
View all tutorials
Intelligence Artificielle

How to Master the OpenAI Agents SDK in 2026

Lire en français

Introduction

The OpenAI Agents SDK enables creation of autonomous agents capable of orchestrating complex tasks. Unlike simple API calls, it manages memory, tools, and reasoning loops. This tutorial guides you toward a scalable multi-agent architecture essential for enterprise applications in 2026.

Prerequisites

  • Python 3.11+
  • OpenAI API key with access to recent models
  • Solid knowledge of Pydantic and asyncio
  • Understanding of agent design patterns

Installation and Configuration

terminal
pip install openai-agents pydantic

export OPENAI_API_KEY="sk-..."

Installs the official SDK and configures the API key. Use a secrets manager in production to prevent leaks.

Defining a Basic Agent

agent_base.py
from agents import Agent, Runner
from pydantic import BaseModel

class ResearchAgent(Agent):
    name = "researcher"
    instructions = "You are an expert researcher. Use the tools to find precise information."
    model = "gpt-4o"

agent = ResearchAgent()
result = Runner.run_sync(agent, "Analyze the AI market in 2026")
print(result.final_output)

Creates a typed agent with clear instructions. Runner.run_sync enables simple synchronous execution for testing.

Adding Custom Tools

tools.py
from agents import function_tool

@function_tool
def search_web(query: str) -> str:
    """Search the web."""
    # Real implementation with Tavily or Serper
    return f"Results for {query}: market data 2026..."

agent.tools = [search_web]

The function_tool decorator turns your functions into tools the agent can use. Always validate inputs/outputs.

Multi-Agent Orchestration

orchestrator.py
from agents import Agent, Runner, handoff

researcher = Agent(name="researcher", instructions="...")
writer = Agent(name="writer", instructions="...")

handoff_tool = handoff(writer)
researcher.tools.append(handoff_tool)

result = Runner.run_sync(researcher, "Write a report on AI")

Handoff allows transferring control between agents. This creates collaborative workflows without infinite loops.

Advanced Context Management

context.py
from agents import Agent, Runner, RunContext

class MyContext(BaseModel):
    user_id: str
    session_data: dict

agent = Agent(
    name="contextual",
    instructions="Use context to personalize responses.",
    context=MyContext(user_id="123", session_data={})
)

result = Runner.run_sync(agent, "Recommend content", context=agent.context)

Pydantic enables typed and serializable context. Avoid passing too much data to stay under token limits.

Best Practices

  • Always type tool inputs/outputs with Pydantic
  • Limit tools per agent to 5-7 maximum
  • Implement timeouts and retries on external calls
  • Log every agent decision for debugging
  • Use reasoning models (o1) for critical tasks

Common Errors to Avoid

  • Forgetting to handle exceptions in tools (agent loops)
  • Passing overly large context and exceeding tokens
  • Not defining precise instructions (hallucinations)
  • Ignoring concurrent state management in production

Going Further

Deepen these concepts with our Learni training courses on advanced AI agent architectures.