🤖AI Agents Guide
TutorialsComparisonsReviewsExamplesIntegrationsUse CasesTemplatesGlossary
Get Started
🤖AI Agents Guide

Your comprehensive resource for understanding, building, and implementing AI Agents.

Learn

  • Tutorials
  • Glossary
  • Use Cases
  • Examples

Compare

  • Tool Comparisons
  • Reviews
  • Integrations
  • Templates

Company

  • About
  • Contact
  • Privacy Policy

© 2026 AI Agents Guide. All rights reserved.

Home/Examples/OpenAI Agents SDK Examples: 5 Real Builds
ExampleEngineering10 min read

OpenAI Agents SDK Examples: 5 Real Builds

Explore 5 concrete OpenAI Agents SDK examples showing agent handoffs, tool definitions, and multi-agent orchestration. Each example includes working Python code using the Agent and Runner pattern introduced in the official SDK.

Abstract visualization of AI neural network connections representing agent coordination
Photo by Growtika on Unsplash
By AI Agents Guide Team•February 28, 2026

Table of Contents

  1. Example 1: Basic Research Agent with Web Search Tool
  2. Example 2: Customer Support System with Agent Handoffs
  3. Example 3: Code Review Agent with Structured Output
  4. Example 4: Data Analysis Pipeline Agent
  5. Example 5: Document Processing Agent with Input Guardrails
  6. Choosing the Right OpenAI Agents SDK Pattern
  7. Getting Started
  8. Frequently Asked Questions
Robotic arm in a factory representing automated agent processes
Photo by Possessed Photography on Unsplash

The OpenAI Agents SDK introduced a clean, minimal API for building multi-agent systems: define an Agent with tools and instructions, use Runner.run() to execute it, and implement handoffs to transfer control between specialized agents. The pattern is more opinionated than LangChain but significantly simpler to reason about.

These five examples demonstrate the SDK's core patterns — from basic tool use to complex multi-agent triage systems — with working Python code you can adapt directly. For context on how the SDK compares to alternatives, see OpenAI Agents SDK vs LangChain.

First, install the SDK: pip install openai-agents


Example 1: Basic Research Agent with Web Search Tool#

Use Case: A simple research agent that answers questions by searching the web when its built-in knowledge is insufficient or potentially outdated.

Architecture: Single Agent with a web search function tool + Runner.run(). The agent decides when to invoke the tool based on its instructions.

Key Implementation:

import asyncio
from agents import Agent, Runner, function_tool
import httpx

@function_tool
async def search_web(query: str) -> str:
    """Search the web for current information on a topic."""
    # Production: use Tavily, Serper, or Brave Search API
    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://api.tavily.com/search",
            params={"query": query, "max_results": 3},
            headers={"Authorization": f"Bearer {TAVILY_API_KEY}"}
        )
        results = response.json()["results"]
        return "\n".join([f"- {r['title']}: {r['content'][:200]}" for r in results])

research_agent = Agent(
    name="Research Agent",
    model="gpt-4o",
    instructions="""You are a research assistant. For questions about current events
    or recent developments, always use the search_web tool to find accurate information.
    Summarize findings clearly and cite your sources.""",
    tools=[search_web]
)

async def main():
    result = await Runner.run(
        research_agent,
        input="What are the most significant AI agent framework releases in early 2026?"
    )
    print(result.final_output)

asyncio.run(main())

Outcome: A production-ready research agent in under 30 lines of code. The @function_tool decorator handles schema generation automatically from the function's type hints and docstring. Learn the full setup in the OpenAI Agents SDK tutorial.


Example 2: Customer Support System with Agent Handoffs#

Use Case: A customer support triage system where a front-line agent routes conversations to billing, technical support, or sales specialists based on the customer's need.

Architecture: Triage Agent + Billing Agent + Technical Agent + Sales Agent. Uses the handoff() function to transfer control. The triage agent never answers domain questions directly — it only routes.

Key Implementation:

import asyncio
from agents import Agent, Runner, handoff

billing_agent = Agent(
    name="Billing Specialist",
    model="gpt-4o-mini",
    instructions="""You handle billing questions: invoices, charges, upgrades,
    cancellations, and refunds. Resolve issues thoroughly and confirm next steps."""
)

technical_agent = Agent(
    name="Technical Support Engineer",
    model="gpt-4o",
    instructions="""You resolve technical issues: API errors, integration problems,
    configuration questions, and bug reports. Ask clarifying questions when needed."""
)

sales_agent = Agent(
    name="Sales Representative",
    model="gpt-4o-mini",
    instructions="""You help prospects understand pricing, features, and fit.
    You can offer trials and schedule demos. Never offer unauthorized discounts."""
)

