Sub topic 16
Reading traces to debug agents
This chapter assumes you can already produce traces for an agent: an invoke_agent span as the root, with chat and execute_tool child spans, and token usage recorded as attributes. The goal here is to read those traces to find out why a run was slow, wrong, or expensive.
The working model: read the tree, then the clock, then the attributes
A trace shows three things at once, and each answers a different question.
- Shape: the parent-child tree shows what the agent did and in what order.
- Timing: the start and end of each span show where time went.
- Attributes and status: these show what each step was given, what it returned, and whether it failed.
Read them in that order. The shape tells you whether the agent behaved sensibly. The timing tells you which steps to look at. The attributes explain those steps.
Read the shape first
Open the trace in your backend's waterfall view. Before you look at any numbers, count the children of the agent span.
- A healthy run usually has a short alternation:
chat, thenexecute_tool, thenchat, ending with a finalchatthat produces the answer. - A runaway loop shows the same tool name many times in a row, often with a
chatspan between each one. The agent keeps asking for the same thing and does not accept the result. - A missing step shows a
chatspan that should have been followed by a tool call but was not. The model answered from its own guess instead of calling the tool. - A flat tree where every span is a direct child of the root can mean context was lost. For example, a tool ran in a thread pool or a background task and did not inherit the parent context. The spans exist, but they are not nested where you expect.
Read the clock: self time, not total time
A parent span's duration includes its children, so the root is always the longest span. That tells you nothing. What you want is self time: a span's duration minus the time spent in its children. Self time on a chat span is mostly model latency. Self time on the agent span is your own glue code, such as parsing, serialization, or waiting on a lock.
Also check whether children overlap. Sequential children add up to the parent's duration. If your agent can run tools in parallel, the waterfall shows overlapping bars, and the parent's duration is closer to the longest child than to the sum.
You can compute this yourself from exported spans. The script below uses a small hand-written list of spans that shape-match a looping agent. It prints self time per span, counts tool calls by name, and totals tokens.
from collections import Counter, defaultdict
spans = [
{"id": "a", "parent": None, "name": "invoke_agent support-agent", "start": 0.0, "end": 8.2, "status": "OK", "attrs": {}},
{"id": "b", "parent": "a", "name": "chat example-model", "start": 0.0, "end": 1.5, "status": "OK",
"attrs": {"gen_ai.usage.input_tokens": 800, "gen_ai.usage.output_tokens": 40}},
{"id": "c", "parent": "a", "name": "execute_tool search_orders", "start": 1.5, "end": 2.0, "status": "ERROR", "attrs": {}},
{"id": "d", "parent": "a", "name": "chat example-model", "start": 2.0, "end": 3.6, "status": "OK",
"attrs": {"gen_ai.usage.input_tokens": 950, "gen_ai.usage.output_tokens": 40}},
{"id": "e", "parent": "a", "name": "execute_tool search_orders", "start": 3.6, "end": 4.1, "status": "ERROR", "attrs": {}},
{"id": "f", "parent": "a", "name": "chat example-model", "start": 4.1, "end": 5.8, "status": "OK",
"attrs": {"gen_ai.usage.input_tokens": 1100, "gen_ai.usage.output_tokens": 45}},
{"id": "g", "parent": "a", "name": "execute_tool search_orders", "start": 5.8, "end": 6.3, "status": "ERROR", "attrs": {}},
{"id": "h", "parent": "a", "name": "chat example-model", "start": 6.3, "end": 8.0, "status": "OK",
"attrs": {"gen_ai.usage.input_tokens": 1250, "gen_ai.usage.output_tokens": 50}},
]
children = defaultdict(list)
for s in spans:
children[s["parent"]].append(s)
def duration(span):
return span["end"] - span["start"]
def self_time(span):
# Assumes children run one after another, not in parallel.
return duration(span) - sum(duration(c) for c in children[span["id"]])
print("Self time per span (largest first):")
for s in sorted(spans, key=self_time, reverse=True):
print(f" {self_time(s):5.2f}s {s['status']:5} {s['name']}")
tool_counts = Counter(s["name"] for s in spans if s["name"].startswith("execute_tool"))
print("\nTool calls by name:")
for name, count in tool_counts.items():
flag = " <-- possible loop" if count >= 3 else ""
print(f" {count}x {name}{flag}")
tokens_in = sum(s["attrs"].get("gen_ai.usage.input_tokens", 0) for s in spans)
tokens_out = sum(s["attrs"].get("gen_ai.usage.output_tokens", 0) for s in spans)
print(f"\nTotal tokens: {tokens_in} in, {tokens_out} out")Two patterns in this data are worth noticing. First, the input token count grows on every chat span. That is normal for an agent that appends tool results to the conversation, but it means each loop iteration costs more than the one before. Second, search_orders fails three times with the same name. The model never changed its approach, so the loop will continue until something stops it.
Read the attributes and events
Once the timing points you at a span, open its details.
- Status and exception events: a span with
ERRORstatus should carry an exception event fromrecord_exception. Read the exception type first. A timeout, a validation error, and a rate limit each lead to a different fix. - Request attributes: compare
gen_ai.request.modeland any parameter attributes you record, such as temperature or max tokens. A slowchatspan on a larger model than you intended is a configuration bug, not a performance bug. - Finish reasons: a
chatspan that ended because of a length limit explains truncated tool-call JSON, which in turn explains the tool failure on the next span. - Token counts: compare input tokens across sibling
chatspans. A sudden jump means a large tool result or retrieved document was added to the context.
Common errors when reading traces
- Blaming the root span. It is always the slowest. Use self time or look at the longest child.
- Trusting a clean trace too much. A trace with no errors only means no exception was raised. A tool that returns an empty list, or a model that gives a confident wrong answer, produces
OKspans. If you do not record result sizes or a quality signal, these failures are invisible. - Treating missing spans as missing work. A short or empty trace can mean sampling dropped part of it, or that spans from another process never joined the trace because context propagation was broken.
- Comparing runs of different inputs. A run with a long document is slower for good reasons. Compare token counts alongside durations before calling something a regression.
- Ignoring retries. If your client library retries internally and you do not record that, one
chatspan can hide several attempts. The span looks slow, but the cause is a rate limit.
A debugging routine
- Open the failing or slow trace and note the number of
chatandexecute_toolspans. - Look for repeated tool names and
ERRORstatus. - Compute or visually estimate self time to find the dominant span.
- Open that span and read its exception event, finish reason, and token counts.
- Form a hypothesis, change one thing, and compare the new trace against the old one.
Exercise
An agent trace has 14 spans under the root. Nine are execute_tool lookup_account spans, all with OK status, and the input token count on the chat spans rises from 600 to 5,000. The root takes 40 seconds. What is the most likely problem, and which attributes would you check to confirm it?
Show answer
The agent is probably looping on a tool that succeeds but returns a result the model does not accept as an answer, such as an empty or irrelevant result. Each result is appended to the context, which explains the rising input tokens. Check the tool span's result-size attribute (if you record one) and the chat spans' finish reasons and output. Then check the stop condition in the agent loop, because the loop has no effective maximum number of iterations.
Exercise
Why is self time more useful than total duration when finding the slow step in an agent trace, and when does the "subtract the children" calculation give a wrong answer?
Show answer
Total duration of a parent includes all its children, so the root always looks slowest and points at nothing specific. Self time isolates the time spent in the span's own work. The calculation is wrong when children run in parallel, because their durations overlap and the sum of children can exceed the parent's duration, giving a negative or misleading self time. In that case, use the union of the child intervals instead of their sum.