# OpenAI Agents SDK 0.26 in depth: the runner loop, handoffs, guardrails and approvals

The OpenAI Agents SDK reached version 0.26.0 on 24 November 2026. This guide walks through its runner loop step by step and builds a refund agent with handoffs, guardrails, sessions and human approval that runs offline with the SDK's scripted test model.

The OpenAI Agents SDK is a small Python library for building agents out of a few parts: an agent (a model with instructions and tools), handoffs between agents, guardrails that check inputs and outputs, sessions that keep history, and tracing that records each run. Version 0.26.0 shipped on PyPI on 24 November 2026, six days after 0.25.0. The release is mostly fixes, but the SDK has changed a lot since the summer: a new default model, a provider-neutral testing package, and stricter handling of paused runs.

This article explains how the SDK actually runs an agent, one step at a time. Then it builds a small customer-service system with a triage agent, a refunds agent, a guardrail and a human approval step. All code here ran on openai-agents 0.26.0 with Python 3.13, without an API key, by using the SDK's own `ScriptedModel` from `agents.testing`. You can swap in a real model with one line.

If you are new to agents, read [what an AI agent is](/articles/what-is-an-ai-agent-chatbot-workflow) and [the agent loop step by step](/articles/agent-loop-step-by-step-trace) first. If you want to compare this SDK with others, see [one agent built in seven frameworks](/articles/one-agent-seven-frameworks-compared).

## What happened

### OpenAI Agents SDK 0.26.0 ships with runtime fixes (24 November 2026)

Version 0.26.0 was uploaded to PyPI on 24 November 2026. Its release notes list one feature, an upgrade of the GPT-Live demo to 1.1, and fourteen bug fixes. Several of them matter for agent safety and correctness:

- "stop queued function tools after input guardrail rejection": if an input guardrail trips, tool calls that were already queued no longer run.
- "check Realtime output guardrails at turn completion".
- "preserve handoff redaction in Session history": redacted handoff data stays redacted when it is saved to a session.
- "give per-call MCP metadata priority over discovery defaults".
- "require application approval for local images in codex_tool".
- "honor the global tracing switch in Realtime".

Version 0.25.0 came out on 18 November 2026. If you pin versions, move to 0.26.0 for the guardrail fix above.

### A provider-neutral testing package arrives (15 August 2026)

Version 0.21.0 added `agents.testing`, `agents.realtime.testing` and `agents.voice.testing`. The key class is `ScriptedModel`: a fake model that returns a script of outputs you write in advance and records every call. This is what lets the examples below run offline. The same release moved the OpenAI dependency to `openai>=3.0.0,<4`.

### The default model changes (11 August 2026)

Version 0.20.0 changed the default model to `gpt-5.6-luna`. An explicit `model=` on the agent, a run-level override, or the `OPENAI_DEFAULT_MODEL` environment variable still win. We checked: `agents.models.get_default_model()` returns `gpt-5.6-luna` on 0.26.0. The same release added `RunState.add_input()` for adding user input to a paused run before the next model call.

## How the runner loop works

The SDK's core is `Runner`. You give it a starting agent and an input. The documentation describes the loop in three steps:

1. Call the model for the current agent with the current input.
2. Look at the output. If it is a final output (text of the right type and no tool calls), the loop ends. If it is a handoff, switch the current agent and loop again. If it is tool calls, run the tools, add their results to the input and loop again.
3. If the run goes past `max_turns`, raise `MaxTurnsExceeded`.

`max_turns` defaults to 10 in `Runner.run` on 0.26.0, and `max_turns=None` turns the limit off. Think of the runner as a switchboard operator. Each time the model speaks, the operator either hangs up (final answer), puts the call through to another desk (handoff) or goes to fetch a file and reads it back (tool call).

There are three ways to start a run:

| Method | Sync or async | Returns | Use it for |
|---|---|---|---|
| `Runner.run()` | async | `RunResult` | servers and most code |
| `Runner.run_sync()` | sync, wraps `run()` | `RunResult` | scripts and notebooks |
| `Runner.run_streamed()` | async | `RunResultStreaming` | showing tokens and events live |

