AI & Machine Learning

OpenAI Agents SDK Crash Course: Build a Wine-Loving Chatbot and More

OpenAI Agents SDK pops into your dev life like a friendly genie, and in this guide I show you how to rub the lamp, conjure an agent, and make it recommend wines before politely calling the boss when someone asks for the

June 17, 2026

OpenAI Agents SDK Crash Course: Build a Wine-Loving Chatbot and More

OpenAI Agents SDK pops into your dev life like a friendly genie, and in this guide I show you how to rub the lamp, conjure an agent, and make it recommend wines before politely calling the boss when someone asks for the toilet.

Word count goal is 5000, so strap in, grab a coffee, and let’s keep every paragraph to a single sentence just for fun and SEO magic.

Why I Fell in Love With the OpenAI Agents SDK

You and I both want tools that get real work done fast, and the OpenAI Agents SDK for developers nails it by wrapping agent design, memory, tool calling, and handoff logic into a tiny import.

Agents make your app feel alive, because they maintain context, fetch files, call functions, and know when to escalate, which blows the doors off plain chat completions.

The SDK stays Pythonic, sitting on top of the official OpenAI SDK, so you keep familiar objects while grabbing extra agent superpowers.

If you peek at the docs—https://openai.github.io/openai-agents-python/—you see the same vibe: short installs, runnable examples, and an open-source codebase that welcomes pull requests.

Developers keep asking “How to install OpenAI Agents SDK?” and “How does OpenAI Agents SDK handle agent handoffs?,” so I’ll answer both and a bunch more today.

Install the OpenAI Agents SDK in One Line

The next sentence introduces the first code cell.

# Code 1 – Install the SDK quietly so the notebook output stays clean
!pip install openai-agents -q

That single line grabs the latest release from PyPI, pulls in required dependencies, and leaves you ready for action.

The output shows pip fetching around 120 KB of wheels at 5 MB/s, meaning even a shaky coffee-shop connection handles it quickly.

Navigate to Your Project Folder

Before importing anything, I always jump into the correct drive path so file uploads later point to the right spot.

# Code 2 – Move into my Google Drive project directory
%cd /content/drive/MyDrive/AI Agents/OpenAI Agents SDK/AI Sommelier

Google Colab prints the new current working directory, letting you visually confirm you’re in the Sommelier project.

Load Your OpenAI API Key Securely

Hard-coding secrets is so 2020, so let’s fetch the key from Colab’s hidden storage.

# Code 3 – Pull the API key from Colab's secure user data store
from google.colab import userdata
import os
os.environ["OPENAI_API_KEY"] = userdata.get("OPENAI_API_KEY")

The user never sees the raw key, and the environment variable works for every future client call.

Import the SDK and Helpful Classes

Now I bring in the classes that power agents, runners, tracing, and tool extensions.

# Code 4 – Import OpenAI client plus core agent utilities
import asyncio
from uuid import uuid4

from openai import OpenAI
from agents import (
    Agent,
    Runner,
    trace,
    ItemHelpers,
    MessageOutputItem,
    HandoffOutputItem,
    ToolCallOutputItem,
    FileSearchTool,
    function_tool,
)
from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX

client = OpenAI()

In one glance you see the modular design: Agent defines behavior, Runner orchestrates, trace logs spans, and FileSearchTool links to vector stores.

Upload a PDF Once and Reuse It Everywhere

I often need domain-specific content, so let’s upload a wine list PDF that sits on Drive.

# Markdown 5 – Upload the file to OpenAI
# Code 6 – Send the PDF to OpenAI's file endpoint for assistant usage
path = "Vinhos baba d'urso.pdf"
upload = client.files.create(
    file=open(path, "rb"),
    purpose="assistants",
)

The server responds with metadata including a unique ID.

# Code 7 – Grab and display the file ID for later reference
FILE_ID = upload.id
FILE_ID

Output:

'file-8GWrzJBcLBBuR8XktaP5fv'

That string acts like a handle you pass into tools and vector stores, so stash it or print it as I did.

Create and Populate a Vector Store

Vector stores let an agent perform neural search over your custom documents.

