How to debug an AI agent that took the wrong action
Debugging an AI agent means reconstructing what it actually did, each model call, tool call, retrieval step, and decision, and comparing that against what the user needed. Standard logs show the request went through; they don't show whether the task succeeded.
By Arun Prasad · Published · Last updated
On this page
Why AI agents are harder to debug than regular software
With regular software, an exception tells you something went wrong and a stack trace tells you where. An agent can produce no exception at all and still fail the user completely.
Consider a support agent that looks up a customer's order, calls a tool to check the status, retrieves some policy text, and writes a reply. Every step returns a 200. No errors are thrown. The model receives reasonable input and produces a grammatically correct response. And yet the user got the wrong policy, the tool returned a stale status, and the agent confidently said the order would arrive by Tuesday when it had already been cancelled.
None of that failure shows up in a request log. The only record is that a call was made and a response was returned. Standard monitoring tells you the agent ran; it doesn't tell you whether it did the right thing.
This is the core problem. An agent's failure lives in its reasoning across steps, what it chose to retrieve, how it interpreted a tool result, what it decided to say. Tracking that requires capturing the full trajectory, not just the envelope.
Step 1: Instrument your agent to capture a full trace
A useful trace captures every step in the agent's run: each model call with the input it received and the output it produced, every tool call with its arguments and the result that came back, retrieval context, timing, token counts, and a session ID that ties multi-turn exchanges together. Without the intermediate steps you can see that something went wrong, but not where.
There are four ways to send traces to PRISM by Block Convey, and you need one.
Python SDK
The SDK attaches a handler to your framework and records full trajectories: model calls, tool calls, retrieval, handoffs, and errors.
pip install "prismtrace-sdk>=0.5.1"Handlers are available for LangChain (PRISMtraceCallbackHandler), LangGraph (PRISMtraceLangGraphHandler), Google ADK (PRISMtraceADKAdapter), LiteLLM (install_litellm), and the OpenAI Agents SDK (install_openai_agents).
Zero-code proxy
Change one base URL in your model client config, no imports, no call-site changes. The proxy forwards the call, records it, and runs your guardrails in both directions.
# OpenAI client
base_url = "https://api.prism.blockconvey.com/proxy/openai/v1"
# Anthropic client
base_url = "https://api.prism.blockconvey.com/proxy/anthropic"HTTP API
For TypeScript, Go, Java, or any framework the SDK doesn't cover, send one POST after each model response.
POST https://api.prism.blockconvey.com/api/traces
X-PRISMtrace-Key: pt-sk-...
{
"project_id": "your-project-id",
"model": "gpt-4o",
"input_messages": [
{"role": "user", "content": "What is my order status?"}
],
"output_message": "Your order is currently in transit.",
"latency_ms": 820,
"session_id": "session-abc123"
}Required fields: project_id (string), model (string), input_messages (array of {role, content} objects), output_message (string), latency_ms (integer; use 0 if not measured). Optional fields include session_id, agent_id, agent_name, user_identifier, trace_id, token_count_input, token_count_output (integers), and metadata (object).
OpenTelemetry
Set two environment variables and point your OTLP exporter at https://api.prism.blockconvey.com/api/otlp. No PRISM SDK required.
A note on session IDs
If your agent handles multi-turn conversations, include a session_id on every trace that belongs to the same conversation. Traces with the same session ID are grouped into one conversation view. This cannot be backfilled: if you start sending session IDs later, earlier traces won't be joined to new ones. Set it from the start.
Step 2: Reconstruct the run
Reconstructing a run means reading the full sequence of steps the agent took, what it was given, what it called, and what each step returned, until you find where the wrong output entered the chain. Once traces are flowing, open the trace view for a failing run. You're looking for the full trajectory: every step in the order it happened, what the model received at each step, which tools were called and with what arguments, what retrieval returned, and where timing spiked.
The trace view in PRISM shows each of these as a named step. For an agent run, you'll see the model calls, tool calls, retrieval steps, retries, handoffs, and state transitions in sequence. For each step you can read the exact input and output, not a summary, but what was actually passed.
This is where you'll often spot the immediate cause: a tool returned an unexpected value and the model ran with it; retrieval pulled in a document that contradicted what the user asked; a parameter was wrong on the third retry. The trace makes those visible. The question of why it keeps happening is the next step.
Step 3: Find the pattern across runs
Finding the pattern across runs means answering how often this failure occurs and whether it's one cause or many. A single bad trace tells you one failure happened. It doesn't tell you how often, in what context, or whether it's the same underlying problem every time. For that you need to look across runs.
Every trace that arrives in PRISM is scored automatically, at no credit cost, without any configuration. The scores are customer satisfaction (0–100), response quality (0–100, covering accuracy, helpfulness, and clarity), the intent detected, and a flagged-for-review mark with a one-line reason. A trace is flagged when either score is below 40, the reply looks like a hallucination, the user seems very frustrated, or the conversation contradicts itself.
Those scores give you a way to filter: start with the flagged traces rather than reading everything. From there, PRISM groups repeated failures into patterns and shows how many sessions share each one. If the same kind of failure appears in 40 sessions this week, that's a different problem than a one-off edge case.
Agent Intelligence summarizes a window of traffic in prose and names the failure themes inside it, user intent, how conversations feel, repeated failures, missing knowledge. It's the step between reading individual traces and knowing what to fix first.
Step 4: Localize the cause
The next step is narrowing the failure to a specific cause: tracing the cluster back to whether it's the prompt, retrieval, state, or a tool call. Knowing that 40 sessions share a failure pattern is not the same as knowing why.
PRISM's Root Cause analysis clusters failing traces into recurring problems and traces each one back toward the prompt or code responsible. The causes it looks for include the system prompt, a missing retrieval source, stale state, a wrong tool choice, a parameter, a guardrail configuration, and individual workflow steps.
The output is a backlog. Each item in the backlog names the failure cluster, its severity, a suggested fix, an owner, and expected impact. A root-cause run over a project costs 5 credits.
At this point you have a specific, actionable item: the system prompt doesn't cover the case the user asked about, or retrieval is returning a document that was correct six months ago and is now stale, or a tool is being called with an argument derived from an earlier step that's frequently wrong. That's what you take into the fix.
Step 5: Turn a production failure into a regression test
A fix that isn't tested will regress. The only way to know a failure stays fixed is to run the same check after every deploy.
On Growth and above, an Issue can be turned into an evaluator with a single action (Turn into an evaluator). Once it's an evaluator, it runs on every new trace that arrives. If the same failure reappears, it's flagged.
You can also wire the check into your CI pipeline. Send a sample of your agent's replies to POST /api/intelligence/checks/run, and PRISM judges each reply against each check and returns passed. The result is false when any reply fails any check or couldn't be checked. The cost is 1 credit per reply per check, with a maximum of 50 replies per call. Nothing is stored.
For code-level fixes, a root-cause fix attempt drafts a patch, replays the failing traces against it, and opens a draft pull request. PRISM only opens the PR when remediation is turned on and write access has been granted, and only if at least 80% of replays pass. A person reviews and merges it. After the merge, PRISM compares pass rates for the 7 days before and the 7 days after, so you have a concrete before-and-after.
See Fix AI Agent Failures and Prove the Fix for the full remediation workflow.
How this looks in production
Here's what the instrumentation looks like for a LangChain model with the handler attached, and what PRISM records when the first trace arrives.
Instrumentation
import os
import prismtrace
from prismtrace import PRISMtraceCallbackHandler
from langchain_anthropic import ChatAnthropic
# Build the handler once, at startup, and share it.
handler = PRISMtraceCallbackHandler(
api_key=os.environ["PRISMTRACE_API_KEY"],
project_id=os.environ["PRISMTRACE_PROJECT_ID"],
host=os.environ["PRISMTRACE_HOST"],
agent_name="loan-assistant",
)
llm = ChatAnthropic(model="claude-sonnet-4-6", callbacks=[handler])
with prismtrace.session("conversation-1"): # one value per conversation
... # run your chain or agent
handler.close() # at shutdown, not per conversation; flushes firstThe handler records the full trajectory without changes to your agent logic: each model call, every tool call with its arguments and the result, retrieval steps if your chain includes them, and the final response.
What PRISM records on arrival
When the trace arrives, PRISM scores it automatically, no configuration required, no credit cost:
- A customer satisfaction score (0–100)
- A response quality score (0–100, covering accuracy, helpfulness, and clarity)
- The intent detected in the conversation
- A flagged-for-review mark if either score is below 40, the reply looks like a hallucination, the user seems frustrated, or the conversation contradicts itself, with a one-line reason explaining why it was flagged
The trajectory view shows each step in sequence: the model call inputs and outputs, tool calls and their results, timing for each step.
If the trace doesn't arrive
The connection health check in the dashboard walks the pipeline stage by stage, key created, your code reached PRISM, first trace arrived, trace readable, analysis ready, and names the stage that's stuck. That's usually faster than reading logs.
Connect your agent and start free to see your first trace in a few minutes.
Common mistakes
1. Treating a trace viewer as a complete debugging system
A trace viewer shows what happened in one run. It doesn't show whether that failure is happening in 2 sessions or 2,000, or whether it's the same root cause each time. Pattern-finding across runs is a separate step, and skipping it means you'll fix the most recent failure rather than the most frequent one.
2. Evaluating only the final answer
If you check only the last message the agent sent, you'll miss failures that happen mid-run: a tool call that returned a wrong result, a retrieval step that pulled in a stale document, a parameter passed incorrectly to a downstream step. The final answer can look plausible even when the reasoning that produced it was wrong. Inspect the full trajectory, tool calls, retrieval results, intermediate model outputs, not just the last line.
3. Sending traces without a session ID
If your agent handles multi-turn conversations and you don't include a session_id on each trace, PRISM can't group the exchanges into a conversation. You'll see individual turns but not the full journey, which makes it much harder to spot drift across a conversation or find where a user gave up. This can't be backfilled: traces sent before you add session IDs won't be joined retroactively.
4. Skipping the regression test
A fix that works today can silently regress when you change the prompt, update a retrieval source, or swap a model. If a production failure isn't turned into a check that runs on new traces, or into a CI check that runs before each deploy, there's nothing to tell you when it comes back. The fix is only done when the check is in place.
Why are AI agents harder to debug than regular software?
With regular software, something either throws an exception or it doesn't. The failure is observable at the point it happens. An agent can succeed on every observable step, 200s all the way down, tokens consumed, no exceptions raised, and still produce a wrong or harmful answer.
The reason is that the failure lives in the model's reasoning across multiple steps, not in any single function call. The model received a retrieval result that was technically valid but factually stale. It called the right tool but misread an earlier step's output when constructing the arguments. It produced a response that was grammatically correct and confidently wrong. None of those failures are visible from request and response pairs alone.
Tracking the outcome against what the user actually needed, not just whether the spans completed, requires capturing the full trajectory and scoring it against the intent. That's what makes agent debugging different from standard application monitoring.
What should an AI agent trace capture?
A useful agent trace needs the full trajectory, not just the envelope. At minimum:
- Every model call: the exact input (messages, system prompt, context) and the output the model produced
- Every tool call: the name of the tool, the arguments passed, and the result returned
- Retrieval context: what was retrieved, from where, and when
- Timing: how long each step took, so you can spot where latency spikes
- Token counts and cost: useful for understanding which workflows are expensive
- Errors: what failed, at which step
- A session ID: a stable identifier that ties multi-turn exchanges into one conversation
Without the intermediate steps, you can see that something went wrong in the final answer. You can't see which step produced the bad input that led to it.
The PRISM Python SDK records all of this automatically when you attach a handler to a supported framework. The HTTP API lets you send what you have: the five required fields are project_id, model, input_messages (an array of {role, content} objects), output_message (string), and latency_ms (integer). Everything else, session_id, agent_id, tool data, token counts, is optional but recommended. See the integrations page for setup options.
How do you turn a production failure into a regression test?
Three steps:
- Save the failure as an Issue. When PRISM clusters a set of failing traces into a recurring pattern, it creates an Issue with a diagnosis and suggested fix. That's the starting point.
- Turn the Issue into an evaluator. On Growth and above, the Issue page has a Turn into an evaluator action. Once it's an evaluator, it runs on every new trace that arrives. If the same failure reappears, it's flagged automatically.
- Wire it into CI. Send a sample of your agent's replies to POST /api/intelligence/checks/run before each deploy. PRISM returns passed: false if any reply fails any check. That makes the check a build requirement, not a manual review.
For code-level fixes, a root-cause fix attempt also replays the failing traces against a proposed patch before the pull request is opened, so you have evidence the fix works before anything merges. After the merge, PRISM compares pass rates for the 7 days before and after.
See Build an evaluation framework for AI agents for how evaluators fit into a broader quality process.
Related
- Agent ObservabilityWhat the four views show and how PRISM records and groups traces into conversations
- Agent IntelligenceHow Agent Intelligence clusters failures and surfaces patterns
- AI RemediationThe full remediation workflow, from patch to pull request to before-and-after comparison
- AI Agent Evaluation and Quality ChecksHow to write reusable evaluators and run them on real production traces
- Build an evaluation framework for AI agentsHow to structure ongoing evaluation alongside debugging
See exactly where your agent is failing
PRISM captures the full trajectory, every model call, tool call and retrieval step, and scores every trace automatically. Free to start.
Free to start, 100 credits each month.