Sub topic 15
Tracing agent runs
An agent run is a chain of model calls and tool calls. When it fails, the final answer rarely shows where it went wrong. A trace is a recorded timeline of every step in one run, and it lets you find the failing step. This chapter assumes you know the agent loop and tool calling from earlier chapters, and that you can read Python and JSON.
What a trace contains
A trace is one run from start to finish. It is made of spans. A span is one timed step, such as a single model call or a single tool call. Each span records:
- The span name and type (model or tool).
- The inputs and outputs.
- Start time and duration.
- Status, either ok or error.
- Token counts for model calls.
Spans are linked by a shared trace ID, so you can collect every step of one run.
A minimal tracer
You do not need a framework to start. This tracer writes one JSON line per span to a list. It uses only the standard library.
import json
import time
import uuid
class Tracer:
def __init__(self):
self.trace_id = str(uuid.uuid4())
self.spans = []
def record(self, name, kind, inputs, fn):
start = time.time()
status, output = "ok", None
try:
output = fn()
return output
except Exception as exc:
status, output = "error", str(exc)
raise
finally:
self.spans.append({
"trace_id": self.trace_id,
"name": name,
"kind": kind,
"inputs": inputs,
"output": output,
"status": status,
"duration_ms": round((time.time() - start) * 1000, 2),
})
tracer = Tracer()
result = tracer.record(
"get_weather", "tool", {"city": "Oslo"},
lambda: json.dumps({"city": "Oslo", "temp_c": 18}),
)
print(json.dumps(tracer.spans[0], indent=2))In your agent loop, wrap each call_model(messages) call and each run_tool(...) call with tracer.record. The finally block makes sure a span is saved even when the step raises an error.
Reading a trace
Read a failed run from the top and ask these questions in order:
- Did the model pick the right tool? If not, the tool description or system prompt is the likely cause.
- Were the arguments valid? Bad arguments point to a schema problem.
- Did the tool return an error? Check whether the model recovered or repeated the same call.
- Did the run end by answer or by hitting
max_steps? A step limit often means a loop of repeated calls. - Which span took the longest, and which used the most tokens?
Common mistakes
- Logging only the final answer. You lose every intermediate step.
- Not recording the full tool inputs. You cannot reproduce the failure without them.
- Storing secrets or personal data in span inputs. Redact them before saving.
- Using a new ID for each span with no shared trace ID. You cannot group spans into a run.
Tools you can adopt later
Hosted and open-source tracing tools, many built on the OpenTelemetry standard, store spans, show them as a timeline, and let you search them. The span model above maps directly onto them, so a hand-built tracer is a good way to learn what to record.
Exercise
A run ended with "Stopped: step limit reached." Which two things in the trace would you check first, and what would each suggest?
Show answer
Check the sequence of tool-call spans and their statuses. Repeated identical calls suggest the model is stuck and not using the result, or a tool keeps returning an error the model cannot fix. Then check the arguments and outputs of those spans to see whether a vague tool description or a bad schema caused it.