Tracing an Agent Failure
Engineering

Tracing an Agent Failure

When an agent gets something wrong, the mistake is rarely in the last message. A worked trace review shows how to find the first wrong step, fix it in the right layer and keep it fixed.

Short answer

To diagnose an AI agent failure, read its trace from the beginning rather than starting from the final answer. Record every model call, tool call, retrieval step and side effect under one trace ID, then find the first step where the input, tool choice, arguments or interpretation went wrong. Fix that step in the right layer, redact sensitive content, and turn the case into a regression test.

Why can't you diagnose an agent failure from the final answer?

Because the final answer is only the last link in a chain of many steps, and the point where the agent first went wrong is usually much earlier. A wrong summary may come from a stale search result, a swapped account number or a tool response the model misread. Trying to fix the final answer treats the symptom and leaves the cause in place.

Diagnosis needs a trace. Anthropic's article on agent evaluations defines a transcript as the complete record of a trial, including outputs, tool calls, reasoning, intermediate results and any other interactions, and stresses that you will not know whether your graders work unless you read the transcripts and grades from many trials. Investigating a production failure needs the same record: what the user asked, which step the agent took and why, what each tool returned and what actually changed in the world.

What should an agent trace contain?

Give every user request a trace ID, and record each model call, tool call, retrieval step and approval wait as a separate child span under it. If the agent touches several services, carry the trace ID across them. The W3C Trace Context recommendation defines standard HTTP headers for this: the traceparent header carries a version, a 16-byte trace ID, an 8-byte parent ID and a sampling flag. That way the tool server's own logs appear inside the same trace.

For attribute names, OpenTelemetry's generative AI attributes are a good starting point: they define values for gen_ai.operation.name such as invoke_agent, execute_tool, chat and retrieval, along with tool name and tool call ID, conversation ID and token usage. These definitions are still in development and have moved to a separate repository, so pin the version you use. Choose a stable subset your team will actually read rather than every field:

SpanWhat to recordWhy it helps diagnosis
Agent invocationUser and tenant ID, task, prompt and tool-definition version, model versionShows which configuration the failure happened under
Model callTool chosen, argument shape, finish reason, token countShows where the plan and the tool choice changed
Tool callTool name, call ID, response code, result status, retry count, durationSeparates a tool failure from a misreading
RetrievalReturned document IDs and versions, filter appliedExposes stale or wrong evidence
Side effectID of the order, ticket or refund createdLinks the trace to the record that changed in the real world

The last row is the one most often skipped. The agent saying "refund started" and a record actually appearing in the refund system are separate events; if the trace lacks the ID that links them, diagnosis turns into guesswork.

How do you read a trace and find the first divergence?

Read the trace from the start, not from the end, and mark the first wrong step. The review steps below can be applied in the same order to every incident:

  1. Write the user's authorised task and the expected outcome in one sentence.
  2. Find the last step at which the state was still correct.
  3. From there, ask four questions at every step: Was the input right? Was the tool choice right? Were the arguments right? Was the result interpreted correctly?
  4. Mark the step with the first "no" as the first divergence; most later errors follow from it.
  5. Compare with a successful trace of the same task type and note where the two paths split.
  6. Watch for clock differences: if service clocks are not in sync, order steps by their parent-span relationships rather than by timestamp.

Do not automatically blame the last model call. The model that wrote the final answer has often summarised, quite faithfully, wrong information it was given.

Is the fault in the model, the tool or the data?

Once you have found the first divergence, place it in the right layer; that classification decides where the fix goes. A prompt change can hide an API defect for a while, but it does not remove it.

SymptomLikely layerWhere to fix
The right tool was called with the right arguments, but it returned stale dataIntegration or data freshnessSource system, cache, sync
The agent requested an action it is not authorised forModel behaviour and the authorisation ruleBoth: the tool check and the task definition
The tool ran twice after a timeoutRetry logicIdempotency key, retry policy
The wrong one of two similar tools was chosenTool definitionsTool name, description, argument schema
The tool returned an error and the agent took it as successResult interpretationResponse schema, an explicit status field
Retrieval returned the wrong or an outdated documentRetrievalIndex, filter, document version
The agent repeated the same step in a loopStop ruleStep and cost limits

Hypothetical example: the agent that said "your refund is complete"

A customer asks the support agent to cancel order 4471 and start a refund. The agent replies "Your refund is complete"; two days later the customer reports that the money never arrived. The trace looks like this:

StepSpanObservationAssessment
1Agent invocationTask: cancel 4471, start the refundCorrect
2read_order(4471)Delivered, amount knownCorrect
3cancel_order(4471)Succeeded, cancellation record createdCorrect
4start_refund(4471)HTTP 202, status "queued", refund ID R-311The tool worked correctly
5Model callReported the "queued" result as "complete"First divergence
6Outside the traceR-311 failed two hours laterNo link to the trace