### Why each turn costs more than the last

Every model call re-sends the instructions and the whole history so far. That makes the total input grow roughly with the square of the number of turns. Take a small example: 400 tokens of instructions, a 50-token user message, and each tool call plus its result adding 150 tokens.

- Turn 1 sends 450 tokens.
- Turn 2 sends 450 + 150 = 600 tokens.
- Turn 6 sends 450 + 5 x 150 = 1,200 tokens.
- The six turns together send 450 + 600 + 750 + 900 + 1,050 + 1,200 = 4,950 input tokens.

Six turns cost 11 times the first turn, not 6 times. This is why `max_turns` is a cost control as well as a safety net. The [agent loop token cost simulation](/ai-simulations/agent-loop-token-cost) lets you change these numbers.

```chart
{"type": "line", "title": "Input tokens per turn and cumulative, agent loop example", "x": ["1", "2", "3", "4", "5", "6"], "series": [{"name": "input tokens this turn", "data": [450, 600, 750, 900, 1050, 1200]}, {"name": "cumulative input tokens", "data": [450, 1050, 1800, 2700, 3750, 4950]}], "xlabel": "turn", "ylabel": "tokens", "note": "Computed in the worked example above: 450 tokens on turn 1, plus 150 tokens per earlier tool step."}
```

## The building blocks, with the exact API

The documentation names three core primitives: agents, handoffs or agents as tools, and guardrails. Sessions and tracing sit around them.

### Agents and function tools

An `Agent` is a dataclass. On 0.26.0 its fields include `name`, `instructions`, `tools`, `handoffs`, `model`, `model_settings`, `input_guardrails`, `output_guardrails`, `output_type`, `mcp_servers`, `hooks` and `tool_use_behavior`. The `@function_tool` decorator turns a Python function into a tool. It reads the type hints for the JSON schema and the docstring for the description. Its options include `needs_approval`, `timeout`, `strict_mode` (on by default), `tool_input_guardrails` and `tool_output_guardrails`.

### Handoffs versus agents as tools

A handoff passes the conversation to another agent, which then answers the user. The docs say handoffs "are represented as tools to the LLM". An agent named `Refund Agent` becomes a tool called `transfer_to_refund_agent`. The `handoff()` helper lets you change the tool name, run an `on_handoff` callback, pass typed arguments with `input_type`, and filter the history with `input_filter`.

`agent.as_tool()` is different. The SDK's docstring puts it this way: in a handoff the new agent receives the conversation history and takes over; as a tool, the new agent receives generated input and the calling agent stays in charge. Use a handoff when the specialist should own the rest of the conversation. Use `as_tool()` when a manager agent wants a sub-result and keeps control. The [multi-agent supervisor article](/articles/multi-agent-supervisor-handoffs-subagents) compares both patterns across frameworks.

### Guardrails

Guardrails come in three kinds, and the docs are precise about where each runs:

| Guardrail | Runs on | Timing | Exception when tripped |
|---|---|---|---|
| Input | first agent only | parallel by default, or blocking with `run_in_parallel=False` | `InputGuardrailTripwireTriggered` |
| Output | the agent that gives the final output | after that agent finishes | `OutputGuardrailTripwireTriggered` |
| Tool input / output | every guarded function-tool call | before / after the call | `ToolInputGuardrailTripwireTriggered` / `ToolOutputGuardrailTripwireTriggered` |

The parallel mode is a trade. The guardrail runs alongside the first model call, so it adds no delay when the input is fine. But if it trips, "the agent may already have used tokens or run tools". Here is a worked case. Say the guardrail takes 300 ms, the first model call takes 1,200 ms and uses 1,800 tokens, and 2% of 10,000 daily requests are bad.

