The first agent failure I could not explain took most of a day to diagnose. The final answer was wrong, the logs showed three tool calls, and none of the individual steps looked obviously broken. Only when I printed the entire message history—every user turn, every assistant block, every tool result—did the mistake become obvious: on the second iteration the model had received a tool result for a different tool than the one it had requested, because I had reused a tool_use_id from an earlier turn. The agent was not “confused.” It was working with corrupted observation data.
That is the moment I stopped debugging agents by reading the final answer and started debugging them by reading the full trace. This post walks through exactly that process. We will take a deliberately broken agent, capture a complete trace, locate the failure stage, and apply a minimal fix. The same method works for the agents we built earlier in this series and for larger systems that sit on top of them.
As always:
Build the smallest useful version, then test what breaks.
What You Will Have Working by the End
A clear definition of what belongs in an agent trace
A concrete failing example you can reproduce
A step-by-step inspection of the decide → call → observe → respond loop
A minimal fix that makes the failure disappear
A short checklist you can reuse on the next failure
What a Useful Trace Contains
A trace is the complete record of one agent run. At minimum it should include:
The original user message
Every model request (messages sent, tools offered, model name)
Every model response (content blocks, stop reason, token usage)
Every tool call (name, arguments, tool_use_id)
Every tool result (tool_use_id, content, success or error)
The final answer or the reason the loop stopped
Timestamps or iteration numbers so you can see order
If any of those pieces is missing, you will eventually guess instead of observe. Guessing is how a one-hour bug becomes a one-day bug.
A Deliberately Broken Agent
We will reuse the minimal tool-using agent from earlier posts and introduce a single, realistic bug: the code that builds the tool-result message accidentally drops the tool_use_id under a certain condition. The model then receives an observation it cannot match to its request and produces a wrong or incomplete final answer.
Python
import json
import os
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
TOOLS = [
{
"name": "add_numbers",
"description": "Add two integers and return their sum.",
"input_schema": {
"type": "object",
"properties": {
"a": {"type": "integer"},
"b": {"type": "integer"}
},
"required": ["a", "b"]
}
}
]
def add_numbers(a: int, b: int) -> str:
return str(a + b)
TOOL_MAP = {"add_numbers": add_numbers}
def run_broken_agent(user_message: str, max_iterations: int = 4):
"""Intentionally imperfect agent that records a full trace."""
messages = [{"role": "user", "content": user_message}]
trace = []
for iteration in range(1, max_iterations + 1):
step = {"iteration": iteration, "messages_in": len(messages)}
response = client.messages.create(
model="claude-sonnet-5", # verify current ID in official docs
max_tokens=256,
tools=TOOLS,
messages=messages
)
step["stop_reason"] = response.stop_reason
step["usage"] = {
"input": response.usage.input_tokens,
"output": response.usage.output_tokens
}
step["assistant_content"] = [
block.model_dump() if hasattr(block, "model_dump") else str(block)
for block in response.content
]
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
final = "".join(
b.text for b in response.content if getattr(b, "type", None) == "text"
)
step["final_answer"] = final
trace.append(step)
return final, trace
tool_results = []
for block in response.content:
if getattr(block, "type", None) != "tool_use":
continue
name = block.name
args = block.input
tool_use_id = block.id
step.setdefault("tool_calls", []).append(
{"name": name, "args": args, "id": tool_use_id}
)
try:
result = TOOL_MAP[name](**args)
except Exception as e:
result = f"Error: {e}"
# ----- THE BUG -----
# Under a contrived condition we drop the tool_use_id.
# This simulates a real class of observation errors.
if iteration == 1:
tool_results.append({
"type": "tool_result",
# "tool_use_id": tool_use_id, # <-- missing on purpose
"content": result
})
else:
tool_results.append({
"type": "tool_result",
"tool_use_id": tool_use_id,
"content": result
})
# -------------------
step.setdefault("tool_results", []).append(
{"id": tool_use_id if iteration > 1 else None, "content": result}
)
messages.append({"role": "user", "content": tool_results})
trace.append(step)
return "Stopped: max iterations", traceWhen you run this agent on a simple addition request you will often see a second tool call, a confused final answer, or an API error. The exact symptom can vary; the trace will still show the root cause.
Capturing and Printing the Trace

Python
def print_trace(trace: list[dict]):
for step in trace:
print(f"\n===== Iteration {step['iteration']} =====")
print(f"Stop reason : {step.get('stop_reason')}")
print(f"Usage : {step.get('usage')}")
if "tool_calls" in step:
print("Tool calls :")
for call in step["tool_calls"]:
print(f" - {call['name']}({call['args']}) id={call['id']}")
if "tool_results" in step:
print("Tool results:")
for res in step["tool_results"]:
print(f" - id={res['id']} content={res['content']}")
if "final_answer" in step:
print(f"Final answer: {step['final_answer']}")Always print the trace before you change any code. The printed record is the only source of truth for what the model actually saw.
Walkthrough: Locating the Failure

