Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 20 min · revision 3

Reading a Failed Trace

Diagnose a failed agent run from its trace, with or without an error span: separate the symptom from the first wrong step, and classify the failure as tool selection, arguments, missing context, reasoning or environment.

Contentsand lesson path

What you will learn

  • Diagnose a failed run from its trace and classify the failure (tool selection, arguments, missing context, reasoning or environment).

01. Symptoms, Causes and Five Kinds of Failure

When an agent fails, what the user sees is usually a symptom: a timeout, a "turn budget exhausted" error or a confident but wrong answer. The step that caused it often happened several turns earlier. An agent might pass a bad argument on turn 2, misread the error on turn 3 and repeat a useless check until its turn limit stops it on turn 8. Reading only turn 8 tells you about the turn limit, not about the bad argument.

A trace keeps the whole causal chain: every model call and tool call, in order, with its inputs, outputs and status. Diagnosis means finding the first step where the run went wrong and naming what kind of mistake it was, because each kind has a different fix.

Start from the earliest error span when there is one. But many failed runs have no error span at all. The model can pick the wrong tool, and that tool runs successfully. A correct tool can return stale data. A fact can be missing from the prompt, or the final answer can be wrong although every step succeeded. In those runs every span is green, and you find the failure only by reading the run turn by turn.

At the first turn where the trajectory went wrong, ask which of five things happened. Each comes with a typical trace signal and a typical fix:

  • Tool selection: the model chose the wrong tool, or no tool when it needed one. Signal: the tool name does not fit the step, even though the tool span succeeded. Fix: clearer tool names and descriptions, fewer overlapping tools.
  • Arguments: the right tool, called with bad arguments, such as a wrong type, a wrong ID or an invented value. Signal: the arguments on the model span do not match the schema or the facts already in context, often followed by a validation error. Fix: a stricter schema, examples, validation that returns an actionable message.
  • Missing context: the model never saw the information it needed, because it was not retrieved, was truncated, or was dropped when the history was compacted. Signal: the input of the model call lacks the fact. Fix: retrieval, truncation, pagination or memory, not the prompt wording.
  • Reasoning: the model had correct observations but drew a wrong conclusion, misread a result or lost the goal. Signal: a correct tool result followed by an action or answer that does not follow from it. Fix: clearer instructions, a verification step, a smaller task per call or a stronger model.
  • Environment: something outside the model failed, such as a timeout, a rate limit, a 503 or a missing permission. Signal: an error span with an error.type such as timeout or an HTTP status. Fix: retries with backoff, quotas, alerts and fallbacks.

Label the first wrong step as the primary category. Later mistakes that follow from it are secondary, and an exhausted turn or token budget is a symptom, not a category. Reading arguments and inputs needs content in the trace, so teams usually enable redacted content capture in development and staging, as in the previous lab.

02. Worked Example: Two Failed Runs, With and Without an Error Span

Two runs failed their evaluation, the check that compares each answer with the expected outcome. The first is a billing agent asked to sync the billing record of a customer, [email protected], to the ERP (enterprise resource planning) system. The second is an account agent asked by a user to cancel their subscription. Both traces were exported with redacted content and simplified into the fixture below: one row per span, with a short summary of what the span recorded. Save it and the script after it in a folder trace-triage.

Python · trace-triage/runs.py
"""Two failed runs, simplified from exported spans (content captured, redacted)."""


def span(turn, start, name, status="UNSET", detail="", error_type=None):
    return {"turn": turn, "start": start, "name": name, "status": status,
            "detail": detail, "error.type": error_type}


ERP = {"id": "erp-sync-0412", "passed": False, "spans": [
    span(0, 0, "invoke_agent BillingAgent", "ERROR", "turn budget exhausted"),
    span(1, 1, "chat gpt-6-luna", detail="calls search_customer"),
    span(1, 2, "execute_tool search_customer", detail='-> user_id "usr_8819"'),
    span(2, 3, "chat gpt-6-luna", detail='calls sync_erp_billing(discount="null")'),
    span(2, 4, "execute_tool sync_erp_billing", "ERROR",
         "discount must be a number or omitted", "ValidationError"),
    span(3, 5, "chat gpt-6-luna", detail="calls check_erp_health"),
    span(3, 6, "execute_tool check_erp_health", detail='-> "HEALTHY"'),
    span(4, 7, "chat gpt-6-luna", detail="calls check_erp_health again (to turn 8)"),
]}

CANCEL = {"id": "cancel-0907", "passed": False, "spans": [
    span(0, 0, "invoke_agent AccountAgent", detail="answer: cancelled"),
    span(1, 1, "chat gpt-6-luna", detail="calls pause_subscription"),
    span(1, 2, "execute_tool pause_subscription", detail='-> status "paused"'),
    span(2, 3, "chat gpt-6-luna", detail='answers "Your subscription is cancelled."'),
]}

The triage script checks the outcome first, because a run can fail with no error at all. It then looks for the earliest error span in the steps. The root span is skipped: its status is the symptom. When there is no error span, first_error_span returns None, and the script says so instead of pretending to have found a cause. In both cases it prints the run turn by turn for you to read.

Python · trace-triage/triage.py
"""Start at the earliest error span if there is one; many failed runs have none."""
from runs import CANCEL, ERP


