Sub topic 6
The handoff pattern
This chapter covers how one agent transfers control of a conversation to another agent. It assumes you can read Python, know what a message list and a JSON tool call are, and have seen the basic agent loop (model, instructions, tools, repeat). Agents as tools and the orchestrator pattern come in other chapters, so they appear here only as contrast.
What a handoff is
A handoff is a transfer of control. The active agent decides that another agent should handle the rest of the conversation, and the loop switches to that agent. The first agent does not wait for a result and does not come back unless some later handoff sends control back to it.
A handoff looks like a tool call to the model. The model emits a structured request such as "transfer to billing". The runtime does not run a normal function. It changes which agent is active. This keeps handoffs simple to implement. You need no new model capability beyond tool calling.
Three properties define the pattern:
- Control moves. Exactly one agent is active at a time, and the new agent talks to the user directly.
- History usually continues. In the basic form, the same message list carries over, so the new agent sees what was said earlier.
- No return value. Nothing flows back to the previous agent. This is the main difference from calling an agent as a tool.
A minimal implementation
The loop below handles three reply types from the model: a final answer, a tool call, and a handoff. A handoff changes the agent variable and continues. The max_turns limit stops runaway loops.
from dataclasses import dataclass, field
from typing import Callable
@dataclass
class Agent:
name: str
instructions: str
tools: dict[str, Callable] = field(default_factory=dict)
handoffs: dict[str, "Agent"] = field(default_factory=dict)
def run(start: Agent, messages: list, call_model, max_turns: int = 10):
"""call_model(agent, messages) returns one of:
{"type": "final", "text": str}
{"type": "tool", "name": str, "args": dict}
{"type": "handoff", "target": str}
"""
agent = start
for _ in range(max_turns):
reply = call_model(agent, messages)
if reply["type"] == "final":
return agent.name, reply["text"]
if reply["type"] == "handoff":
agent = agent.handoffs[reply["target"]]
continue
result = agent.tools[reply["name"]](**reply["args"])
messages.append({"role": "tool", "name": reply["name"], "content": str(result)})
raise RuntimeError("max_turns exceeded")Notice what the handoff branch does and does not do. It looks up the target in agent.handoffs, so an agent can only transfer to agents it was explicitly given. It adds nothing to messages. The next call to call_model passes the same list with a different agent, so the model receives the new agent's instructions and tools plus the old history.
How the model sees a handoff
In a real system, call_model builds a request that lists each handoff as a tool. Typical names are transfer_to_billing or transfer_to_refunds. The description of each tool tells the model when to use it. When the model calls one, call_model translates that into the {"type": "handoff", "target": ...} shape above.
Because the model chooses handoffs based on tool descriptions, those descriptions matter as much as the agent's instructions. A vague description such as "for other questions" leads to wrong transfers. A clear one states the condition: "Use when the customer asks about charges, invoices, or payment methods."
Control flow
The diagram shows a customer request moving from a front-desk agent to a specialist.
What the new agent sees
The history that carries over is a design choice, and the simple loop above makes the most permissive choice: everything is shared. That has costs.
| Choice | What the next agent gets | Benefit | Risk |
|---|---|---|---|
| Full history | Every earlier message and tool result | No lost detail, trivial to build | Long context, higher cost, leaked data from earlier steps |
| Filtered history | Only selected messages, such as user turns | Smaller and safer | May drop a fact the next agent needs |
| Structured payload | A short summary of goal, facts, and limits | Compact and explicit | Someone must write the summary correctly |
The payload approach works well when the previous agent has done a lot of work that the next agent does not need to re-read. The example below sends a compact summary as a single message.
from dataclasses import dataclass, asdict
import json
@dataclass
class HandoffPayload:
goal: str
facts: list[str]
open_questions: list[str]
constraints: list[str]
payload = HandoffPayload(
goal="Issue a refund for order 1042",
facts=["Customer reports a damaged item", "Order was delivered on time"],
open_questions=["Does the refund exceed the auto-approval limit?"],
constraints=["Do not promise a replacement"],
)
message = {"role": "user", "content": json.dumps(asdict(payload))}The constraints field is easy to forget and important. If the first agent promised or ruled out something, the next agent must know, because it will otherwise answer as if the conversation just started. Later chapters cover context passing in more depth.
Common errors
Ping-pong loops. Agent A hands off to B because the request looks like B's job. B hands back to A for the same reason. Each handoff consumes a turn, so max_turns eventually raises an error, but the user sees nothing useful until then. Reduce the risk by giving each agent a narrow, non-overlapping scope, and by letting specialists hand off only to a small set of targets.
Wrong instructions after the switch. If your code keeps a system message at the start of the history, the new agent may see the old agent's system message as well as its own. Rebuild the system message from agent.instructions on each call, as shown below, rather than storing it in messages.
def build_request(agent: Agent, messages: list) -> list:
system = {"role": "system", "content": agent.instructions}
return [system] + messagesUnknown targets. In the loop above, agent.handoffs[reply["target"]] raises KeyError if the model names a target that does not exist. Treat that as a model error. Either catch it and append an error message so the model can retry, or fail the run with a clear message.
Tool results from the old agent. Messages with role set to tool may refer to tools the new agent does not have. Some model APIs reject a history that mentions a tool missing from the current tool list. If you see such errors, filter tool messages or convert them to plain text when you switch.
Handoff with no explanation. The user sees a sudden change of voice. Have the outgoing agent say a short line, such as "I'll pass you to billing", before the transfer, or have the incoming agent acknowledge the context in its first reply.
When handoffs fit
Handoffs suit conversations where the right expert changes as the topic changes, and where that expert should speak to the user directly. Customer support is the classic case: a triage agent identifies the issue and passes the user to billing, technical support, or returns.
They fit poorly when you need to combine several specialists' outputs into one answer. After a handoff, the first agent is gone, so no one remains in charge of merging. That case calls for an orchestrator. Choosing between the two, and mixing them, is covered in a later chapter.
Exercise
In the run function, a handoff does not append anything to messages. What does the new agent see on its first turn, and what problem can occur if the old agent's system message is stored inside messages?
Show answer
The new agent sees the full existing message history, combined with its own instructions and tools, because call_model receives the new agent and the same messages list. If the old agent's system message is stored inside messages, the new agent also sees those old instructions, which can conflict with its own. The fix is to build the system message from agent.instructions on each call and keep it out of the stored history.
Exercise
Two agents, A and B, each have a handoff to the other. A request is ambiguous and the agents keep passing it back and forth. Name two measures that limit the damage or prevent it.
Show answer
The max_turns limit stops the loop with an error after a fixed number of turns. Narrowing each agent's scope and removing unneeded handoff targets reduces the chance that the loop starts. Tracking the handoff count per agent pair and failing on a repeat is another valid guard.