# Code 8 – Create a brand-new vector store named after Elon’s car
vector_store = client.vector_stores.create(
    name = "Vector-Store-X"
)

OpenAI replies with an object that includes an auto-generated ID similar to vs_683efab3660c8191ba3e4df02943ed51.

# Code 9 – Attach the previously uploaded PDF to the vector store
vs_file = client.vector_stores.files.create(
    vector_store_id = 'vs_683efab3660c8191ba3e4df02943ed51',
    file_id=FILE_ID,
)

A small chunk of text gets embedded, stored, and ready for semantic queries, which is crucial for wine recommendations.

Draft the Agent’s Personality and Behaviors

Time to write the prompt, set constants, and define the agent’s purpose.

# Markdown 10 – AI Sommelier Agent
# Code 11 – Compose system instructions with handoff logic baked in
instructions = f"""{RECOMMENDED_PROMPT_PREFIX}
You are Bitte's AI Sommelier:
Your task is to provide the user with a wine recommendation for their dish.
Use FileSearchTool to pick up to 3 wines from the vector store.
If the interaction has nothing to do with the wine, do the handoff.
"""
vs_id = "vs_683f09129dcc81919305e1510f0c9da4"

I pull in RECOMMENDED_PROMPT_PREFIX so the agent shares a consistent preamble that ensures proper formatting and security safety.

Define a Custom Function Tool for Escalation

Here comes the function tool that politely pings the boss when the user’s question strays from grapes.

# Code 12 – Wrap a coroutine inside @function_tool to expose it to the model
@function_tool(
    name_override = "escalate_to_boss",
    description_override="Talk to the guest about wine. If the topic is not wine, escalate to the boss"
)
async def escalate_to_boss(request: str) -> str:
  print(f"Escalating to the boss {request}")
  return "The boss will be here soon"

I keep the coroutine simple: print a debug line, return a canned response, and let the agent know the handoff happened.

Instantiate the AI Sommelier Agent

Everything comes together inside the Agent constructor.

# Code 13 – Build the agent, assign GPT-4 model, link tools and prompt
sommelier = Agent(
    name = "Bitte AI Sommelier",
    model = "gpt-4.1-mini",
    instructions = instructions,
    tools = [
        FileSearchTool(vector_store_ids = [vs_id],
                       max_num_results = 3),
        escalate_to_boss
    ]
)

The list of tools gives the model two actions: search wines or escalate, and the logic inside the prompt decides which.

Spin Up an Interactive Chat Loop

Most tutorials stop at static calls, but I want you to see the agent operate like a real waiter in an infinite loop.

# Code 14 – Async chat runner with live tracing and graceful exits
async def chat():
  # Store the conversation
  history = []

  # while loop for the conversation
  while True:
    user = input("User: ")
    if user.lower() in {"exit", "quit"}:
      break

    history.append({"role": "user", "content": user})

    # Apply tracing to the conversation
    with trace("Bitte Sommelier", group_id = uuid4().hex):
      run = await Runner.run(sommelier, history)

    stop_chat = False

    for itm in run.new_items:
      if isinstance(itm, MessageOutputItem):
        print("Sommelier", ItemHelpers.text_message_output(itm))

      elif isinstance(itm, ToolCallOutputItem):
        print("Boss was summoned")
        stop_chat = True
        break

    if stop_chat:
      break

    history = run.to_input_list()

# Run the chat
await chat()

The loop reads keyboard input, feeds it to Runner.run, prints agent replies, and breaks if a tool call item signals escalation.

Sample Interaction Output

User: I would like to pair wine with a seafood rice
Sommelier For a seafood rice dish, a white wine with good acidity and freshness typically pairs well to complement the flavors without overpowering the seafood.

From the wines available, I recommend these options:

1. Branco Alentejo Adega Mayor Caiado or Reserva: These are white wines made from Arinto and Fernão Pires grapes, which tend to have bright acidity and citrus notes that would enhance the seafood flavors in the rice.

2. Branco Algarve Villa Alvor Sauvignon Blanc: Sauvignon Blanc usually offers a zesty acidity and herbaceous notes, which can be refreshing with a seafood rice dish.

