Sub topic 2
The Handoff Pattern
Assume you know basic Python, JSON, message-based LLM APIs, and tool calling. A handoff transfers control from one agent to another during the same task. The new agent continues from the shared conversation history, but its instructions and available tools change.
The handoff pattern
A handoff is useful when the next agent should own the conversation. For example, a triage agent can transfer a billing question to a billing agent. The handoff is represented as a special tool call rather than an ordinary function result.
from dataclasses import dataclass, field
@dataclass
class Agent:
name: str
instructions: str
handoffs: dict[str, "Agent"] = field(default_factory=dict)
def run(start, messages, call_model, max_turns=10):
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
raise ValueError(f"Unexpected reply: {reply['type']}")
billing = Agent("billing", "Resolve billing questions.")
support = Agent("support", "Handle general support and route billing issues.")
support.handoffs["billing"] = billing
def fake_model(agent, messages):
if agent.name == "support":
return {"type": "handoff", "target": "billing"}
return {"type": "final", "text": "Billing support resolved the request."}
print(run(support, [{"role": "user", "content": "I need a refund"}], fake_model))The loop keeps the same messages list while replacing agent. A turn limit prevents agents from handing work back and forth forever.
What to pass between agents
Pass the smallest context that lets the receiving agent act correctly:
- The goal and relevant user request
- Facts confirmed by tools or trusted systems
- Open questions and decisions still required
- Constraints, such as approval limits
- A correlation ID for tracing
A structured payload is safer than an informal summary because required fields can be validated.
Triage and routing agents
A triage agent classifies a request and hands it to a specialist. Keep its output constrained to known routes, such as billing, technical, or human_review. Validate the route before changing agents. If classification is uncertain, ask a clarifying question or escalate rather than guessing.
Choosing handoffs, orchestrators, or both
Use a handoff when one specialist should take ownership of the conversation. Use an orchestrator when a manager must call several specialists, compare their outputs, and produce one result. A hybrid can use triage for initial routing, then an orchestrator inside a specialist workflow.
Exercise
A request needs independent legal and technical analyses before one final answer. Which pattern fits best?
Show answer
Use an orchestrator. It can call both specialists, merge their outputs, and retain control of the final response.