Skip to content
AgenticAIWiki
  1. Learn
  2. Part 13
  3. 67. Observability and tracing
  4. 67.5

Lesson 67.5 · 5 of 9 · 4 min read · Reviewed 24 Nov 2026

Debugging an agent from its trace

By the end, you can

  • Debug an agent failure from its trace.
  • Recognise common failure patterns in traces.

Debugging an agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. means reading its traceTrace: A record of everything that happened during one request or agent run, as a tree of timed steps. like a story and finding the first point where it went off course.

Walk the trace

For each model span, ask three questions:

  1. What did it see? The full context: system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation., history, tool results.
  2. What did it decide? Its text and tool calls.
  3. Was that reasonable given what it saw? If yes, the problem is upstream (bad input or tool result). If no, the problem is the prompt, tool description or model choice.

Patterns to recognise

What you see in the trace Likely cause Fix
Same tool, same arguments, many times Tool result unclear or error hidden Return clear errors and next steps
Wrong tool chosen Overlapping or vague tool descriptions Sharpen descriptions, merge tools
A wrong fact repeated confidently Bad tool result trusted Validate results, show source
Good start, confused end Key fact trimmed from context Pin case facts (chapter 63)
Very long run, then a timeout No step limit or stop condition Add limits and a done check
Subagent output ignored Handoff too long or unstructured Ask for a short structured summary

Fix at the right step

Changing the final reply prompt won’t help if step 3 got a wrong tool result. Fix the first bad step, then rerun the same input and compare traces. Add the input to your evalEval: A repeatable test that measures how well an AI system performs on a set of cases with defined success criteria. set so it stays fixed.

Key points

  • Start from the failing trace and walk it step by step: what did the model see, decide and receive?
  • Common patterns: a wrong tool choice, a bad tool result taken as truth, a loop, context lost after trimming.
  • Fix at the step that went wrong, then add the case to your evals.
Hands-on labRuns in the Playground

Find the first bad step in a trace

Debug an agent failure by checking each step against what it saw.

You will have: A trace walker that reports the first unreasonable step and why.

Steps

  1. Run the starter: every step looks reasonable.
  2. Add a check that tool arguments match what the user wrote.
  3. Add checks for tool results and for replies that contradict tool output.
  4. Run again and read which step is flagged first.
  5. Write one sentence on how you would fix that step and which eval case you would add.

Done when

  • The output names step 2 as the first bad step.
  • Steps 3 and 4 are reported as reasonable given their input.
  • The reason mentions order 1102 versus 1120.

Open in the Playground No API key needed.

Starter code (Python)
# Walk a trace and find the first step that went off course.
USER_MESSAGE = "Has my order 1120 shipped yet?"
TRACE = [
    {"step": 1, "kind": "model", "decided": {"say": "I will look up the order."}},
    {"step": 2, "kind": "model", "decided": {"tool": "lookup_order", "order_id": "1102"}},
    {"step": 3, "kind": "tool", "args": {"order_id": "1102"}, "result": {"order_id": "1102", "status": "shipped"}},
    {"step": 4, "kind": "model", "decided": {"say": "Good news: your order has shipped."}},
]


def check(step, context):
    """Return a problem string if this step's decision was unreasonable given what it saw, else None."""
    d = step.get("decided", {})
    # TODO 1: a model step that calls lookup_order must use an order id the user actually wrote
    # TODO 2: a tool step must return the same order id it was asked for
    # TODO 3: a reply must agree with the last tool status (context["status"])
    return None


context = {"user": USER_MESSAGE}
first = None
for step in TRACE:
    problem = check(step, context)
    print(f"step {step['step']} ({step['kind']}): {problem or 'reasonable given its input'}")
    if problem and first is None:
        first = (step, problem)
    if step["kind"] == "tool":
        context["status"] = step["result"]["status"]

if first:
    print(f"first bad step: {first[0]['step']} ({first[0]['kind']}): {first[1]}")
else:
    print("no bad step found")
Show a solution
# Walk a trace and find the first step that went off course.
USER_MESSAGE = "Has my order 1120 shipped yet?"
TRACE = [
    {"step": 1, "kind": "model", "decided": {"say": "I will look up the order."}},
    {"step": 2, "kind": "model", "decided": {"tool": "lookup_order", "order_id": "1102"}},
    {"step": 3, "kind": "tool", "args": {"order_id": "1102"}, "result": {"order_id": "1102", "status": "shipped"}},
    {"step": 4, "kind": "model", "decided": {"say": "Good news: your order has shipped."}},
]


def check(step, context):
    """Return a problem string if this step's decision was unreasonable given what it saw, else None."""
    d = step.get("decided", {})
    if step["kind"] == "model" and d.get("tool") == "lookup_order":
        if d["order_id"] not in context["user"]:
            return f"asked for order {d['order_id']} but the user wrote {USER_MESSAGE!r}"
    if step["kind"] == "tool" and step["result"]["order_id"] != step["args"]["order_id"]:
        return "tool returned a different order than it was asked for"
    if step["kind"] == "model" and "say" in d and context.get("status"):
        if context["status"] not in d["say"]:
            return "reply contradicts the last tool result"
    return None


context = {"user": USER_MESSAGE}
first = None
for step in TRACE:
    problem = check(step, context)
    print(f"step {step['step']} ({step['kind']}): {problem or 'reasonable given its input'}")
    if problem and first is None:
        first = (step, problem)
    if step["kind"] == "tool":
        context["status"] = step["result"]["status"]

if first:
    print(f"first bad step: {first[0]['step']} ({first[0]['kind']}): {first[1]}")
else:
    print("no bad step found")
Quick checkA trace shows the agent calling search_orders eight times with the same arguments. What is the likely problem?
How sure are you?
Pick an answer and how sure you are