Introduction
In our last lesson, we established a comprehensive framework for measuring agent quality using metrics across the Goal, Plan, and Act phases. We concluded that to calculate these detailed metrics, we need to capture a rich, granular dataset of the agent's entire execution process. Simply knowing the final outcome is insufficient for the kind of deep debugging and reliability engineering you're aiming for.
This lesson directly addresses that need. We will focus on how to implement structured logging that captures a full, replayable trace of an agent's execution. This is the foundational observability layer upon which all advanced evaluation, debugging, and reliability patterns are built. For a systems engineer, this is analogous to moving from scattered print statements to a cohesive, distributed tracing and logging pipeline. We will explore not just what to log, but how to structure it so that we can perfectly reconstruct and replay any given agent task, taming the non-determinism inherent in LLM-based systems.
The Observability Gap: Why Standard Logging Fails
Your experience with distributed systems has likely shown you that debugging complex, asynchronous operations is impossible without robust observability. Agentic systems introduce a new, formidable challenge: inherent non-determinism. Even with the same input, an agent might behave differently on subsequent runs.
To build a production-grade system, you must be able to answer why a specific failure occurred. This requires more than a standard log; it requires a complete, deterministic record of the execution.
Trustworthy AI Agents: Deterministic Replay
This article from the "Missing Primitives for Trustworthy AI" series provides an excellent first-principles explanation of the problem we're trying to solve.
Read the first two sections, the introduction and "Why Agent Debugging Is Non Deterministic." The author lists six sources of non-determinism that make standard debugging ineffective. This list is the core justification for the techniques we'll cover in this lesson.
As the article makes clear, logs show what happened, but a replayable trace allows us to reconstruct why. It is the difference between an autopsy report and a full video recording of the events leading up to a failure.
The Execution Trace: A Blueprint for Replay
The solution to non-determinism is to create a structured execution trace. This is an immutable, append-only log of every significant event that occurs during an agent's task lifecycle.

In a complete agentic architecture, the "Audit Trail" component is responsible for generating "JSONL Logs" and enabling "Full Replay." This is the system we are designing today.
A trace isn't just a list of messages. It's a structured narrative. At its simplest, it maps the agent's execution flow to a corresponding log of events.