- Parallel: time to the first answer is max(300, 1,200) = 1,200 ms. Bad requests still burn 10,000 x 0.02 = 200 model calls, or 200 x 1,800 = 360,000 tokens a day.
- Blocking: time to the first answer is 300 + 1,200 = 1,500 ms for every request. Bad requests burn no model tokens.

```chart
{"type": "bar", "title": "Input guardrail modes: latency vs wasted tokens", "x": ["parallel", "blocking"], "series": [{"name": "latency to first model answer (ms)", "data": [1200, 1500]}, {"name": "wasted tokens per day (thousands)", "data": [360, 0]}], "ylabel": "value", "note": "Computed in the worked example: 300 ms guardrail, 1,200 ms and 1,800-token model call, 10,000 requests a day, 2% tripped."}
```

If the agent can run tools that change things, choose blocking, or add a tool input guardrail. The 0.26.0 fix that stops queued tools after a guardrail trip narrows the gap, but blocking is still the safe default for actions. For a broader design, see [layered agent guardrails](/articles/layered-agent-guardrails-runnable-stack) and the [guardrails simulation](/ai-simulations/guardrails).

### Sessions

A session stores history so the next run can see it. The SDK fetches the history before each run and saves new items after it. `SQLiteSession("user_123")` keeps history in memory and loses it when the process ends; `SQLiteSession("user_123", "conversations.db")` writes to a file. The docs list other backends, including `RedisSession`, `SQLAlchemySession`, `MongoDBSession`, `DaprSession`, `OpenAIConversationsSession`, `AdvancedSQLiteSession`, `EncryptedSession` and `OpenAIResponsesCompactionSession`, which compacts long histories. A session cannot be combined with `conversation_id`, `previous_response_id` or `auto_previous_response_id` in the same run.

### Tracing

"Tracing is enabled by default." Each run becomes a trace called "Agent workflow", with spans for agents, model generations, function calls, guardrails and handoffs, plus task and turn spans. You can turn it off with `OPENAI_AGENTS_DISABLE_TRACING=1`, `set_tracing_disabled(True)` or `RunConfig.tracing_disabled`. Generation and function spans store inputs and outputs by default; set `RunConfig.trace_include_sensitive_data=False` to stop that. The docs warn that tracing is unavailable for organisations using OpenAI under Zero Data Retention. They also list processors that send traces to other tools, including LangSmith, Langfuse, Arize Phoenix, MLflow, Braintrust and Datadog. See [agent observability with Langfuse and OpenTelemetry](/articles/agent-observability-langfuse-opentelemetry-cost) for that route.

## Build it: a refund desk that runs offline

Install the SDK. The examples need nothing else.

```bash
pip install "openai-agents==0.26.0"
```

The first script has two agents. Triage hands off to Refunds. Refunds looks up the order with a tool and answers. An input guardrail blocks messages that look like they contain a card number. Each agent uses its own `ScriptedModel`, so we control what the "model" says.

```python
import asyncio
from agents import (Agent, Runner, function_tool, input_guardrail,
    GuardrailFunctionOutput, InputGuardrailTripwireTriggered, SQLiteSession,
    set_tracing_disabled)
from agents.testing import ScriptedModel, function_call, assistant_message

set_tracing_disabled(True)

@function_tool
def get_order(order_id: str) -> str:
    """Look up an order by id."""
    return '{"id": "%s", "total_eur": 120.0, "days_since_delivery": 9}' % order_id

@input_guardrail
async def no_card_numbers(ctx, agent, user_input):
    text = user_input if isinstance(user_input, str) else str(user_input)
    digits = sum(c.isdigit() for c in text)
    return GuardrailFunctionOutput(output_info={"digits": digits},
                                   tripwire_triggered=digits >= 13)

refunds_model = ScriptedModel([
    [function_call("get_order", {"order_id": "A-1042"}, call_id="call_1")],
    [assistant_message("Order A-1042 (120.00 EUR) is within the 14-day window. Refund approved.")],
])
triage_model = ScriptedModel([
    [function_call("transfer_to_refunds", {}, call_id="call_0")],
])

refunds = Agent(name="Refunds", instructions="Handle refunds. Always look up the order first.",
                model=refunds_model, tools=[get_order])
triage = Agent(name="Triage", instructions="Route the user to the right specialist.",
               model=triage_model, handoffs=[refunds], input_guardrails=[no_card_numbers])

async def main():
    session = SQLiteSession("user-42")
    result = await Runner.run(triage, "I want a refund for order A-1042",
                              session=session, max_turns=6)
    for item in result.new_items:
        print(type(item).__name__, "|", item.agent.name)
    print("last agent:", result.last_agent.name)
    print("final:", result.final_output)
    print("model calls:", len(triage_model.calls), len(refunds_model.calls))
    print("session items:", len(await session.get_items()))
    try:
        await Runner.run(triage, "My card is 4111 1111 1111 1111, refund me")
    except InputGuardrailTripwireTriggered as e:
        print("guardrail tripped:", e.guardrail_result.output.output_info)

asyncio.run(main())
```