def first_error_span(spans):
    """The earliest step span with status ERROR, or None when no step failed.
    The root span (turn 0) is skipped: its status is the symptom, not the cause."""
    errors = [s for s in spans if s["status"] == "ERROR" and s["turn"] > 0]
    return min(errors, key=lambda s: s["start"]) if errors else None


def triage(run):
    print(f"run {run['id']}: passed={run['passed']}")
    if run["passed"]:
        return
    first = first_error_span(run["spans"])
    if first is None:
        print("  no error span: find the first turn where the run went wrong")
    else:
        print(f"  earliest error: turn {first['turn']}, {first['name']} "
              f"({first['error.type']})")
        print("  start there, and check the turns before it too")
    for s in sorted(run["spans"], key=lambda s: s["start"]):
        print(f"  t{s['turn']} {s['name']:<31} {s['status']:<5} {s['detail']}")


for run in (ERP, CANCEL):
    triage(run)
Terminal (Python 3.12 or later, standard library only)
cd trace-triage && python3 triage.py
Expected output
run erp-sync-0412: passed=False
  earliest error: turn 2, execute_tool sync_erp_billing (ValidationError)
  start there, and check the turns before it too
  t0 invoke_agent BillingAgent       ERROR turn budget exhausted
  t1 chat gpt-6-luna                 UNSET calls search_customer
  t1 execute_tool search_customer    UNSET -> user_id "usr_8819"
  t2 chat gpt-6-luna                 UNSET calls sync_erp_billing(discount="null")
  t2 execute_tool sync_erp_billing   ERROR discount must be a number or omitted
  t3 chat gpt-6-luna                 UNSET calls check_erp_health
  t3 execute_tool check_erp_health   UNSET -> "HEALTHY"
  t4 chat gpt-6-luna                 UNSET calls check_erp_health again (to turn 8)
run cancel-0907: passed=False
  no error span: find the first turn where the run went wrong
  t0 invoke_agent AccountAgent       UNSET answer: cancelled
  t1 chat gpt-6-luna                 UNSET calls pause_subscription
  t1 execute_tool pause_subscription UNSET -> status "paused"
  t2 chat gpt-6-luna                 UNSET answers "Your subscription is cancelled."

Run 1, the ERP sync. The root span says "turn budget exhausted", but that is the symptom. The earliest error is the ValidationError on turn 2, and the turn before it is clean: the customer lookup returned the right ID. On turn 2 the model chose the right tool but sent the string "null" for discount, so the primary category is arguments. The cause sits in the tool definition: discount was optional, but its JSON Schema did not say how to express "no discount", so the model improvised. Turn 3 adds a secondary reasoning failure: the error said the argument was wrong, yet the model concluded the ERP server might be down. It checked the server's health, got HEALTHY, and kept checking until the turn limit stopped the run.

Run 2, the cancellation. Every span is UNSET, so the script finds nothing to start from, and you read the turns. Turn 1 is already wrong: the user asked to cancel, and the model called pause_subscription, which succeeded. The agent also had a cancel_subscription tool, and the two descriptions overlapped. The primary category is tool selection. Turn 2 adds a secondary reasoning failure: the result said "paused", yet the answer said "cancelled". Fixing only the answer wording would hide the real problem, which is two tools the model cannot tell apart.

03. Turning the Diagnosis into Fixes

The category tells you where to fix. For the ERP run, an arguments failure, the fixes are in the tool layer:

  1. Tool definition: declare optional numbers as {"type": ["number", "null"]}, or say in the description: "Omit discount if no discount applies; never pass the string null."
  2. Input normalisation: convert the string "null" or an empty string to None in the tool wrapper before calling the ERP client.
  3. Error feedback: keep returning a message the model can act on, such as {"error": "discount must be a number or omitted"}, instead of a bare stack trace. This run already got that message and still checked the server on turn 3, so a better message would not have saved it: that is the secondary reasoning failure. For it, add a rule to the instructions, for example "a ValidationError means your arguments were wrong: correct them and call the tool again", and check on this run that the model now retries with a valid discount.

For the cancellation run, a tool selection failure, the fix is in the tool set: rewrite both descriptions so they say when to use each tool, or merge them into one tool with an action argument. Then add both runs to your evaluation set and rerun it after every change.

04. Practice questions

Practice check · 3 questions

Reading failed traces check

Three scenario questions on where to start, runs without an error span, and choosing a category.

Q1. A trace ends with "turn budget exhausted" on turn 10, and an argument validation error appears on turn 3. Turns 1 and 2 look correct. Where should the diagnosis start?
Q2. Your evaluation marks a run as failed, but every span in its trace has an unset status and no exception events. What is the sound next step?
Q3. A support agent calls `get_balance`, which returns `{"balance": -40.0, "currency": "GBP"}`. The agent then tells the customer their account is £40 in credit. Which category is the primary failure?
Practice only: not graded, not saved, not evidence.

05. Apply it

Take three failed runs of your own agent, including at least one with no error span:

  • Sort the spans by start time and note whether the run has an error span.
  • Find the first turn where the run went wrong and write one sentence on what happened there.
  • Give that turn a primary category from the five, and note any secondary ones.
  • Write the fix the category points to, and add the failing input to your evaluation set.

You will need these labels for the failure taxonomy in the next lab.

06. Review prompt

Without looking back, name the five failure categories and, for each, one trace signal and one fix. Then explain why the last error in a trace is often not the cause, and describe how you would diagnose a failed run in which no span has an error status.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check