Sub topic 15
Reading a Trace to Find Out Why an Agent Went Wrong
This chapter assumes you know the pieces covered earlier in the tutorial. You should know that model calls are stateless, that messages carry roles, that the harness runs tools and appends their results, and that the context window is finite. You should also be comfortable reading JSON and short Python.
What a trace is
A trace is the full ordered list of messages the harness sent to and received from the model during one task. It holds the user request, each assistant reply, each tool call with its arguments, and each tool result. In the loop from earlier chapters, the trace is the messages list.
The trace is the best evidence for debugging because the model has no other memory. Everything it knew at a given step is in the messages sent at that step. If the trace shows the model never saw a fact, the model could not have used it. If the fact is there and the model ignored it, you have a different problem.
Keep three things in your logs for every run:
- The system prompt and tool definitions exactly as sent, because they change between versions of the harness.
- Every message in order, with the step number.
- The raw tool output before truncation, stored separately, so you can see what the model did not see.
Read in a fixed order
Reading a long trace from top to bottom is slow. Use this order instead.
- Read the user request and the system prompt. Check that the task is stated clearly and that the instructions do not conflict with it.
- Read the last ten messages. This shows how the run ended: a final answer, a step limit, or an error.
- Find the first tool result that was an error or was surprising. Work backward from the end to the first deviation, not the last one. Later mistakes are often consequences of an early one.
- At that point, read the call that produced the result. Check the tool name, the arguments, and whether the call was reasonable given what the model had seen.
- Read the result as the model saw it. Look for truncation, missing paths, or error text that gives no hint about what to do next.
Common failure patterns
Most agent failures fall into a small number of patterns. Each has a signature in the trace.
| Pattern | Signature in the trace | Usual cause |
|---|---|---|
| Loop on one call | The same tool call with the same arguments appears three or more times | The error result gave no new information, so the model tried again |
| Wrong tool arguments | Errors such as "no such file" or schema validation failures | Vague tool description, or the model guessed a path instead of searching |
| Lost information | The model asks again for something it already read | The context was compacted or truncated and the detail was dropped |
| Ignored instruction | A rule from the system prompt is broken late in the run | The instruction is far back in a long context, or conflicts with the task |
| Premature stop | A final answer with no test run after an edit | No stop condition requires verification, or the model hit the step limit |
| Obeying tool content | The model takes an action that appears only inside a file or web page | Untrusted text was treated as an instruction |
| Context blowout | One tool result is thousands of characters, and quality drops after it | An unbounded read or command output filled the window |
A worked example
The task is "Fix the failing test in the date parser." The run below ends with the step limit. This is the trace, abbreviated as a Python list so we can analyze it.
trace = [
{"role": "user", "content": "Fix the failing test in the date parser."},
{"role": "assistant", "content": "", "tool_calls": [
{"id": "c1", "name": "run_command", "arguments": {"command": "pytest -q"}}]},
{"role": "tool", "tool_call_id": "c1",
"content": "FAILED tests/test_parse.py::test_dates - ValueError: bad date"},
{"role": "assistant", "content": "", "tool_calls": [
{"id": "c2", "name": "read_file", "arguments": {"path": "parse.py"}}]},
{"role": "tool", "tool_call_id": "c2",
"content": "error: [Errno 2] No such file or directory: 'parse.py'"},
{"role": "assistant", "content": "", "tool_calls": [
{"id": "c3", "name": "read_file", "arguments": {"path": "parse.py"}}]},
{"role": "tool", "tool_call_id": "c3",
"content": "error: [Errno 2] No such file or directory: 'parse.py'"},
{"role": "assistant", "content": "", "tool_calls": [
{"id": "c4", "name": "read_file", "arguments": {"path": "parse.py"}}]},
{"role": "tool", "tool_call_id": "c4",
"content": "error: [Errno 2] No such file or directory: 'parse.py'"},
]Applying the reading order: the request is clear. The first surprise is message 4, where read_file fails. The call in message 3 used the path parse.py, but the pytest output named only tests/test_parse.py. The model guessed that the source file sat in the workspace root. It never searched for it.
The model then repeated the same call twice more. The error text was identical each time, so the model received no new information. The loop was not a model "bug" in the abstract. The harness gave the model a dead end and no hint.
The fix has several layers, and you should pick the cheapest one that works:
- Tool result: when a path is missing, return a list of similar paths. This helps every future run.
- Tool description: tell the model to use a search tool to locate files before reading them.
- Harness: detect repeated identical calls and inject a message such as "this call failed twice with the same arguments; try a different approach."
Automating the first pass
You can find the signatures from the table with a short script. This one flags repeated calls, tool errors, and oversized results. It works on the message format used by the loop in this tutorial.
import json
from collections import Counter
def summarize(messages, big=5000):
seen = Counter()
findings = []
for i, m in enumerate(messages):
for c in m.get("tool_calls") or []:
key = (c["name"], json.dumps(c["arguments"], sort_keys=True))
seen[key] += 1
if seen[key] == 3:
findings.append(
f"message {i}: {c['name']} called 3 times with identical arguments")
if m["role"] == "tool":
text = str(m["content"])
if text.startswith("error:"):
findings.append(f"message {i}: tool error: {text[:80]}")
if len(text) >= big:
findings.append(f"message {i}: large result ({len(text)} chars)")
return findings
# Using the trace defined above:
for line in summarize(trace):
print(line)Run against the example trace, it prints:
message 4: tool error: error: [Errno 2] No such file or directory: 'parse.py'
message 6: tool error: error: [Errno 2] No such file or directory: 'parse.py'
message 7: read_file called 3 times with identical arguments
message 8: tool error: error: [Errno 2] No such file or directory: 'parse.py'The script finds symptoms, not causes. It tells you where to look. You still read messages 3 and 4 to decide why the call was made.
A decision path
When a run fails, ask a sequence of questions. Each one narrows the problem to a layer of the system.
Edge cases and cautions
- Runs are not deterministic. The same task can succeed on one run and fail on the next. A single failing trace shows one path. Before you change the harness, run the task several times and compare traces to see whether the failure is common.
- Truncation hides the cause. If your logs store only the truncated tool result, you will see what the model saw but not what happened. Store the raw output separately, as noted earlier.
- The final answer can be wrong while the trace looks clean. An agent may report success after a test run that was actually skipped or that printed a warning. Read the actual test output, not the model's description of it.
- The model's stated reasoning is not a log of its internals. Explanations in assistant text are useful clues, but they can be wrong or invented after the fact. Trust the tool calls and results over the narrative.
- Traces can contain secrets. Tool results may include environment variables, tokens, or private code. Redact them before sharing a trace in a bug report.
Summary of the method
Start from the end of the trace and work back to the first deviation. Check whether the model had the information, whether the tool told it what to do next, and whether the call was reasonable. Then fix the layer where the evidence points: context management, tool output, tool description, system prompt, or the harness's stop conditions. Verify the fix by replaying the task.
Exercise
A trace shows the agent reading config.py at step 4, and at step 31 it asks to read config.py again and then makes an edit that contradicts what the file contained. The context window is large and the harness summarizes history when it passes 80% of the window. Name the most likely cause, say what in the trace you would check to confirm it, and give one fix.
Show answer
The most likely cause is that compaction replaced the early file contents with a summary that dropped the relevant detail, so the model re-read the file and the edit was based on incomplete information, or the re-read result was itself truncated. Confirm it by looking at the messages sent at step 31: check whether the summary message mentions the key setting from config.py, and whether the second read result was cut off at the tool's length limit (compare it with the stored raw output). One fix is to make the summary keep specific facts that later steps depend on, such as exact values and file paths. Another is to raise the read tool's length limit or return the file in ranges so the needed part is not cut.
Exercise
Your summarize script reports "run_command called 3 times with identical arguments" but no tool errors. What does that suggest, and what would you look at next?
Show answer
The command is succeeding, so the loop is not caused by an error message. Likely causes are output that does not change as the model expects (for example, a test that still fails the same way because the model's edit was not applied or was applied to the wrong file) or output that gives the model no sign of progress. Look at the edit calls between the repeats to see whether they changed the right file, then read the command output to see whether it changed at all. A harness-level fix is to flag repeated identical calls and tell the model to try a different approach.