Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Debugging AI Agents: Replay, Traces, Logs

· 7 min read · Home Tech

In this article
  1. Why AI Agents Are Hard to Debug
  2. What a Trace Contains
  3. How Replay Works
  4. Logs vs. Traces: Complementary Roles
  5. Common Pitfalls and How to Avoid Them
  6. Choosing a Debugging Strategy
  7. Limitations and What Replay Cannot Show
  8. Frequently Asked Questions

Debugging production AI agents is made possible by replaying recorded traces and analyzing logs, which together expose the internal state and decision path that a black-box model hides. You capture every input, output, and intermediate step during live operation, then replay that sequence offline to reproduce errors, inspect variable values, and test fixes without affecting real users. This article explains how trace replay and log analysis work, what they reveal, and how to apply them to your own agents.

Why AI Agents Are Hard to Debug

Traditional software fails with a stack trace and a clear error message. AI agents, built on large language models (LLMs), fail in vaguer ways: they call the wrong tool, loop on the same step, or produce a plausible but incorrect answer. The model itself is a black box—you cannot step through its internal reasoning like you would a function call. What you can observe is everything around the model: the prompt sent, the tool calls made, the results returned, and the final output. That surrounding data is your window into the agent’s behavior.

Production adds another layer of difficulty. You cannot attach a debugger to a live agent without pausing service or risking data corruption. The agent may run across distributed services, making a single session hard to follow. And the nondeterministic nature of LLMs means the same input can produce different outputs on different runs. Replay solves these problems by recording the full session and letting you step through it later, deterministically.

What a Trace Contains

A trace is a structured, time-stamped record of one agent run. It typically includes:

  • Inputs: the original user message, system prompt, and any retrieved context.
  • Model calls: the exact prompt sent to the LLM, the response, token counts, and latency.
  • Tool calls: the function name, arguments, and the raw result returned.
  • State changes: variables updated, memory writes, and conversation history at each step.
  • Control flow: which branch the agent took (e.g., “decided to search the web” vs. “decided to ask a clarifying question”).
  • Errors and warnings: any exceptions, timeouts, or validation failures.

Each trace gets a unique ID, and child spans link to parent spans so you can reconstruct the full call tree. For example, a single user question might trigger a retrieval span, a model span, and a database lookup span, all nested under the top-level request.

How Replay Works

Replay takes a recorded trace and re-executes the agent’s logic offline, but with a crucial twist: instead of calling the live LLM or external APIs, it substitutes the recorded responses. This makes the replay deterministic—the agent follows the exact same path as the original run, even if the model has since changed or the external service is unavailable.

Concretely, a replay system works like this:

  1. Load the trace file and reconstruct the initial state (conversation history, variables, memory).
  2. Run the agent’s code, but intercept every LLM call and tool invocation.
  3. For each intercepted call, look up the recorded response in the trace and return it instead of making a real request.
  4. Compare the replayed execution to the original trace—any divergence indicates a bug or a change in code.

This lets you set breakpoints, inspect variables, and add logging to the replayed run without touching production. You can also modify the trace (e.g., change a tool result) to test how the agent would react to different data.

Logs vs. Traces: Complementary Roles

Logs and traces serve different purposes. Logs are unstructured or semi-structured messages written by the agent’s code—for example, “calling search tool with query=weather” or “user session expired.” They are cheap to produce and good for high-level monitoring, but they lack the full context of a session.

Traces are richer and structured, capturing the entire call graph and state. However, they are more expensive to store and process. In practice, you use both: logs for alerting and quick troubleshooting, traces for deep investigation. When an error appears in the logs, you can jump to the corresponding trace ID to see the full context around that log line.

For example, a log might say “Tool call failed: database timeout.” The trace shows that the agent had already made three failed attempts, each with increasing timeouts, and that the final error message was passed directly to the user without a fallback. That context is invisible in the log alone.

