To evaluate a multi-agent system, test the handoffs as well as the final answer. Check three things for every transfer: control went to the right agent, the receiving agent got the context it needs and nothing it shouldn't, and the run didn't bounce between agents. Do it in two layers. Deterministic tests with a scripted model check the plumbing on every commit. A labeled eval with the real model measures how often the router picks the right specialist, and an end-state check confirms the task actually got done.
This post shows both layers with the OpenAI Agents SDK, where a handoff is a tool call that moves control to another agent. The code was run with openai-agents 0.25.0 on Python 3.13, using the SDK's own test double, so the tests need no API key.
Why handoffs need their own tests
A single agent fails in ways you can see in one transcript. A multi-agent system adds failures that live between agents. The MAST study, "Why Do Multi-Agent LLM Systems Fail?", annotated more than 1,600 traces from seven multi-agent frameworks, including ChatDev, MetaGPT and Magentic-One. It sorts failures into 14 modes in three categories: system design issues, inter-agent misalignment and task verification. The authors report inter-annotator agreement of kappa 0.88 on the labels.
Several of the inter-agent modes are handoff problems you can write tests for:
- Information withholding: an agent has information another one needs and doesn't pass it on.
- Ignored other agent's input: the receiving agent disregards what it was given.
- Conversation reset: the dialogue restarts and progress is lost.
- Task derailment: an agent drifts away from the task it was handed.
- Fail to ask for clarification: an agent proceeds on unclear input instead of asking.
Anthropic's post on its multi-agent research system describes the same pattern from the builder's side. Without detailed task descriptions, its subagents would "duplicate work, leave gaps, or fail to find necessary information." It also notes that multi-agent systems used about 15 times more tokens than chats in its data, so a handoff that sends work to the wrong agent costs more than a wrong turn in a single agent.
How a handoff looks to the model
In the OpenAI Agents SDK, handoffs are "represented as tools to the LLM." An agent named Refund agent becomes a tool called transfer_to_refund_agent. When the model calls it, the runner switches the current agent and runs the loop again. The handoff() function adds the pieces you will want to test:
input_type: a schema for arguments the model fills in during the handoff, such as an order ID and a reason.on_handoff: a callback that runs when the handoff is invoked. The docs say to raise if a check fails, because "the SDK continues the transfer afteron_handoffreturns successfully."input_filter: a function that changes the history the next agent sees. By default the receiving agent sees the whole previous conversation.
Here is a small system with a triage agent and two specialists. The refund handoff carries an order ID, refuses bad ones and strips tool calls from the history the refund agent sees. Each agent takes its model as a parameter so tests can swap in a scripted one.
"""A triage agent that hands refunds and billing questions to specialists."""
from pydantic import BaseModel
from agents import Agent, RunContextWrapper, handoff
from agents.extensions import handoff_filters
from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX
class RefundHandoff(BaseModel):
order_id: str
reason: str
async def check_refund_handoff(ctx: RunContextWrapper, data: RefundHandoff) -> None:
# Raising here stops the transfer, so bad context never reaches the specialist.
if not data.order_id.startswith("A-"):
raise ValueError(f"order_id {data.order_id!r} is not a valid order number")
def build_agents(triage_model, refund_model, billing_model):
refund = Agent(
name="Refund agent",
instructions=f"{RECOMMENDED_PROMPT_PREFIX} Process refunds for one order.",
model=refund_model,
)
billing = Agent(
name="Billing agent",
instructions=f"{RECOMMENDED_PROMPT_PREFIX} Answer invoice and payment questions.",
model=billing_model,
)
triage = Agent(
name="Triage agent",
instructions=f"{RECOMMENDED_PROMPT_PREFIX} Route the customer to one specialist.",
model=triage_model,
handoffs=[
handoff(refund, input_type=RefundHandoff, on_handoff=check_refund_handoff,
input_filter=handoff_filters.remove_all_tools),
billing,
],
)
return triage, refund, billing
Layer 1: deterministic tests with a scripted model
The SDK ships test doubles in agents.testing. ScriptedModel takes one list of output items per expected model call and returns them in order. function_call() scripts a tool call, and a handoff is a tool call, so it scripts handoffs too. assistant_message() scripts a final answer. The model records every call it receives, so you can assert on what each agent was offered and what it saw. assert_complete() fails if any scripted step went unused, and an extra model request raises UnexpectedModelCall.
These tests don't measure the model. They pin down everything around it: the handoff tools exist, the guard works, the filter works and control lands where it should.
To record where control went, use a RunHooks subclass. The docs say RunHooks "observe the entire Runner.run(...) invocation, including handoffs to other agents," and on_handoff fires "when control moves from one agent to another."
"""Record every handoff in a run, for tests and live evals alike."""
from agents import RunHooks
class HandoffRecorder(RunHooks):
def __init__(self) -> None:
self.path: list[str] = []
async def on_handoff(self, context, from_agent, to_agent) -> None:
if not self.path:
self.path.append(from_agent.name)
self.path.append(to_agent.name)
Use the hook rather than reading the run's items. The SDK records handoffs in result.new_items as HandoffCallItem and HandoffOutputItem, but in our run with remove_all_tools on the handoff, those items were missing from new_items and only the refund agent's message remained. The filter removes handoff items along with tool calls, and that affected the run result too. The hook saw the handoff either way.
import json
import pytest
from agents import RunConfig, Runner
from agents.testing import ScriptedModel, assistant_message, function_call
from handoff_path import HandoffRecorder
from support_agents import build_agents
NO_TRACE = RunConfig(tracing_disabled=True)
@pytest.mark.asyncio
async def test_refund_request_reaches_refund_agent_with_context():
triage_model = ScriptedModel([[function_call(
"transfer_to_refund_agent",
{"order_id": "A-1001", "reason": "arrived broken"}, call_id="h1")]])
refund_model = ScriptedModel([[assistant_message("Refund started for A-1001.")]])
billing_model = ScriptedModel([])
triage, refund, _ = build_agents(triage_model, refund_model, billing_model)
recorder = HandoffRecorder()
result = await Runner.run(triage, "My order A-1001 arrived broken",
hooks=recorder, run_config=NO_TRACE)
# Control moved once, to the right agent.
assert recorder.path == ["Triage agent", "Refund agent"]
assert result.last_agent is refund
# The triage model was offered both handoffs as tools.
offered = {h.tool_name for h in triage_model.first_call.handoffs}
assert offered == {"transfer_to_refund_agent", "transfer_to_billing_agent"}
# The specialist saw the customer's words, and the filter removed tool items.
seen = refund_model.first_call.input
assert "A-1001 arrived broken" in json.dumps(seen, default=str)
assert not [i for i in seen if isinstance(i, dict) and i.get("type") == "function_call"]
for model in (triage_model, refund_model, billing_model):
model.assert_complete()
@pytest.mark.asyncio
async def test_bad_order_id_blocks_the_handoff():
triage_model = ScriptedModel([[function_call(
"transfer_to_refund_agent",
{"order_id": "12345", "reason": "broken"}, call_id="h1")]])
refund_model = ScriptedModel([])
triage, _, _ = build_agents(triage_model, refund_model, ScriptedModel([]))
with pytest.raises(ValueError, match="not a valid order number"):
await Runner.run(triage, "Refund order 12345", run_config=NO_TRACE)
assert refund_model.calls == () # the specialist never ran
Both tests pass:
.. [100%]
2 passed in 1.62s
What each assertion catches:
- The path: a renamed agent, a missing handoff or a specialist that hands back to triage.
- Offered handoffs: a handoff disabled by mistake, or a new one that changes the router's choices.
- What the specialist saw: context lost in transfer, the code version of information withholding. The filter check confirms the refund agent got the customer's words without the triage agent's tool traffic. The SDK docs add a caveat:
remove_all_tools"does not redact tool arguments or results already copied into ordinary messages." - The blocked handoff: the guard in
on_handoffstops bad context at the boundary, and the specialist's model is never called.
Layer 2: score routing with the real model
Scripted tests can't tell you whether the model picks the right specialist. For that, build a labeled set of inputs with the agent each one should end up with, run the real system, and score the path. Start small. Anthropic's post recommends starting "with small-scale testing right away with a few examples" rather than waiting for a large suite, and the agent evals starter guide suggests 20 to 50 tasks drawn from real failures.
"""Score handoff routing over labeled cases: right specialist, in one hop."""
from collections import Counter
from agents import MaxTurnsExceeded, RunConfig, Runner
from handoff_path import HandoffRecorder
CASES = [
{"input": "My order A-1001 arrived broken, I want my money back", "route": "Refund agent"},
{"input": "Why was I charged twice on my last invoice?", "route": "Billing agent"},
{"input": "Cancel order A-2002 and refund it", "route": "Refund agent"},
{"input": "Can I pay by bank transfer instead of card?", "route": "Billing agent"},
]
async def score_routing(make_triage, cases, max_turns: int = 6) -> dict:
results, confusion = [], Counter()
for case in cases:
recorder = HandoffRecorder()
try:
await Runner.run(make_triage(), case["input"], hooks=recorder,
max_turns=max_turns, run_config=RunConfig(tracing_disabled=True))
error = None
except MaxTurnsExceeded as exc:
error = f"max turns: {exc}"
path = recorder.path
landed = path[-1] if path else "(no handoff)"
confusion[(case["route"], landed)] += 1
results.append({
"input": case["input"], "expected": case["route"], "path": path,
"routed_ok": landed == case["route"],
"one_hop": len(path) == 2, # triage -> specialist, no bouncing
"error": error,
})
n = len(results)
return {
"routing_accuracy": sum(r["routed_ok"] for r in results) / n,
"one_hop_rate": sum(r["one_hop"] for r in results) / n,
"confusion": dict(confusion),
"failures": [r for r in results if not (r["routed_ok"] and r["one_hop"])],
}
With a real model, pass make_triage=lambda: build_agents(None, None, None)[0]. An agent with no model set uses the SDK's default model, and the call needs an API key. To check the scorer itself, we ran it with scripted models where one billing question was sent to refunds:
{'routing_accuracy': 0.75, 'one_hop_rate': 1.0, 'confusion': {('Refund agent', 'Refund agent'): 2, ('Billing agent', 'Refund agent'): 1, ('Billing agent', 'Billing agent'): 1}, 'failures': [{'input': 'Why was I charged twice on my last invoice?', 'expected': 'Billing agent', 'path': ['Triage agent', 'Refund agent'], 'routed_ok': False, 'one_hop': True, 'error': None}]}
Three metrics come out of it:
- Routing accuracy: the share of cases where the last agent in control is the expected one. The confusion counts show which pairs get mixed up, which tells you which
handoff_descriptionor instruction to sharpen. Routing is tool selection, so the fixes in why your agent calls the wrong tool apply. - One-hop rate: the share of runs that went from triage to one specialist. Agents handing work back and forth is a loop with extra steps. The runner raises
MaxTurnsExceededwhen a run passesmax_turns, which defaults to 10 in the SDK source, and the scorer records that as an error. See debugging agents that never stop for the general case. - Failures: every case that routed wrong or bounced, with its path, so you can read them.
Run each case several times. Routing is a model decision, and one run can be lucky. The starter guide covers pass^k for measuring that.
Grade the end state, not the route
Routing right is necessary but not enough. Anthropic's advice for multi-agent evaluation is to judge results over process: "evaluate whether it achieved the correct final state." For the support system above, that means checking that a refund exists for order A-1001 in your test database, not that the refund agent said it started one. Add an end-state grader to each case, as in the starter guide's harness, and treat routing metrics as diagnostics that explain failures.
Don't rely on one check at the end, either. The MAST authors found that many verifier agents only ran superficial checks, such as whether code compiles, and concluded that multi-level verification is needed. In their ChatDev case study, adding a high-level task objective verification step improved results on their ProgramDev set by 15.6%. A handoff test, a routing eval and an end-state grader are three levels of that.
Use traces for the rest
Tests cover the cases you thought of. Traces cover the rest. The Agents SDK wraps each handoff in a handoff_span() by default, next to spans for agents, model calls and tool calls. Sample production traces, look for runs with more than one handoff or a handoff right before an error, and turn the bad ones into new eval cases. Agent observability tracing covers what to record on each step.
Checklist
- Give every agent its model as a parameter so tests can inject
ScriptedModel. - Assert the handoff path with a
RunHooks.on_handoffrecorder, not by parsing items. - Assert which handoffs each agent was offered.
- Assert what the receiving agent saw, after any
input_filter. - Validate handoff arguments in
on_handoffand raise to block bad transfers. - Keep a labeled routing set built from real misroutes.
- Track routing accuracy, one-hop rate and the confusion pairs.
- Set
max_turnsand countMaxTurnsExceededas a failure. - Grade the end state, and use routing metrics to explain failures.
FAQ
How do you evaluate a multi-agent system?
Test at several levels: deterministic tests for handoff plumbing, a labeled eval that scores which agent ends up in control, and an end-state check on the task. Read failing traces to find new cases.
How do I test agent handoffs without calling the API?
Use the Agents SDK's ScriptedModel from agents.testing. Script the handoff as a function call to transfer_to_<agent_name>, run the agents normally, and assert on the recorded calls and the handoff path.
What are the most common multi-agent failures?
The MAST taxonomy lists 14 failure modes in three categories: system design issues, inter-agent misalignment and task verification. Inter-agent modes include information withholding, ignoring another agent's input and task derailment.
How do I stop agents from handing work back and forth?
Measure it first with a one-hop rate in your eval. Set max_turns so a bouncing run fails fast, and make each agent's scope and handoff description specific enough that only one agent fits each request.
Sources
- Cemri et al., Why Do Multi-Agent LLM Systems Fail? (arXiv 2503.13657, MAST taxonomy)
- Anthropic, How we built our multi-agent research system (June 2025)
- OpenAI Agents SDK, Handoffs (documentation)
- OpenAI Agents SDK, Testing (documentation)
- OpenAI Agents SDK, Agents: lifecycle hooks (documentation)
- OpenAI Agents SDK, Results (documentation)
- OpenAI Agents SDK, Running agents (documentation)
- OpenAI Agents SDK, Tracing (documentation)
- OpenAI, openai-agents-python (source,
run_config.pyfor the defaultmax_turns)