The output on 0.26.0:

```text
HandoffCallItem | Triage
HandoffOutputItem | Triage
ToolCallItem | Refunds
ToolCallOutputItem | Refunds
MessageOutputItem | Refunds
last agent: Refunds
final: Order A-1042 (120.00 EUR) is within the 14-day window. Refund approved.
model calls: 1 2
session items: 6
guardrail tripped: {'digits': 16}
```

Read this as a trace of the loop. Turn 1: Triage's model asks for `transfer_to_refunds`, so the runner records a handoff call and output and switches agent. Turn 2: Refunds' model asks for `get_order`; the runner runs it and appends the result. Turn 3: Refunds' model returns plain text with no tool calls, so the loop ends. Three model calls in total, as the call counters show. The session now holds six items: the user message plus the five new items. The second run never reaches a model, because the guardrail counts 16 digits and trips. The [ReAct tool-calling simulation](/ai-simulations/react-tool-calling) animates this same call-observe-repeat cycle.

### Adding a human approval step

Refunds move money, so a person should approve them. Set `needs_approval=True` on the tool. The run then pauses and returns the pending call in `result.interruptions`. You turn the result into a `RunState`, approve or reject each item, and run again with the same top-level agent.

```python
from agents import Agent, Runner, function_tool, Usage, set_tracing_disabled
from agents.testing import ScriptedModel, function_call, assistant_message
import asyncio
set_tracing_disabled(True)

@function_tool(needs_approval=True)
def issue_refund(order_id: str, amount_eur: float) -> str:
    """Send money back to the customer."""
    return f"refunded {amount_eur:.2f} EUR on {order_id}"

model = ScriptedModel([
    [function_call("issue_refund", {"order_id": "A-1042", "amount_eur": 120.0}, call_id="c1")],
    [assistant_message("Done: 120.00 EUR refunded on A-1042.")],
], default_usage=Usage(requests=1, input_tokens=1800, output_tokens=60, total_tokens=1860))
agent = Agent(name="Refunds", instructions="Issue refunds.", model=model, tools=[issue_refund])

async def main():
    r1 = await Runner.run(agent, "Refund A-1042")
    print("paused:", [(i.raw_item.name, i.raw_item.arguments) for i in r1.interruptions])
    state = r1.to_state()
    for item in r1.interruptions:
        state.approve(item)
    r2 = await Runner.run(agent, state)
    print("final:", r2.final_output)
    u = r2.context_wrapper.usage
    print("usage:", u.requests, u.input_tokens, u.output_tokens, u.total_tokens)

asyncio.run(main())
```

```text
paused: [('issue_refund', '{"order_id":"A-1042","amount_eur":120.0}')]
final: Done: 120.00 EUR refunded on A-1042.
usage: 2 3600 120 3720
```