The first divergence is the interpretation at step five, but step six reveals a second gap: because the refund job did not carry the trace context, its failure could not be linked back to the conversation. The fix lands in three places: the tool response gets a status field that plainly means "queued, not yet complete", the trace context is passed to the refund job, and the reply to the customer is tied to a "refund request received, reference R-311" pattern. The incident also becomes a regression case.

Which traces should be reviewed, and how long should they be kept?

You cannot read every trace, so define signals that mark the ones worth reading. A good starting list: tasks where the user corrected the answer or complained, actions whose human approval was rejected, calls where a tool returned an error or was retried more than once, runs whose step count or cost exceeds the normal range for that task type, and cases where the agent could not do the job and handed it to a person. When one of these signals fires, the trace should land in the review queue on its own.

Use two tiers for retention. The structural trace, meaning spans, IDs, status codes and durations, can be kept for as long as incident review needs; full content should be kept only for flagged traces and only for a short time. The sampling flag in Trace Context carries the decision about whether a trace is recorded across services, so one service does not drop a trace that another is recording. Always keep traces of failed and handed-over tasks, regardless of the sampling rate. That may mean deciding on sampling after the task has finished, but these are exactly the traces you will need most.

How do you protect sensitive data in traces?

A trace must not cause a bigger incident than the one you are investigating. Prompts and tool outputs can contain personal data, secrets and customer documents. The OpenTelemetry definitions themselves flag tool call arguments and results as possibly containing sensitive information, and input messages as likely to contain personal data. OWASP's logging cheat sheet says session IDs, access tokens, passwords, connection strings, encryption keys, payment card data and sensitive personal data should usually not be logged directly, and should instead be removed, masked, sanitised, hashed or encrypted.

By default, log identifiers, hashes and redacted excerpts. Sample full content selectively and put access to it behind an audited review process. Apply the retention and deletion rules you use for source data to traces as well. Test redaction against realistic formats; ID numbers and email addresses embedded in model-generated text are the examples that slip through most often.

How do you turn an incident into a regression test?

Every diagnosed failure should become the smallest case that will run again on the next release. Anthropic's article likewise recommends going through the bug tracker and support queue and converting user-reported failures into test cases. The case should contain the authorised task, the recorded tool responses (replayable with mock tools), the allowed actions and the forbidden behaviour.

Choose the grader to fit the behaviour. According to the same article, code-based graders are fast, cheap and reproducible but brittle to valid variations, while model-based graders are flexible but need calibrating against human graders. In the example above, the rule "never say complete while the status is queued" is checked in code; the tone of the reply can be judged by a model or a person. The article also notes that it is often better to grade what the agent produced than the exact path it took. Because agents can behave differently from run to run, run the case several times; for work that must be right every time, a single passing attempt is not enough. We cover how to build the evaluation set in our article on building an agent evaluation dataset.

Common mistakes

  • Logging only the final answer and none of the intermediate steps.
  • Not carrying the trace ID into tool services and background jobs.
  • Leaving side-effect IDs (order, refund, ticket) out of the trace.
  • Covering an API defect with a prompt change.
  • Keeping full prompts and tool outputs unredacted and indefinitely.
  • Closing a diagnosed failure without turning it into a regression test.

Logging every step of the agent, the tool it called, its input and its result is the audit-trail layer described on our AI agent development service page.

Key takeaways

  • Give every request one trace ID, record model calls, tool calls, retrieval and approvals as child spans, and carry the ID across services.
  • Add side-effect IDs such as order or refund numbers so the trace links to what actually changed.
  • Read the trace from the start and mark the first step where input, tool choice, arguments or interpretation went wrong.
  • Classify the divergence as model, tool, data, retry or stop-rule before fixing it; do not hide API defects with prompt changes.
  • Log identifiers and redacted excerpts by default, and apply retention and deletion rules to traces.
  • Turn each diagnosed failure into a replayable regression case and run it several times.

Frequently asked questions

What is an agent trace?

It is the complete record of one agent run: the user's request, every model call, tool call, retrieval step and approval, their results and the side effects they caused, all linked by one trace ID. Anthropic calls the evaluation equivalent a transcript and treats reading it as a core skill.

Should agent traces follow OpenTelemetry?

OpenTelemetry's generative AI conventions are a useful shared vocabulary for operations such as invoke_agent and execute_tool, tool call IDs and token usage. They are still in development and now live in a separate repository, so pin the version you adopt and log only the fields your team will read.

How do I tell whether the model or the tool caused the failure?

Check the first wrong step. If the right tool was called with the right arguments and returned bad data, the fault is in the integration or data. If the tool returned a correct result that the agent misread, the fix belongs in the response schema or the agent's instructions.

Is it safe to log full prompts and tool outputs?

Not by default. They can contain personal data, secrets and customer documents, and OWASP advises removing, masking, hashing or encrypting such values. Log identifiers and redacted excerpts, sample full content selectively with audited access, and apply retention rules to traces.

How do I make sure the same failure does not come back?

Turn it into a minimal replay case with the task, recorded tool responses, allowed actions and forbidden behaviour, then run it on every prompt, model or tool change. Check deterministic rules in code, and run the case several times because agent behaviour varies between runs.

All articles