Trace and Debug an AI Agent in Python: Step Logs, Token Costs and Replays

8 min read

The problem: when an agent fails, you need to see what it saw

An agent run is a chain of decisions: a model call, a tool call, another model call. When the final answer is wrong, the cause can be at any link. Did the model call the wrong tool? Did the tool return bad data? Did the model get good data and misread it? Did the history get trimmed and lose a fact?

The final answer alone cannot tell you. And agents are hard to debug by rerunning, because the next run may take a different path, or the tool data may have changed since.

What you need is the same thing every lesson has hinted at: a record of every step. Anthropic's "Building effective agents" lists transparency, showing the agent's steps explicitly, as one of its core principles. This lesson builds that for the trip helper with three small scripts:

  1. A tracer that writes every model call and tool call to a JSON Lines file, with tokens, cost and timing.
  2. A trace viewer that prints a run as a readable timeline.
  3. A replayer that re-runs a recorded question using the recorded tool results, so the tools cannot change the outcome.

There are hosted tracing products and open standards for this. The file based version here shows what they record and why, with nothing to install.

The tracer

Save this as tracer.py:

python
# file: tracer.py
import json
import os
import time
import uuid
from pathlib import Path

PRICE_IN = float(os.getenv("AGENT_PRICE_IN_PER_M", "0"))   # set to your provider's prices
PRICE_OUT = float(os.getenv("AGENT_PRICE_OUT_PER_M", "0"))


class Tracer:
    """Append one JSON line per event. Plain files are easy to grep, diff and replay."""

    def __init__(self, folder: str = "traces"):
        self.run_id = time.strftime("%Y%m%d-%H%M%S-") + uuid.uuid4().hex[:6]
        self.path = Path(folder) / f"{self.run_id}.jsonl"
        self.path.parent.mkdir(exist_ok=True)
        self.totals = {"prompt_tokens": 0, "completion_tokens": 0, "cost_usd": 0.0}

    def log(self, event: str, **data) -> None:
        record = {"ts": round(time.time(), 3), "run_id": self.run_id, "event": event, **data}
        with self.path.open("a") as f:
            f.write(json.dumps(record, default=str) + "\n")

    def llm_call(self, step: int, request: dict, response, seconds: float) -> None:
        usage = response.usage
        cost = (usage.prompt_tokens * PRICE_IN + usage.completion_tokens * PRICE_OUT) / 1_000_000
        self.totals["prompt_tokens"] += usage.prompt_tokens
        self.totals["completion_tokens"] += usage.completion_tokens
        self.totals["cost_usd"] += cost
        msg = response.choices[0].message
        self.log("llm_call", step=step, model=response.model, seconds=round(seconds, 2),
                 messages=request["messages"], finish_reason=response.choices[0].finish_reason,
                 content=msg.content,
                 tool_calls=[{"id": c.id, "name": c.function.name, "arguments": c.function.arguments}
                             for c in (msg.tool_calls or [])],
                 prompt_tokens=usage.prompt_tokens, completion_tokens=usage.completion_tokens,
                 cost_usd=round(cost, 6))

Design choices:

  • One file per run, named with a timestamp and a short random id, in a traces folder. Easy to find, easy to delete.
  • JSON Lines: one JSON object per line, appended as events happen. If the program crashes halfway, every event before the crash is already on disk. You can read the file with grep, jq or ten lines of Python.
  • Every event carries the run_id and a timestamp, so traces from many runs can be merged and still sorted out.
  • llm_call stores the full request messages. That is the most important field: it is exactly what the model saw. Storing it makes each line large, which is fine for debugging. In production you might store it only for failed runs.

Token counts come from response.usage, as in lesson 11. Cost uses prices per million tokens from environment variables, defaulting to 0 for local models. Set them to your provider's published prices when you use a paid API.

An agent that reports to the tracer

Save this as traced_agent.py. It uses trip_tools.py from lesson 4:

python
# file: traced_agent.py
import time

from llm import client, MODEL
from tracer import Tracer
from trip_tools import TOOLS, run_tool


