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:
| Span | What to record | Why it helps diagnosis |
|---|---|---|
| Agent invocation | User and tenant ID, task, prompt and tool-definition version, model version | Shows which configuration the failure happened under |
| Model call | Tool chosen, argument shape, finish reason, token count | Shows where the plan and the tool choice changed |
| Tool call | Tool name, call ID, response code, result status, retry count, duration | Separates a tool failure from a misreading |
| Retrieval | Returned document IDs and versions, filter applied | Exposes stale or wrong evidence |
| Side effect | ID of the order, ticket or refund created | Links 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:
- Write the user's authorised task and the expected outcome in one sentence.
- Find the last step at which the state was still correct.
- 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?
- Mark the step with the first "no" as the first divergence; most later errors follow from it.
- Compare with a successful trace of the same task type and note where the two paths split.
- 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.
| Symptom | Likely layer | Where to fix |
|---|---|---|
| The right tool was called with the right arguments, but it returned stale data | Integration or data freshness | Source system, cache, sync |
| The agent requested an action it is not authorised for | Model behaviour and the authorisation rule | Both: the tool check and the task definition |
| The tool ran twice after a timeout | Retry logic | Idempotency key, retry policy |
| The wrong one of two similar tools was chosen | Tool definitions | Tool name, description, argument schema |
| The tool returned an error and the agent took it as success | Result interpretation | Response schema, an explicit status field |
| Retrieval returned the wrong or an outdated document | Retrieval | Index, filter, document version |
| The agent repeated the same step in a loop | Stop rule | Step 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:
| Step | Span | Observation | Assessment |
|---|---|---|---|
| 1 | Agent invocation | Task: cancel 4471, start the refund | Correct |
| 2 | read_order(4471) | Delivered, amount known | Correct |
| 3 | cancel_order(4471) | Succeeded, cancellation record created | Correct |
| 4 | start_refund(4471) | HTTP 202, status "queued", refund ID R-311 | The tool worked correctly |
| 5 | Model call | Reported the "queued" result as "complete" | First divergence |
| 6 | Outside the trace | R-311 failed two hours later | No 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.