Run the broken agent:
Python
if __name__ == "__main__":
answer, trace = run_broken_agent("What is 19 + 23? Use the add_numbers tool.")
print("\n=== Returned Answer ===")
print(answer)
print_trace(trace)A typical trace looks something like this (abbreviated):
text
===== Iteration 1 =====
Stop reason : tool_use
Tool calls :
- add_numbers({'a': 19, 'b': 23}) id=toolu_01ABC...
Tool results:
- id=None content=42
===== Iteration 2 =====
Stop reason : tool_use # or end_turn with a wrong answer
...Four observations jump out:
Decide (iteration 1) – The model correctly requested add_numbers with the right arguments.
Call – The tool executed and returned 42.
Observe – The tool result was appended without a tool_use_id.
Decide (iteration 2) – The model no longer has a clean association between its request and the result, so it either calls the tool again or produces an answer that ignores the observation.
The failure is not in the model’s reasoning ability. The failure is in the observation stage of the loop. Once the trace makes that visible, the fix is obvious.
The Minimal Fix
Restore the tool_use_id in every tool result:
Python
tool_results.append({
"type": "tool_result",
"tool_use_id": tool_use_id, # always present
"content": result
})Re-run the same user message. The trace should now show a single tool call, a matching tool result with the correct ID, and a final answer that uses the value 42. The quality, latency, and cost numbers from the previous post will also improve because the extra iteration disappears.
A Reusable Debugging Checklist
When an agent produces a wrong answer or appears to loop, walk through these questions in order:
Did the model decide correctly on the first turn?
Inspect the first assistant content blocks and the stop reason. If the wrong tool was chosen, the problem is in the tool descriptions or the system prompt, not in the loop.Were the tool arguments correct?
If the arguments are wrong, the problem is still in the decide stage (prompt, schema, or missing context).Did the tool itself return the right value?
Log the raw tool output. If the tool is wrong, fix the tool; the agent loop is innocent.Was the tool result correctly observed?
Check that every tool_result carries the matching tool_use_id and that the content is exactly what the tool returned. This is the stage that hid the bug in our example.Did later iterations still contain the earlier observations?
If the messages list is truncated or older tool results are dropped, the model is deciding with incomplete history.Did a guard (max iterations, duplicate detection, allow-list) fire?
If a guard stopped the run, the trace should show which guard and why. That is a successful safety stop, not a model failure.
Most agent bugs fall into one of these six places. The trace tells you which one.
Three Failure Patterns the Trace Makes Obvious
1. Observation Mismatch
Tool result IDs do not match tool call IDs, or the result content is malformed. Symptom: repeated identical tool calls or answers that ignore known tool output. Fix: make the observation stage a pure, tested function that always emits correct tool_result blocks.
2. Silent History Loss
Earlier turns are missing from the messages list on later iterations. Symptom: the model “forgets” constraints or previously retrieved facts. Fix: log len(messages) on every iteration and assert that the list only grows (unless you have an explicit compaction step).
3. Guard Misconfiguration
A duplicate-action or max-iteration guard fires on a legitimate multi-step plan. Symptom: the agent stops with a safety message even though the task is unfinished. Fix: inspect the trace for the exact guard that fired, then adjust the limit or the canonicalization logic with the concrete example in hand.
Practical Habits That Keep Traces Useful
Emit one structured trace object per run; do not scatter print statements that you later have to reassemble.
Include the tool_use_id in every log line that mentions a tool call or result.
Store the trace even for successful runs while you are still developing; successful traces are the baseline that makes failures obvious.
When you fix a bug, keep the failing trace and the input that produced it as a regression test.
What This Walkthrough Does Not Cover
It does not:
Show distributed tracing across multiple services
Integrate with OpenTelemetry or a commercial observability product
Automatically highlight the failing stage
Handle multi-agent hand-offs
Those topics belong to later production and observability posts. The goal today is a complete, readable trace of a single agent run and a repeatable method for finding the broken stage.
Verification Checklist
Run the broken agent and confirm the printed trace shows a missing tool_use_id on the first tool result.
Apply the one-line fix and confirm the new trace contains a matching ID and a correct final answer.
Manually drop an earlier message from the history and confirm the checklist’s “history loss” question would catch it.
Force a duplicate tool call and confirm the trace records both the call and the guard response (if you have the duplicate guard from earlier posts).
Save one failing trace and one successful trace side by side; confirm you can explain the difference in under a minute.
If all five steps pass, you have a working trace-based debugging method.
Update Note
The Messages API shapes for tool use (tool_use, tool_result, stop reasons) remain stable. Model identifiers change; always verify the current recommended ID in the official Anthropic documentation. The value of a complete, ordered trace does not depend on those surface details.
Looking Ahead
We have now completed the four Testing and Evaluation posts: a first evaluation dataset, structural testing of structured outputs, combined measurement of latency/cost/quality, and a full trace-based debugging walkthrough. The next set of posts moves into Deployment and Consultant Notes—secrets, observability, cost estimation, and production readiness checklists that sit on top of the workflows and tests we have already built.
Keep the tracing habit. When a larger agent later fails in production, you will already know how to reduce the problem to a single decide-call-observe-respond cycle you can inspect by hand.
Build the smallest useful version, then test what breaks.
— Caleb Fletcher
Boise, Idaho

No feedback yet — submit the first.