Sub topic 13
Tracing and Evaluating Multi-Agent Runs
This chapter assumes you have read the earlier chapters on handoffs, orchestrators, and turn limits. It also assumes you are comfortable with Python dataclasses and JSON. The Agent and run code from those chapters is the base here.
A multi-agent run is hard to debug from its final answer alone. If a refund request ends with "I can't help with that", the cause could be a wrong routing decision, a failed tool call, or a specialist that never received the order number. You need a record of what happened inside the run. You also need a repeatable way to judge whether a run was good.
What a trace contains
A trace is the complete record of one run. It is made of spans. A span is one timed unit of work with a start, a duration, a status, and a few attributes. Spans nest, so a span can have a parent. The nesting is what lets you read a multi-agent run as a story.
For multi-agent systems, record these span kinds:
| Span kind | When it starts | Attributes worth keeping |
|---|---|---|
| run | A request enters the system | Start agent, user request ID, final status |
| model | An agent calls the model | Agent name, turn number, reply type, token counts |
| tool | An agent calls a tool | Tool name, arguments, result size, error |
| handoff | Control moves to another agent | Source agent, target agent, payload size |
When an orchestrator calls a specialist as a tool, the specialist's whole run is nested inside the orchestrator's tool span. Cost and latency then roll up naturally. A slow orchestrator run shows which worker took the time.
Adding a tracer to the loop
The tracer below is small enough to read in one sitting. It keeps a stack of open spans, so each new span gets the right parent without you passing IDs around. The traced loop is the run function from earlier with spans added. The script is complete and runs as shown. A scripted call_model stands in for a real model.
import json
import time
import uuid
from contextlib import contextmanager
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)
class Tracer:
def __init__(self):
self.trace_id = uuid.uuid4().hex[:8]
self.spans = []
self._stack = []
@contextmanager
def span(self, kind, name, **data):
span = {
"id": uuid.uuid4().hex[:6],
"parent": self._stack[-1] if self._stack else None,
"kind": kind,
"name": name,
"status": "ok",
"data": dict(data),
}
start = time.perf_counter()
self._stack.append(span["id"])
try:
yield span
except Exception as exc:
span["status"] = "error"
span["data"]["error"] = repr(exc)
raise
finally:
span["ms"] = round((time.perf_counter() - start) * 1000, 2)
self._stack.pop()
self.spans.append(span)
def run_traced(start, messages, call_model, tracer, max_turns=10):
agent = start
with tracer.span("run", start.name):
for turn in range(max_turns):
with tracer.span("model", agent.name, turn=turn) as s:
reply = call_model(agent, messages)
s["data"]["reply_type"] = reply["type"]
if reply["type"] == "final":
return agent.name, reply["text"]
if reply["type"] == "handoff":
with tracer.span("handoff", reply["target"], source=agent.name):
agent = agent.handoffs[reply["target"]]
continue
with tracer.span("tool", reply["name"], args=reply["args"]) as s:
result = agent.tools[reply["name"]](**reply["args"])
s["data"]["result_chars"] = len(str(result))
messages.append(
{"role": "tool", "name": reply["name"], "content": str(result)}
)
raise RuntimeError("max_turns exceeded")
def scripted_model(agent, messages):
if agent.name == "triage":
return {"type": "handoff", "target": "billing"}
if not any(m["role"] == "tool" for m in messages):
return {"type": "tool", "name": "lookup_order", "args": {"order_id": 1042}}
return {"type": "final", "text": "Refund issued for order 1042."}
billing = Agent(
"billing",
"Handle refunds.",
tools={"lookup_order": lambda order_id: {"id": order_id, "total": 40}},
)
triage = Agent("triage", "Route requests.", handoffs={"billing": billing})
tracer = Tracer()
answer = run_traced(triage, [{"role": "user", "content": "Refund 1042"}],
scripted_model, tracer)
print(answer)
for s in tracer.spans:
print(json.dumps(s))Three details matter here.
- Spans are appended when they close, so children appear before their parent in
tracer.spans. Sort by start time, or follow theparentfield, when you display them. - The error handler records the exception and re-raises it. A trace must not hide a failure. If
max_turnsis exceeded, therunspan ends with statuserror, and you can see the last agents that were active. - The tracer records tool arguments. Do not record secrets or personal data in span attributes without redaction. Traces are often stored longer and read by more people than the conversation itself.
Following nested agents
If you build an orchestrator with as_tool, the worker's run should receive the same tracer. Then the worker's spans are opened while the orchestrator's tool span is on the stack, and they nest under it with no extra work. If the worker gets a new tracer, its spans land in a separate trace and you lose the link between the delegation and the work it caused.
Parallel fan-out breaks this simple design. A shared stack assumes one thread of control. If workers run in threads or async tasks, their spans interleave on the stack and get wrong parents. Fix this by storing the current span ID in a contextvars.ContextVar instead of a list. Each task then sees its own parent. You can also pass the parent ID explicitly when you start each worker.
What to look for in a trace
Read traces with specific questions in mind:
- Routing. Did the first handoff go to the right agent? Misrouting is the most common multi-agent failure, and it shows up as a handoff span with the wrong target.
- Loops. Do the same two agents hand off to each other repeatedly? Look for repeated
A to BandB to Apairs before a turn-limit error. - Wasted work. Did an orchestrator call a worker twice with nearly identical tasks? Compare tool span arguments.
- Lost context. Did a worker ask for information the orchestrator already had? Compare the task text in the tool span with the facts available earlier.
- Latency and cost. Which span has the largest duration or token count? Sum model spans per agent to see where spend goes.
Evaluating runs
Tracing tells you what happened. Evaluation tells you whether it was acceptable. Because a trace is structured data, you can write two kinds of checks.
Outcome checks judge the final answer. Examples are exact matches for facts, schema validation for structured output, and a model-based grader for free text. These work the same as in single-agent systems.
Trajectory checks judge the path. They are specific to multi-agent systems, because the same correct answer can come from a good path or a wasteful one. Typical rules:
- The sequence of handoff targets equals the expected route.
- Required tools were called, and forbidden tools were not.
- The number of model turns stays under a budget.
- No span has status
errorunless the case expects one.
def check_trajectory(tracer, expected_route, max_model_turns):
spans = tracer.spans
route = [s["name"] for s in spans if s["kind"] == "handoff"]
model_turns = sum(1 for s in spans if s["kind"] == "model")
errors = [s["name"] for s in spans if s["status"] == "error"]
problems = []
if route != expected_route:
problems.append(f"route {route} != {expected_route}")
if model_turns > max_model_turns:
problems.append(f"{model_turns} model turns > {max_model_turns}")
if errors:
problems.append(f"error spans: {errors}")
return problems
print(check_trajectory(tracer, ["billing"], max_model_turns=4)) # prints []Run a set of fixed test cases through the system and record the pass rate for both kinds of check. Include cases where the right behavior is to refuse, escalate, or hand off to a human, because routing bugs often hide there.
Common mistakes
- Logging only the final answer. You then cannot tell which agent caused a bad result.
- Evaluating only outcomes. A run that guesses the right answer after five wasted handoffs looks identical to a clean run, until cost grows.
- Giving each worker its own trace. Delegation links are lost.
- Storing full prompts and tool results everywhere. Traces become large and may leak sensitive data. Store sizes and hashes by default, and keep full content for sampled or failing runs.
- Treating a grader model as ground truth. Spot-check its verdicts against human judgments.
Exercise
A run ends with the error "max_turns exceeded". Your trace shows handoff spans in the order triage to billing, billing to triage, triage to billing, billing to triage. Which trace feature identifies the problem, and which two checks would catch it in future test runs?
Show answer
The repeated pair of handoff spans between the same two agents shows a routing loop. The run span has status error with the max_turns message. A trajectory check that compares the handoff route to the expected route (here a single handoff to billing) would fail, and a model-turn budget check would also fail. Fixing it means clarifying the instructions of the two agents so one of them owns the request, and, if needed, passing a payload that says why the request came back.
Exercise
You change as_tool so that each worker creates its own Tracer. What do you lose, and how do you restore it?
Show answer
You lose the parent-child link between the orchestrator's tool span and the worker's spans, so the worker's cost and latency do not roll up and the traces cannot be joined. Restore it by passing the orchestrator's tracer into the worker's run_traced call, or by passing the parent span ID and trace ID to the worker's tracer.