Sub topic 15
Tracing agent runs
An agent run is a chain of model calls and tool calls that you don't control step by step. When it fails, the final answer rarely shows why. A trace is a structured record of what happened during one run. This chapter shows what to record, how to add tracing to the agent loop from earlier chapters, and how to read a trace to find the failing step.
This chapter assumes you can read the agent loop and run_tool from the earlier chapters, and that you know basic Python, JSON, and how a model call returns text or a tool call.
Why logs are not enough
You could add print statements. That works for one short run and breaks down quickly, for three reasons:
- A run has many steps, and flat log lines don't show which step caused which.
- Failures often come from a step far from where the symptom appears. A wrong tool argument at step 2 can surface as a wrong answer at step 6.
- Runs are not repeatable. The same goal can take a different path next time, so you need the record of the run that actually failed.
A trace fixes this by storing each unit of work as a span. A span is one timed operation with a name, a status, attributes, and a parent span. Spans nest, so the whole run reads as a tree.
What to record
Record enough to replay the reasoning without recording everything.
| Span kind | Record | Why it matters |
|---|---|---|
| run | goal, step limit, outcome (answered or step limit), total duration | Shows how the run ended |
| model | step number, message count, whether a tool call was requested, token counts, duration | Finds slow steps, growing context, and cost |
| tool | tool name, arguments, success or error, result size, duration | Finds bad arguments and failing tools |
Token counts and message counts show context growth. If the message count rises every step and latency rises with it, context management is your problem, not the model.
The shape of a trace
A single run with one tool call produces a small tree. The run span is the root. Each model call and tool call is a child.
Adding tracing to the loop
The tracer below keeps a stack of open spans so each new span knows its parent and depth. A context manager guarantees every span gets a duration and a status, even when an exception passes through.
import json
import time
import uuid
from contextlib import contextmanager
class Tracer:
def __init__(self):
self.run_id = uuid.uuid4().hex[:8]
self.spans = []
self._stack = []
self._next_id = 0
@contextmanager
def span(self, kind, name, **attrs):
record = {
"run_id": self.run_id,
"id": self._next_id,
"parent_id": self._stack[-1]["id"] if self._stack else None,
"depth": len(self._stack),
"kind": kind,
"name": name,
"started_at": time.time(),
"attrs": dict(attrs),
"status": "ok",
}
self._next_id += 1
self._stack.append(record)
t0 = time.perf_counter()
try:
yield record
except Exception as exc:
record["status"] = "error"
record["attrs"]["exception"] = repr(exc)
raise
finally:
record["duration_ms"] = round((time.perf_counter() - t0) * 1000, 2)
self._stack.pop()
self.spans.append(record)
def get_weather(city: str) -> str:
return json.dumps({"city": city, "temp_c": 18})
TOOLS = {"get_weather": get_weather}
def run_tool(name: str, arguments: dict) -> str:
if name not in TOOLS:
return json.dumps({"error": f"unknown tool: {name}"})
try:
return TOOLS[name](**arguments)
except Exception as exc:
return json.dumps({"error": str(exc)})
def result_is_error(result: str) -> bool:
try:
parsed = json.loads(result)
except json.JSONDecodeError:
return False
return isinstance(parsed, dict) and "error" in parsed
def run_agent_traced(call_model, user_goal: str, tracer: Tracer, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": user_goal}]
with tracer.span("run", "agent", goal=user_goal, max_steps=max_steps) as run_span:
for step in range(max_steps):
with tracer.span("model", "call_model", step=step, n_messages=len(messages)) as m:
reply = call_model(messages)
call = reply.get("tool_call")
m["attrs"]["requested_tool"] = call["name"] if call else None
messages.append({"role": "assistant", "content": reply.get("content"), "tool_call": call})
if call is None:
run_span["attrs"]["outcome"] = "answered"
return reply["content"]
with tracer.span("tool", call["name"], arguments=call["arguments"]) as t:
result = run_tool(call["name"], call["arguments"])
t["attrs"]["result_chars"] = len(result)
if result_is_error(result):
t["status"] = "error"
t["attrs"]["error"] = result
messages.append({"role": "tool", "name": call["name"], "content": result})
run_span["attrs"]["outcome"] = "step_limit"
run_span["status"] = "error"
return "Stopped: step limit reached."
def fake_model(messages):
if messages[-1]["role"] == "user":
return {"content": None, "tool_call": {"name": "get_weather", "arguments": {"city": "Oslo"}}}
return {"content": "It is 18 C in Oslo.", "tool_call": None}
tracer = Tracer()
print(run_agent_traced(fake_model, "What is the weather in Oslo?", tracer))
for s in sorted(tracer.spans, key=lambda s: s["id"]):
print(" " * s["depth"] + f'{s["kind"]}:{s["name"]} {s["status"]} {s["duration_ms"]}ms')The output ends with a tree like this, with timings that vary:
run:agent ok 0.05ms
model:call_model ok 0.01ms
tool:get_weather ok 0.02ms
model:call_model ok 0.0msNote two details in the code.
run_toolreturns errors as text, so no exception reaches the tool span. The code checks the result and sets the span status itself. Without that check, every tool span would showokand the trace would hide failures.- Hitting the step limit does not raise an exception either. The code marks the run span as an error explicitly, so a search for failed runs finds it.
Exporting traces
Keep the trace as data, not formatted text. Writing one JSON object per line is enough to start, and you can query it with any tool that reads JSON.
with open("traces.jsonl", "a", encoding="utf-8") as f:
for s in tracer.spans:
f.write(json.dumps(s) + "\n")When you outgrow files, use a tracing standard such as OpenTelemetry or an agent-focused tracing service. The span model is the same: id, parent, name, timing, attributes. Moving your records over is mostly renaming fields.
Reading a trace
Start at the run span, then walk down the children in order. Common patterns:
| What you see | Likely cause | Where to look |
|---|---|---|
| Run ends with `step_limit` and the same tool repeats | The model ignores the tool result or the error message is unclear | Tool result text and tool description |
| Tool span errors on the first call, then succeeds | Model sent wrong arguments, then corrected | Argument schema and tool description |
| Model spans get slower each step | Context grows with every step | `n_messages` and token counts |
| Model requests a tool that does not exist | Stale or vague tool list in the prompt | Tool registry and system prompt |
| One tool span dominates the duration | Slow external call | Add a timeout or cache |
| Final answer contradicts a tool result | Model ignored or misread the observation | The tool result text in the trace |
Privacy and cost of traces
Traces contain goals, arguments, and results, which can include personal data, credentials, or customer records. Treat trace storage like any other data store.
Other practical rules:
- Store large payloads, such as full documents, as a size or a short preview, not in full. The tracer above records
result_charsfor this reason. - Sample traces in high-volume systems, but always keep traces for runs that ended in an error or hit the step limit.
- Give every run an id and put it in your application logs, so you can jump from a user's complaint to the trace.
Common mistakes
- Tracing only the model calls. Most failures happen at the tool boundary, so tool spans need arguments and results.
- Recording errors only when an exception is raised. Agents return errors as text, so check the result.
- Logging after the fact from the message list. The message list lacks timings, step boundaries, and parent links.
- Keeping everything forever. Trace volume and sensitivity grow quickly.
Exercise
A run ends with outcome steplimit. In the trace, steps 1 to 7 are all a tool span for searchdocs with status ok, and each model span has a larger n_messages than the one before. List two things you would check, and say which span fields you would use.
Show answer
First, check the result text of the searchdocs tool spans (the tool result in the trace). Status ok only means the call did not raise. The results may be empty or unhelpful, and the model may keep retrying the same query. Compare the arguments across spans to see whether the model repeats an identical query. Second, check nmessages (and token counts if recorded) on the model spans to see how fast context grows, since long results appended every step can push the model toward worse decisions. Likely fixes are to return a clearer "no results" message, shorten or summarize results, or add a repeated-call check that stops the loop.