This diagram illustrates the core concept: an execution graph on the left has a one-to-one correspondence with a structured "Replay Log" on the right. Each step, whether success or failure, is captured.
Designing the Log Schema: The Three Surfaces of Agent Observability
To create a useful trace, we need a robust schema. Randomly logging strings won't work. A powerful mental model for this is to think of agent activity as occurring on three distinct "surfaces," each requiring its own type of instrumentation.
[PDF] A Structured Logging Framework for Agent System Observability
The "AgentTrace" research paper provides a principled, schema-based methodology for capturing agent behavior. It introduces a taxonomy that is incredibly useful for structuring our thinking.
Read the Abstract for a high-level overview. Then, focus on the "Methodology" section, specifically the subsection "Surface Taxonomy and Extraction Procedure." This defines the three surfaces we will use to structure our logs: Operational, Cognitive, and Contextual.
Let's break down these three surfaces from an implementation perspective:
-
Operational Surface: This captures the agent's internal mechanics—its control flow.
- What it is: Method calls, function arguments, return values, execution timings, errors.
- Analogy: This is the equivalent of Application Performance Monitoring (APM) in traditional services. It traces the code's execution path.
- Example Log Event:
{ "surface": "operational", "event": "method_start", "method": "search_tool.execute", "args": {"query": "Q2 earnings"} }
-
Cognitive Surface: This is the most novel and critical surface for agent observability. It captures the agent's "mind."
- What it is: The full prompt sent to the LLM, the raw model response, extracted thoughts or reasoning steps (e.g., from a ReAct loop), generated plans, and any self-correction or critique.
- Why it's crucial: This surface explains why the agent made a particular decision. It's the source of truth for debugging flawed reasoning.
- Example Log Event:
{ "surface": "cognitive", "event": "llm_completion", "prompt": "...", "raw_response": "<thinking>I need to find the Q2 earnings. I will use the search_tool.</thinking><tool_call>...", "parsed_thought": "I need to find the Q2 earnings. I will use the search_tool." }
-
Contextual Surface: This tracks the agent's interactions with the external world.
- What it is: Outbound API calls (e.g., to a weather API), database queries (SQL or NoSQL), vector store lookups, and filesystem operations.
- Analogy: This is similar to tracing external dependencies in a microservices architecture.
- Example Log Event:
{ "surface": "contextual", "event": "api_call", "endpoint": "https://api.weather.com/v1/forecast", "request_headers": "...", "response_code": 200, "response_body": "{...}" }
By logging events from all three surfaces, we create a comprehensive record that captures not just the agent's actions, but also its reasoning and its environmental interactions.
From Logs to Traces: Structured Data and Causal Linking
A series of disconnected log entries is hard to parse. To make them useful, we need two things: a machine-readable format and a way to link related events.
- Format: We'll use JSON Lines (JSONL). Each log entry is a self-contained JSON object on a new line. This format is highly structured, easy to parse, and ideal for streaming.
- Causal Linking: We borrow a key concept from distributed tracing:
trace_idandspan_id.- A
trace_idis a unique identifier for an entire end-to-end task (e.g., one user request). Every single log event for that task shares the sametrace_id. - A
span_idis a unique identifier for a single unit of work within a trace (e.g., one LLM call, one tool execution). Spans can be nested to represent causal relationships.
- A
How Tracing works with OpenTelemetry
To solidify the concepts of traces and spans, this video on OpenTelemetry provides a clear, practical explanation. While we are focusing on generating the data now, understanding these concepts is key for the visualization work we'll do in the next lesson.
First, watch the introduction What is OpenTelemetry? to understand its role as a standard for telemetry data. Then, watch the segment on how the service section stitches everything together into a pipeline. This conceptual model of a pipeline connecting receivers, processors, and exporters is a standard pattern in observability engineering.
A log event in our JSONL file would therefore look something like this:
{
"uuid": "...",
"timestamp": "2023-10-27T10:00:05.123Z",
"trace_id": "trace-abc-123",
"span_id": "span-def-456",
"parent_span_id": "span-xyz-789",
"surface": "cognitive",
"event_body": {
"model": "claude-3.5-sonnet-20240620",
"prompt": "...",
"completion": "...",
"usage": { "input_tokens": 512, "output_tokens": 128 }
}
}
This structure is the key. It's machine-readable, contains all necessary metadata, and establishes clear causal links between events.
The Ultimate Goal: The Deterministic Replay Harness
Now we arrive at the most powerful application of our structured trace: deterministic replay. Having a perfect record of every non-deterministic input (LLM responses, tool outputs) allows us to build a harness that can replay a past execution with 100% fidelity.
This is a concept that should resonate with your background in systems engineering, as it draws heavily on principles like dependency injection and mocking.
Trustworthy AI Agents: Deterministic Replay
Let's return to the "Trustworthy AI Agents" article to see how to put these traces into practice.
Read the sections titled "Primitive 5: Deterministic Agent Harness" and "Why This Matters." The core idea is to design your agent to operate in two modes: Record Mode: Interacts with real systems while writing to the trace. Replay Mode: Interacts with "stubs" that read from the trace instead of calling external systems. Finally, review the "Practical Next Steps" for a summary of the implementation strategy.
Here is how you would implement this from first principles:
-
Instrumentation: You need to wrap every non-deterministic component of your agent. In Python, decorators are a perfect, non-intrusive way to do this.
- Wrap your LLM client's
generatemethod. The wrapper's job is to log the prompt and the completion to your trace file (a Cognitive event). - Wrap each tool's
executemethod. The wrapper logs the tool input and the tool's return value (a Contextual event). - Wrap key methods in your agent's core loop (
think,act). The wrapper logs the entry and exit of these functions (Operational events).
- Wrap your LLM client's
-
Dependency Injection: Design your agent to accept its clients (LLM client, tool clients) as arguments to its constructor, rather than hard-coding them.
class Agent: def __init__(self, llm_client, tool_executor): self.llm = llm_client self.tools = tool_executor def run(self, task): # ... agent logic uses self.llm and self.tools pass
-
Record and Replay Clients:
LiveLLMClient: The real client that calls the OpenAI/Anthropic API. Your instrumentation wrapper logs its inputs and outputs.ReplayLLMClient: A "mock" client that, instead of calling an API, reads the next LLM response for the currenttrace_idfrom your trace file and returns it.- You create similar
LiveToolExecutorandReplayToolExecutorpairs.
-
The Harness: Your main execution script now has a simple switch.
- To record a new run:
agent = Agent(LiveLLMClient(), LiveToolExecutor()). - To replay a past run (e.g.,
trace-abc-123):agent = Agent(ReplayLLMClient("trace-abc-123.jsonl"), ReplayToolExecutor("trace-abc-123.jsonl")).
- To record a new run:
This architecture gives you a superpower: you can step through a failed production run in your local debugger, with perfect fidelity, without making a single external network call. This transforms debugging from a guessing game into a deterministic engineering process. The trace file itself becomes a "golden file" for regression testing. If you change your agent's logic, you can replay your entire suite of past traces to ensure you haven't introduced regressions.
Conclusion
In this lesson, we have designed the cornerstone of a production-grade agentic system: a structured, replayable logging mechanism. By moving beyond simple logging to a principled approach, we can tame the non-determinism of agents and enable robust engineering practices.
Key Takeaways:
- Non-determinism is the core challenge: LLM sampling, tool outputs, and other factors make simple logging insufficient for debugging.
- The Execution Trace is the solution: An append-only JSONL file capturing every significant event.
- A Three-Surface Schema provides structure:
- Operational: The agent's code execution path.
- Cognitive: The agent's reasoning and LLM interactions.
- Contextual: The agent's interactions with the external world.
- Causal linking is key: Using
trace_idandspan_idturns a log stream into a coherent trace, laying the groundwork for distributed tracing. - Deterministic Replay is the ultimate goal: By instrumenting components and using dependency injection, you can create a harness to replay any past execution with perfect fidelity for debugging and regression testing.
Preview of the Next Lesson:
We now have the ability to generate a highly structured JSONL file that represents a complete execution trace. While this is perfect for machines, it can be difficult for humans to read and analyze, especially for complex, parallel tasks. In our next lesson, we will instrument agent workflows with trace spans to visualize execution flow, latency, and costs. We'll take the concepts of trace_id and span_id we introduced today and use OpenTelemetry-compatible tools like Jaeger or Grafana Tempo to transform our text-based traces into interactive graphs and timelines.