def run_agent(user_text: str, tool_runner=run_tool, max_steps: int = 6) -> tuple[str, Tracer]:
    tracer = Tracer()
    tracer.log("run_start", model=MODEL, user_text=user_text)
    messages = [{"role": "system", "content": "You are a trip helper. Use tools for facts. Be brief."},
                {"role": "user", "content": user_text}]
    answer = None
    for step in range(1, max_steps + 1):
        request = {"model": MODEL, "messages": messages, "tools": TOOLS, "temperature": 0}
        start = time.time()
        response = client.chat.completions.create(**request)
        tracer.llm_call(step, request, response, time.time() - start)
        msg = response.choices[0].message
        messages.append(msg.model_dump(exclude_none=True))  # plain dicts are easy to log
        if not msg.tool_calls:
            answer = msg.content
            break
        for call in msg.tool_calls:
            start = time.time()
            result = tool_runner(call.function.name, call.function.arguments)
            tracer.log("tool_call", step=step, call_id=call.id, name=call.function.name,
                       arguments=call.function.arguments, result=result, seconds=round(time.time() - start, 3))
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
    tracer.log("run_end", answer=answer, **tracer.totals)
    return answer, tracer


if __name__ == "__main__":
    answer, tracer = run_agent("Is Oslo colder than Lisbon right now?")
    print("answer:", answer)
    print("trace file:", tracer.path)
    print("totals:", tracer.totals)

Two details make replay possible later:

  • tool_runner is a parameter. By default it is the real run_tool. The replayer passes a different function that returns recorded results.
  • Assistant messages are stored as plain dicts with model_dump(exclude_none=True), so the whole history can be written to JSON.

Run it:

bash
python traced_agent.py

In the tested run with qwen2.5:1.5b on Ollama, it answered that Oslo is colder than Lisbon, with both forecasts and rain chances, and printed the trace file path and these totals:

text
totals: {'prompt_tokens': 906, 'completion_tokens': 109, 'cost_usd': 0.0}
sequenceDiagram
    autonumber
    participant A as traced_agent
    participant M as Model
    participant T as get_weather
    participant F as traces/*.jsonl
    A->>F: run_start: model, user_text
    A->>M: step 1 request
    M-->>A: 2 tool calls, in=381 out=43
    A->>F: llm_call: full request, tokens, 5.74s
    A->>T: Oslo, then Lisbon
    T-->>A: forecasts
    A->>F: tool_call x2: arguments, result, seconds
    A->>M: step 2 request, now with tool results
    M-->>A: answer, in=525 out=66
    A->>F: llm_call: 13.43s
    A->>F: run_end: answer, totals in=906 out=109

Diagram: Every model call and tool call is appended to the JSON Lines trace as it happens.

Read a trace as a timeline

Save this as show_trace.py:

python
# file: show_trace.py
import json
import sys
from pathlib import Path

path = Path(sys.argv[1]) if len(sys.argv) > 1 else max(Path("traces").glob("*.jsonl"))
for line in path.read_text().splitlines():
    e = json.loads(line)
    if e["event"] == "llm_call":
        what = ", ".join(c["name"] for c in e["tool_calls"]) or f"answer: {(e['content'] or '')[:50]!r}"
        print(f"step {e['step']} LLM  {e['seconds']:>5}s  in={e['prompt_tokens']:<5} out={e['completion_tokens']:<4} {what}")
    elif e["event"] == "tool_call":
        print(f"step {e['step']} TOOL {e['name']}({e['arguments']}) -> {e['result'][:60]}")
    elif e["event"] == "run_end":
        print(f"total tokens in={e['prompt_tokens']} out={e['completion_tokens']} cost=${e['cost_usd']:.4f}")

With no argument it shows the newest trace. The tested output for the run above:

text
step 1 LLM   5.74s  in=381   out=43   get_weather, get_weather
step 1 TOOL get_weather({"city":"Oslo"}) -> {"city": "Oslo", "forecast": "cloudy", "high_c": 6, "low_c":
step 1 TOOL get_weather({"city":"Lisbon"}) -> {"city": "Lisbon", "forecast": "sunny", "high_c": 22, "low_c
step 2 LLM  13.43s  in=525   out=66   answer: 'Right now, Oslo is colder than Lisbon. The high te'
total tokens in=906 out=109 cost=$0.0000

The timings are from a CPU only machine and will be very different on yours. The pattern is what matters. In five lines you can see:

  • the model asked for two tools in one step (parallel calls, from lesson 3)
  • what each tool returned
  • that input tokens grew from 381 to 525 between steps, because the history now includes the tool results
  • which step took the most time

When an answer is wrong, this view usually tells you which link broke. If the tool results are right and the answer is wrong, the problem is the model's reasoning or the prompt. If a tool result is wrong, fix the tool. If the model never called a tool, look at the descriptions.

Timeline with a 5.74 second model call, two get_weather tool calls, then a 13.43 second model call; total 906 tokens in, 109 out

The tested run as a waterfall: 5.74 s for step 1, two tool calls, 13.43 s for step 2.

Animation: The tested trace, one line per event: two weather calls in step 1, then the answer, with input tokens growing from 381 to 525.

Replay a run

Some failures happen once and then not again, because tool data changed or the model took a different path. The trace holds what the tools returned. Save this as replay.py:

python
# file: replay.py
"""Re-run an agent with the tool results recorded in a trace, so tools cannot change the outcome."""
import json
import sys
from pathlib import Path

from traced_agent import run_agent

path = Path(sys.argv[1]) if len(sys.argv) > 1 else max(Path("traces").glob("*.jsonl"))
events = [json.loads(line) for line in path.read_text().splitlines()]
user_text = next(e["user_text"] for e in events if e["event"] == "run_start")
recorded = {(e["name"], e["arguments"]): e["result"] for e in events if e["event"] == "tool_call"}


def replay_tool(name: str, arguments: str) -> str:
    if (name, arguments) in recorded:
        return recorded[(name, arguments)]
    return json.dumps({"error": "not in the recording"})  # the model took a different path


print("replaying:", path.name, "| question:", user_text)
answer, tracer = run_agent(user_text, tool_runner=replay_tool)
print("answer now:", answer)
print("new trace:", tracer.path)

The replayer:

  1. Reads the original question from the run_start event.
  2. Builds a lookup of (tool name, arguments) to recorded result.
  3. Runs the agent again with replay_tool, which returns the recorded result for any call that matches, and an error for any call that does not.

In the tested run, the replay produced the same answer as the original and wrote a new trace. That is expected here, because the original run used temperature 0 and the model asked for the same calls.

What replay is good for:

  • Testing a fix against a past failure. Change the system prompt, replay the failing trace, and see if the answer changes, without depending on live tools.
  • Comparing models on identical data. Replay the same trace with a different AGENT_MODEL.
  • Spotting divergence. If the replay hits a "not in the recording" error, the new version took a different path. That is useful information in itself.

What replay is not: a guarantee of identical model output. Models can vary between runs even at temperature 0, and changing anything in the prompt can change the path. Replay pins the tool results; it does not pin the model.

Turning traces into tests

A trace of a failed run contains everything you need for a new eval case from lesson 14: the input, the tool calls the agent should have made, and the answer that was wrong. A simple workflow:

  1. A user reports a bad answer.
  2. Find the trace by time or run id.
  3. Read it with show_trace.py and find the broken link.
  4. Add the input as a case in eval_agent.py.
  5. Fix the agent, rerun the suite, and confirm the new case passes and the old ones still do.

That loop is how an agent improves over time without breaking what already works.

What to record, and what not to

Traces contain everything the model saw, which can include personal information from users and anything your tools returned. Treat them like any other sensitive log:

  • Never log API keys or secrets. The tracer stores messages and tool results, not client configuration. Keep it that way, and keep secrets out of prompts (lesson 6).
  • Decide how long to keep traces, and delete old files.
  • Remove personal data before turning a trace into a shared test case.
  • Restrict access to the traces folder on a shared server.

Beyond files

When one machine and a folder of JSON files is no longer enough, the same events map onto standard tools. OpenTelemetry is an open standard for traces and spans, and it has semantic conventions for generative AI operations, with attribute names such as gen_ai.usage.input_tokens. Those conventions are still marked as in development, so names can change. Hosted LLM observability products accept similar data. The concepts carry over directly: a run is a trace, each model or tool call is a span, and tokens, cost and timings are attributes. Building the file version first means you will know exactly what to look for in those tools.

Common mistakes

  • Logging only the final answer. The cause of a bad answer is almost always in an earlier step.
  • Not logging the exact messages sent. "The model saw the weather" is a guess; the logged request is a fact.
  • Writing logs only at the end of a run. A crash loses everything. Append as you go.
  • Logging secrets or full personal data without a plan for retention and access.
  • Replaying and expecting identical model output. Replay controls the tools, not the model.

What to try next

  • Set AGENT_PRICE_IN_PER_M and AGENT_PRICE_OUT_PER_M to your provider's prices and rerun to see cost per run.
  • Make a tool fail on purpose (ask about Paris) and read the trace to see how the model handled the error.
  • Add a budget_stop event using the Budget class from lesson 11, so stopped runs are visible in traces.
  • Write a script that reads every trace in the folder and prints average tokens per run.

Where to go from here

You now have every piece of a working agent, written by hand: a loop, well designed tools, structured outputs, safety checks, short and long term memory, retrieval, planning, budgets, multiple agents, MCP, tests and tracing. The capstone project puts them together. From here, frameworks will make more sense, because you know what they do underneath, and you can judge when one saves time and when the plain loop is all you need.

Sources