triage_agent = Agent(
    name="Customer Support Triage",
    model="gpt-4o-mini",
    instructions="""You are the first point of contact. Greet the customer warmly,
    understand their need, then hand off to the right specialist:
    - Billing questions → billing_specialist
    - Technical issues → technical_support
    - Pricing or features → sales
    Do not attempt to answer domain-specific questions yourself.""",
    handoffs=[
        handoff(billing_agent, tool_description="Transfer to billing for payment and account questions"),
        handoff(technical_agent, tool_description="Transfer to technical support for product issues"),
        handoff(sales_agent, tool_description="Transfer to sales for pricing and upgrade questions")
    ]
)

async def main():
    result = await Runner.run(
        triage_agent,
        input="Hi, I was charged twice for my subscription this month and my API integration stopped working."
    )
    print(result.final_output)

asyncio.run(main())

Outcome: Clean separation of concerns with automatic routing. The triage agent stays in its lane, and specialists receive full conversation context. This pattern is compared in depth in LangChain vs CrewAI.


Example 3: Code Review Agent with Structured Output#

Use Case: An automated code reviewer that returns structured feedback as a typed Pydantic model, making it easy to parse and render in CI/CD pipelines.

Architecture: Single Agent with output_type=CodeReview Pydantic model. The SDK enforces the output schema, guaranteeing parseable structured output.

Key Implementation:

import asyncio
from agents import Agent, Runner
from pydantic import BaseModel
from typing import List, Literal

class ReviewIssue(BaseModel):
    line_range: str
    severity: Literal["critical", "high", "medium", "low", "info"]
    category: Literal["security", "performance", "style", "logic", "documentation"]
    description: str
    suggested_fix: str

class CodeReview(BaseModel):
    verdict: Literal["approved", "approved_with_suggestions", "changes_required", "rejected"]
    summary: str
    issues: List[ReviewIssue]
    positive_aspects: List[str]

code_reviewer = Agent(
    name="Code Reviewer",
    model="gpt-4o",
    instructions="""You are a senior software engineer conducting a thorough code review.
    Analyze the provided code for security vulnerabilities, performance issues, logic errors,
    and style problems. Be specific about line numbers and provide concrete fix suggestions.
    Output a structured review in the required format.""",
    output_type=CodeReview
)

async def review_code(code: str) -> CodeReview:
    result = await Runner.run(
        code_reviewer,
        input=f"Review this Python code:\n\n```python\n{code}\n```"
    )
    return result.final_output  # Already typed as CodeReview

async def main():
    sample_code = """
def get_user(user_id):
    query = f"SELECT * FROM users WHERE id = {user_id}"
    return db.execute(query)
    """
    review = await review_code(sample_code)
    print(f"Verdict: {review.verdict}")
    for issue in review.issues:
        print(f"[{issue.severity.upper()}] {issue.description}")

asyncio.run(main())

Outcome: Machine-readable code reviews that integrate directly into CI/CD tooling. The SQL injection vulnerability in the sample code will reliably surface as a critical security issue. See AI Agent Coding Examples for more development workflow patterns.


Robotic arm in a factory representing automated agent processes

Example 4: Data Analysis Pipeline Agent#

Use Case: An agent that accepts a natural language question about a dataset, generates the appropriate SQL query, executes it, and returns an interpreted answer with visualization recommendations.

Architecture: Agent with a run_sql_query tool + get_schema tool + structured output for query + interpretation. Uses guardrails to prevent destructive SQL.

Key Implementation:

import asyncio
from agents import Agent, Runner, function_tool, input_guardrail, GuardrailFunctionOutput
from pydantic import BaseModel
import sqlite3

DB_PATH = "analytics.db"

@function_tool
def get_database_schema() -> str:
    """Get the schema of all tables in the analytics database."""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.execute("SELECT name, sql FROM sqlite_master WHERE type='table'")
    return "\n".join([f"{row[0]}:\n{row[1]}" for row in cursor.fetchall()])

@function_tool
def run_sql_query(sql: str) -> str:
    """Execute a read-only SQL SELECT query and return results as CSV."""
    if not sql.strip().upper().startswith("SELECT"):
        return "Error: Only SELECT queries are permitted."
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.execute(sql)
    cols = [desc[0] for desc in cursor.description]
    rows = cursor.fetchmany(100)  # Limit results
    return ",".join(cols) + "\n" + "\n".join([",".join(str(v) for v in row) for row in rows])

class AnalysisResult(BaseModel):
    sql_query: str
    interpretation: str
    key_finding: str
    chart_recommendation: str

data_analyst = Agent(
    name="Data Analyst",
    model="gpt-4o",
    instructions="""You are a data analyst. When asked a question:
    1. Use get_database_schema to understand available tables
    2. Write an appropriate SQL SELECT query
    3. Execute with run_sql_query
    4. Interpret the results in plain language
    5. Recommend the best chart type to visualize the answer
    Always explain what the numbers mean in business terms.""",
    tools=[get_database_schema, run_sql_query],
    output_type=AnalysisResult
)

async def main():
    result = await Runner.run(
        data_analyst,
        input="Which product category had the highest revenue growth between Q3 and Q4 last year?"
    )
    analysis = result.final_output
    print(f"SQL: {analysis.sql_query}")
    print(f"Finding: {analysis.key_finding}")
    print(f"Chart: {analysis.chart_recommendation}")