Common Pitfalls and How to Avoid Them

  • Not capturing enough state: If you only log final outputs, you cannot reproduce intermediate decisions. Always record the full prompt, tool arguments, and results.
  • Storing sensitive data: Traces often contain user messages and API responses. Redact PII (personally identifiable information) before storing, or store traces in a restricted-access system.
  • Ignoring nondeterminism: Even with replay, the agent’s code may depend on wall-clock time, random numbers, or external state. Freeze those in the trace (e.g., record the timestamp and random seed).
  • Replaying with changed code: If you update the agent’s logic, the replay may diverge from the original trace. That is not a bug—it is a sign that the code changed. Compare carefully to see whether the divergence is intended.
  • Over-relying on logs: Logs alone rarely contain enough detail to debug a complex agent. Use structured logging that includes trace IDs and key variables.

Choosing a Debugging Strategy

Start with logging, then add tracing as your agent grows. For a simple prototype, a few log lines may be enough. For a production agent handling thousands of requests, you need:

  • Correlation IDs to link logs across services.
  • Trace export to a storage system (e.g., an object store or a tracing backend).
  • Sampling to record only a fraction of traces (e.g., 10%) to control cost, while keeping 100% of error traces.
  • Replay tooling that can run a trace offline with breakpoints and variable inspection.

When an incident occurs, follow this process: find the trace ID from the error log, load the trace into your replay tool, set a breakpoint at the first suspicious step, and step through the agent’s decisions. Compare the recorded tool results to what the agent expected. Often the bug is not in the model but in the glue code—a wrong argument, a missing fallback, or an unhandled exception.

Limitations and What Replay Cannot Show

Replay shows you what the agent did, but not why the model chose that action. The model’s internal reasoning is not in the trace—only the prompt and the output. If the agent makes a poor decision that is logically consistent with the prompt, replay will not tell you which part of the prompt caused it. You can experiment by editing the prompt in the trace and re-running, but that is a manual process.

Replay also cannot catch issues that only appear under real concurrency or load. For example, a race condition between two agent runs may not reproduce in a single-threaded replay. For those, you need load testing and distributed tracing that captures timing across services.

Finally, replay depends on the quality of your instrumentation. If you did not record a particular variable, you cannot inspect it later. Invest in comprehensive tracing from the start—retrofitting it after an incident is much harder.

Frequently Asked Questions

What is the difference between tracing and logging in AI agents?

Tracing captures the full execution path of a single request, including nested tool calls and state changes, in a structured format. Logging records discrete events, often as text lines, without the full context. Tracing is more powerful for debugging, but logging is simpler and cheaper for monitoring. In practice, you use both, linking them with a common request ID.

Can I replay an agent run if the LLM has been updated?

Yes, because replay substitutes the recorded LLM responses instead of calling the live model. The agent’s code will follow the same path as the original run, regardless of the current model version. This is useful for testing whether a code change fixes a bug without depending on the model’s current behavior.

How much storage do traces require?

It varies, but a typical trace for a multi-step agent can be 10–100 KB of JSON. For a service handling 1 million requests per day, that is 10–100 GB per day. Use sampling to reduce storage, and retain full traces only for errors and a random sample of successes. Compress traces and store them in a cost-effective object store.

What should I do if my agent leaks sensitive data in traces?

Implement redaction before storing. Replace email addresses, phone numbers, and other PII with placeholders. If you cannot redact automatically, restrict access to the trace storage and encrypt it at rest. Also consider masking tool arguments that might contain user data, such as database queries or file contents.

Is replaying an agent the same as unit testing?

No. Unit testing verifies that a function returns expected outputs for given inputs. Replay verifies that the entire agent, with all its tool calls and state changes, behaves the same as a recorded run. Replay is closer to integration testing, but it uses recorded data instead of live dependencies. You can use replay to generate regression tests by turning a trace into a test case.

What if the agent’s behavior is nondeterministic even with replay?

If your agent code uses randomness, time, or external state, replay may not reproduce the exact behavior. Freeze those sources in the trace: record the random seed, use a mock clock, and stub external services. If the nondeterminism comes from the LLM itself, replay avoids that by using recorded responses. If it comes from parallel execution, replay may not capture race conditions—use distributed tracing instead.