The tool did not run until `state.approve(item)` was called. Usage adds up across the pause: two model calls at 1,800 input and 60 output tokens each give 3,600 + 120 = 3,720 tokens. In production you save the paused run with `state.to_json()` or `state.to_string()` and load it later with `RunState.from_json()` or `RunState.from_string()`. The docs warn that these loaders "do not authenticate the snapshot or the person submitting it", so only load snapshots from storage you trust. See [human in the loop](/tools/human-in-the-loop) for the wider pattern.

To use a real model, delete the `model=ScriptedModel(...)` argument (the default model is used) or pass a model name such as `model="gpt-5.6-luna"`, and set `OPENAI_API_KEY`. Keep the scripted version as a unit test: it checks your tool wiring, handoffs and guardrails on every commit at zero cost.

## Use cases and examples

**Customer-service triage.** A support team routes chats to billing, refunds and technical agents with handoffs. Each specialist has two or three function tools. With the worked numbers above, a three-turn refund costs 450 + 600 + 750 = 1,800 input tokens, against 4,950 for a six-turn case, so the team sets `max_turns=6` and sends anything longer to a person.

**Money-moving back office.** A finance team lets an agent prepare refunds and credit notes but marks every payment tool `needs_approval=True`. Paused runs are stored with `state.to_json()` in a queue, and a reviewer approves them in a web page. The approval example shows that usage and history survive the pause.

**Research with a manager agent.** An analyst tool uses one manager agent that calls three specialists through `as_tool()`: search, summarise and check facts. The manager keeps control and writes the final answer. This keeps one voice for the user, unlike handoffs, where the last specialist answers.

**Regulated data intake.** A health-insurance intake form runs a blocking input guardrail (`run_in_parallel=False`) that rejects messages with card or ID numbers before any model call. From the worked example, blocking costs 300 ms per request but avoids 360,000 wasted tokens a day at a 2% trip rate. Tracing runs with `trace_include_sensitive_data=False`.

**CI tests for agent logic.** A platform team writes `ScriptedModel` scripts for its ten most common conversations. Each test checks which tools were called, with which arguments and in which order, using `model.calls`. Tests run offline in seconds, and `UnconsumedModelSteps` flags a script that the agent no longer follows.

## What it means in practice

The SDK is small on purpose. Its docs describe the goal as "enough features to be worth using, but few enough primitives to make it quick to learn." In practice that means you control the loop through a handful of settings: `max_turns`, guardrail modes, `needs_approval`, sessions and tracing switches. You do not draw a graph, as in [LangGraph](/tools/langgraph). If your workflow needs explicit branches, loops with checkpoints at every node, or time travel, a graph framework fits better. If it is "one agent with tools, maybe a few specialists", this SDK is short and readable.

Two defaults deserve attention. Tracing is on and stores inputs and outputs, which is useful in development and a privacy question in production. Input guardrails run in parallel, which is fast but lets a bad request use tokens and, before 0.26.0, possibly queue tools. Review both before launch.

## What to do now

1. **Pin the version.** Install `openai-agents==0.26.0` to get the fix that stops queued tools after an input guardrail trips.
2. **Set the model explicitly.** Do not rely on the default; pass `model=` on each agent so an SDK upgrade cannot change your model.
3. **Set `max_turns` from your data.** Count the turns of your normal cases and set the limit a little above, then route `MaxTurnsExceeded` to a person.
4. **Make action guardrails blocking.** Use `run_in_parallel=False` for any agent whose tools change data or move money.
5. **Require approval for risky tools.** Add `needs_approval=True`, or a function that decides per call, for payments, deletions and emails.
6. **Store paused runs safely.** Save `RunState` with `to_json()` in storage you control and check who approves before you load it.
7. **Decide what traces may hold.** Set `trace_include_sensitive_data=False` if prompts contain personal data, or send traces to your own backend through a processor.
8. **Write scripted tests.** Use `agents.testing.ScriptedModel` to test tool calls, handoffs and guardrails offline in CI.
9. **Choose a session backend early.** Use `SQLiteSession` locally and Redis, SQLAlchemy or an encrypted session in production.

## Risks and open questions

