Saltar al contenido

Lección 12 · Tool Calling and Agents

The OpenAI Agents SDK

Learn the OpenAI Agents SDK: agents, the runner, function tools and handoffs, how it compares with the hosted Agents API, and when to keep things simple.

In function calling you wrote the loop yourself: call the model, run tools, send results back, repeat. An agent is a model with instructions and tools that works through such a loop toward a goal. The Agents SDK is a library from OpenAI that runs the loop for you and adds ways to combine several agents.

You will see the core pieces, build a tiny stand-in of the same ideas, and learn when you do not need an agent at all.

Two products with similar names

As of December 2026, OpenAI's agents guide describes two options.

Agents SDK Agents API
Where the loop runs In your application On OpenAI's managed infrastructure
Who manages state and runtime You The service saves sessions and turns
Control High Less code, less control

The Agents API was introduced as a public beta in September 2026. Check its current status, features and pricing before you build on it. This lesson focuses on the SDK, because the ideas stay useful in both.

OpenAI's visual Agent Builder had a shutdown date of November 30, 2026. The suggested replacements are the Agents SDK or ChatGPT workspace agents. Skip tutorials that start in Agent Builder.

Install and run one agent

Terminal
pip install openai-agents
Python
# Read-only: set OPENAI_API_KEY first
import asyncio
from agents import Agent, Runner

tutor = Agent(
    name="SQL tutor",
    instructions="Explain SQL ideas with short examples.",
    model="gpt-6.2-sol",
)

async def main():
    result = await Runner.run(tutor, "What does GROUP BY do?")
    print(result.final_output)

asyncio.run(main())

The pieces are simple. An Agent holds a name, instructions, a model and optionally tools. Runner.run is asynchronous and runs the loop until there is a final result, which you read from final_output. If async is new, see asyncio.

Add a function tool

The decorator @function_tool turns a typed Python function into a tool. The type hints and the docstring describe it to the model, so write them carefully.

Python
# Read-only
from agents import Agent, function_tool

@function_tool
def get_table_columns(table: str) -> str:
    """Return the column names of one table in the demo database."""
    schema = {"books": "id, title, price", "authors": "id, name"}
    return schema.get(table, "unknown table")

tutor = Agent(
    name="SQL tutor",
    instructions="Check column names with the tool before writing a query.",
    tools=[get_table_columns],
    model="gpt-6.2-sol",
)

The current SDK documentation also shows a @tool decorator, imported from agents.decorators. The package still exports function_tool. Check the documentation for the version you install.

The SDK saves you from writing schemas by hand, but it does not decide what is safe. Permission checks, input validation and approvals are still your job inside the function or around it.

Handoffs between agents

With a handoff, one agent passes the conversation to a specialist. A triage agent lists the specialists in handoffs. Each specialist has a handoff_description that tells the triage agent when to choose it.

Python
# Read-only
billing = Agent(name="Billing", handoff_description="Invoices and payments.",
                instructions="Answer billing questions.", model="gpt-6.2-sol")
technical = Agent(name="Technical", handoff_description="Errors and setup.",
                  instructions="Help with technical problems.", model="gpt-6.2-sol")

triage = Agent(name="Triage", instructions="Send each question to the right specialist.",
               handoffs=[billing, technical], model="gpt-6.2-sol")

After a run, result.last_agent tells you which agent produced the answer. Record it, because a wrong handoff is a common failure that you will want to count.

See the idea in plain Python

This stand-in routes with simple keyword rules, so you can see the structure of agents, tools and handoffs. A real triage agent uses a model to decide, which is more flexible and less predictable.

Python Stand-in: triage and handoff

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Try the question "I was charged twice." The keyword rules miss it. This shows why routing needs a test set, whatever method you use.

Guardrails, limits and tracing

A guardrail is a check around an agent, for example on the user's input or the final output. The SDK has features for guardrails, approvals and tracing, which records the steps of a run. Read the SDK documentation for the current interfaces. Whatever library you use, decide these things:

  • A maximum number of turns, and a time and cost budget.
  • Which actions need human approval.
  • What happens when a tool fails.
  • What you log, and how you protect logged data. Traces can contain user messages and tool results.

Do you need an agent?

Use the simplest design that works.

  1. One request if one prompt can do the job.
  2. A fixed workflow if the steps are known: your code calls the model at each step.
  3. An agent only when the steps depend on what the model discovers.

Fixed workflows are cheaper, easier to test and easier to explain. More agents add more calls and more places to fail. Read workflows versus agents before you design a team of them. The AI agents tutorial covers patterns in depth.

An agent with broad tools and no limits can repeat an action many times. Add limits and approvals before you connect it to anything real, and test it against fake services first.

Debugging an agent run

When an agent gives a bad result, look at the whole path, not only the last message. Which agent handled the request? Which tools did it call, with what arguments, and what came back? Did it hand off? How many turns did it take? Tracing helps you answer these questions.

Common causes are easy to name. Two agents have overlapping descriptions, so routing is random. A tool description is vague, so the agent calls the wrong one. A tool returns far too much text, which hides the important fact. Instructions ask for something no available tool can do, so the agent invents it.

Fix the smallest cause you can find, then rerun your examples. For tests, replace real tools with fakes that return fixed values, so that a test never sends an email or changes real data. Keep a few examples where the correct behavior is to refuse or to ask a question, because agents can be too eager to act.

Common mistakes

  • Building several agents before one agent, or one prompt, has been tested.
  • Believing that an instruction such as always ask first is the same as an approval step in code.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Where does the Agents SDK's loop run?

    With the SDK you control deployment, storage and approvals. The Agents API is the managed option.
  2. 2. What describes a function tool to the model in the SDK?

    Clear types and docstrings help the model choose and call the tool well.
  3. 3. What is a handoff?

    A triage agent can route work to specialists listed in its handoffs.
  4. 4. When is a fixed workflow better than an agent?

    Known steps can be coded directly, which is easier to test and cheaper.

Summary

  • The Agents SDK runs the tool loop in your app; the Agents API is a managed alternative.
  • Core pieces are Agent, Runner, @function_tool and handoffs.
  • The SDK does not replace permissions, approvals or limits.
  • Test routing and trace runs while protecting data.
  • Prefer one request or a fixed workflow when that is enough.

Next: Embeddings

Tu progreso se guarda en este navegador. No necesitas una cuenta.