asyncio.run(main())

Outcome: Self-documenting data analysis that produces both the query and its business interpretation. The Data Analyst Agent tutorial covers building a full production version.


Example 5: Document Processing Agent with Input Guardrails#

Use Case: A document intake agent that validates uploaded documents before processing, rejects irrelevant files, and routes compliant documents to specialized processing agents.

Architecture: Guardrail check → Document Classifier Agent → handoff to either Contract Agent, Invoice Agent, or Resume Agent. Uses input_guardrail to block non-document uploads.

Key Implementation:

import asyncio
from agents import Agent, Runner, handoff, input_guardrail, GuardrailFunctionOutput
from pydantic import BaseModel

class DocumentValidation(BaseModel):
    is_valid_document: bool
    rejection_reason: str

@input_guardrail
async def document_validator(ctx, agent, input: str) -> GuardrailFunctionOutput:
    """Reject inputs that don't appear to contain document content."""
    is_too_short = len(input.strip()) < 50
    is_question_not_doc = input.strip().endswith("?") and len(input) < 200

    if is_too_short or is_question_not_doc:
        return GuardrailFunctionOutput(
            output_info=DocumentValidation(
                is_valid_document=False,
                rejection_reason="Input does not appear to be a document. Please paste document content."
            ),
            tripwire_triggered=True
        )
    return GuardrailFunctionOutput(
        output_info=DocumentValidation(is_valid_document=True, rejection_reason=""),
        tripwire_triggered=False
    )

contract_agent = Agent(
    name="Contract Analyst",
    model="gpt-4o",
    instructions="Extract parties, obligations, key dates, and risk clauses from contracts."
)

invoice_agent = Agent(
    name="Invoice Processor",
    model="gpt-4o-mini",
    instructions="Extract vendor, amounts, line items, due date, and payment terms from invoices."
)

resume_agent = Agent(
    name="Resume Parser",
    model="gpt-4o-mini",
    instructions="Extract candidate name, contact info, skills, experience, and education from resumes."
)

document_classifier = Agent(
    name="Document Intake Classifier",
    model="gpt-4o-mini",
    instructions="""Classify the document type and route to the appropriate specialist:
    - Legal contracts or agreements → contract_analyst
    - Invoices or purchase orders → invoice_processor
    - Resumes or CVs → resume_parser
    Never process the document yourself — always route to a specialist.""",
    input_guardrails=[document_validator],
    handoffs=[
        handoff(contract_agent),
        handoff(invoice_agent),
        handoff(resume_agent)
    ]
)

async def main():
    # Test with an invoice
    invoice_text = """
    INVOICE #2026-0234
    From: Acme Supplies Inc. | To: Beta Corp
    Date: 2026-02-15 | Due: 2026-03-15
    Line Items:
    - Cloud Storage (500GB): $299.00
    - Support Plan (Annual): $1,200.00
    Total Due: $1,499.00
    """
    result = await Runner.run(document_classifier, input=invoice_text)
    print(result.final_output)

asyncio.run(main())

Outcome: A document intake pipeline with validation guardrails and automatic routing that handles contracts, invoices, and resumes with specialist agents. For related patterns, read about Human-in-the-Loop Agent Examples which shows how to add human review steps to similar pipelines.


Choosing the Right OpenAI Agents SDK Pattern#

The SDK's strength is its simplicity: the Agent → Runner → handoff pattern covers the majority of multi-agent use cases without requiring complex configuration. Use structured output (output_type) whenever downstream code needs to parse the result programmatically. Add guardrails at the input level for any agent that accepts untrusted external data.

For workflows requiring stateful checkpointing, parallel branches, or complex memory management, consider augmenting the SDK with LangGraph. The OpenAI Agents SDK vs LangChain comparison covers exactly when to make that tradeoff.

Getting Started#

The OpenAI Agents SDK tutorial is the fastest path to a running implementation. Install openai-agents, set your OPENAI_API_KEY, and you can have Example 1 running in under five minutes. For understanding the foundational concepts, What is an AI Agent provides the mental model that makes the SDK patterns easier to internalize.

Frequently Asked Questions#

The FAQ section renders from the frontmatter faq array above.

Related Examples

Agentic RAG Examples: 5 Real Workflows

Six agentic RAG examples with working Python code covering query routing, self-correcting retrieval with hallucination detection, multi-document reranking, iterative retrieval with web fallback, conversational RAG with memory, and corrective RAG with grade-and-retry loops.

7 AI Agent Coding Examples (Real Projects)

Discover 7 real-world AI coding agent examples covering code review, PR generation, test writing, bug diagnosis, documentation generation, and refactoring automation. Each example includes architecture details and working code for engineering teams.

AI Data Analyst Examples: 6 Real Setups

Explore 6 AI data analyst agent examples covering natural language SQL generation, automated chart creation, anomaly detection, report generation, and business intelligence workflows. Includes Python code for building production-ready data analysis agents.

← Back to All Examples