**Version churn is high.** The SDK released 0.20.0 in August and 0.26.0 in late November 2026, and some minor releases were flagged as potentially breaking. Pin exact versions and read each changelog before you upgrade.

**Parallel guardrails can still spend money.** Even after 0.26.0, a tripped parallel guardrail does not refund the tokens of a model call already in flight.

**Snapshots are not authenticated.** A stored `RunState` can be edited by anyone with write access to its storage. The SDK leaves signing and ownership checks to you.

**Nested handoff history is still beta.** The docs say nested handoff history is "an opt-in beta and is disabled by default", and nesting does not redact sensitive data.

**Tracing and data retention may conflict.** Teams on Zero Data Retention cannot use built-in tracing and need another processor.

**Watch next:** how the sandbox agents, which run specialists in isolated workspaces with Docker, Modal and other providers, settle into stable APIs, and whether the testing package grows matchers for tool arguments and handoff order.

## Frequently asked questions

### Do I need an OpenAI model to use the OpenAI Agents SDK?

No. The SDK talks to models through a `Model` interface, and `ScriptedModel` in this article is one implementation. The package also has optional extras such as `litellm` and `any-llm` for other providers. For OpenAI models it uses the Responses API by default.

### What is the difference between a handoff and an agent used as a tool?

In a handoff, the next agent receives the conversation and takes over the reply to the user. With `as_tool()`, the next agent gets generated input, returns a result, and the calling agent stays in charge. Handoffs suit routing; agents as tools suit a manager that combines sub-results.

### What happens when an agent runs too many turns?

The runner raises `MaxTurnsExceeded` once the run passes `max_turns`, which defaults to 10 in `Runner.run`. You can pass `max_turns=None` to remove the limit, but that removes a cost and safety control. A better pattern is to catch the exception and hand the case to a person.

### How do I keep a conversation going across runs?

Use a session, such as `SQLiteSession("user_123", "conversations.db")`, and pass it to each run. The SDK loads history before each run and saves new items after it. Alternatives are passing `result.to_input_list()` yourself or using `conversation_id` or `previous_response_id`, but not together with a session.

### Can I test an agent without paying for model calls?

Yes. Since version 0.21.0, `agents.testing.ScriptedModel` returns outputs you script in advance and records every call. Both examples in this article ran this way. Use it to check tool wiring, handoffs, guardrails and approvals in CI.

## Summary

The OpenAI Agents SDK reached 0.26.0 on 24 November 2026 with a set of safety fixes, including one that stops queued tools after an input guardrail trips. Its runner loop is simple: call the model, then finish, hand off or run tools, and repeat until a final answer or `max_turns`. Around that loop sit function tools, handoffs, three kinds of guardrails, sessions with many storage backends, tracing on by default and a `needs_approval` pause for human review. Because each turn re-sends the history, cost grows faster than the number of turns, so turn limits and blocking guardrails are real cost controls. The `ScriptedModel` test double lets you build and test all of this offline, as the two runnable examples here show.

## Sources

- [OpenAI: OpenAI Agents SDK documentation](https://openai.github.io/openai-agents-python/)
- [OpenAI: Running agents](https://openai.github.io/openai-agents-python/running_agents/)
- [OpenAI: Handoffs](https://openai.github.io/openai-agents-python/handoffs/)
- [OpenAI: Guardrails](https://openai.github.io/openai-agents-python/guardrails/)
- [OpenAI: Human-in-the-loop](https://openai.github.io/openai-agents-python/human_in_the_loop/)
- [OpenAI: Sessions](https://openai.github.io/openai-agents-python/sessions/)
- [OpenAI: Tracing](https://openai.github.io/openai-agents-python/tracing/)
- [GitHub: openai-agents-python release v0.26.0](https://github.com/openai/openai-agents-python/releases/tag/v0.26.0)
- [GitHub: openai-agents-python releases](https://github.com/openai/openai-agents-python/releases)
- [PyPI: openai-agents](https://pypi.org/project/openai-agents/)