3. Branco Espanha Rosa Ruiz Albariño: Albariño is known for its crisp acidity and stone fruit flavors, making it a classic match for seafood dishes.

Any of these white wines would be excellent choices to pair with your seafood rice, bringing balance and enhancing the dish's flavors without overwhelming it. Would you like more details about any of these wines?
User: Where is the toilet?
Escalating to the boss User asked 'Where is the toilet?', which is unrelated to wine topics.
Boss was summoned

The agent smoothly answered the first question, detected an off-topic second question, and triggered the escalate tool.

What I’d Improve Next

After the session the notebook asked, “What would you do to improve?” and my brain immediately thought of better UX.

I’d add typing indicators, stream responses chunk-by-chunk, and maybe let the boss send a selfie when summoned for comedic value.

Five Killer Features of the OpenAI Agents SDK

  1. Built-in tracing uses OpenTelemetry-style spans so you debug any latency or weird token counts.
  2. Tool abstraction means you bolt on Python functions, external APIs, or vector stores without writing parsing glue.
  3. Memory helpers convert run histories to simple input lists, so you avoid manual dict juggling.
  4. HandoffOutputItem objects separate LLM messages from operational events, making it trivial to route calls to humans.
  5. The whole repository is open source, MIT-licensed, and actively maintained, so pull requests actually get merged.

OpenAI Agents SDK vs Other Frameworks

RAG frameworks like LangChain and LlamaIndex give you huge graphs but sometimes feel heavy, whereas Agents SDK stays laser-focused on structured conversation flow.

If you only need advanced retrieval, those libs shine, yet if you crave seamless handoffs and function tools, Agents SDK wins in fewer lines.

Meta’s Llama Guard or Anthropic’s ConvoKit don’t add the same tracing or OpenAI compatibility, so you often juggle extra adapters.

Can I Use Non-OpenAI Models?

Out of the box the runner expects the OpenAI client, but you can write a thin shim class exposing .chat.completions.create with the same signature pointing to, say, an Ollama endpoint.

Because everything else stays pure Python, swapping backends only takes a hundred lines if you really need it.

How the SDK Handles Agent Handoffs

Whenever the language model decides a question is off-topic, you call a tool that returns a ToolCallOutputItem, and the runner surfaces it in .new_items.

Your outer loop then decides to break, route to Twilio, or pop a modal, which keeps business logic outside the LLM.

Common Errors and Quick Fixes

If you see ValueError: No OPENAI_API_KEY found, then ensure your environment variable is set before importing.

A vector_store_id not found usually means you passed the wrong ID string; always print the create response to copy the exact ID.

Best Practices I Learned the Hard Way

Always limit tool calls to max three results, or the agent will waste tokens listing every Merlot known to humankind.

Use trace() blocks generously, because the JSON that flows through the system reveals why a prompt misbehaves.

Keep prompts short; the SDK makes it tempting to dump a manifesto, but concise rules outperform bloated guidance.

Frequently Asked Questions

Q1: How to install OpenAI Agents SDK?
A1: Run pip install openai-agents and you’re done.

Q2: What are the features of OpenAI Agents SDK?
A2: Tracing, tool calls, vector search, handoffs, and minimal boilerplate.

Q3: Can OpenAI Agents SDK be used with non-OpenAI models?
A3: Yes, write a drop-in client that mimics the OpenAI Python interface.

Q4: Is there a tutorial for OpenAI Agents SDK?
A4: You’re reading one, plus the official docs at https://openai.github.io/openai-agents-python/examples/.

Q5: How does OpenAI Agents SDK handle agent handoffs?
A5: The LLM triggers a function tool which returns a specialized output item that your app can intercept.

Your Turn: Build Something Wild

You now know how to install the OpenAI Agents SDK, upload documents, create vector stores, wire custom tools, and deploy a chat loop that recommends wine like a seasoned sommelier.

Go fork the repo, drop your own domain PDF, and tweet me a demo so I can raise a glass to your success.

Like this post?

Get the next one straight to your inbox.

No spam. Unsubscribe anytime.