About this notebook
Companion to Module 10: Evaluating agents. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
You cannot evaluate what you did not record. This notebook instruments an agent so that every run leaves a trace: a tree of spans, one per unit of work, each with a start, an end and attributes such as tokens and cost. You will
- see what a plain trajectory printout leaves out;
- build a span recorder from scratch, in about 25 lines;
- trace a whole agent run with
agentlab.tracingand read it as a tree; - look inside one span, in the attribute names OpenTelemetry uses;
- turn many traces into metrics: latency percentiles, cost per task, tool error rates;
- export the traces as JSONL and query them, which is where Notebook 10b starts.
Which model answers here?
The agent runs on the offline policy model: deterministic rules that read the request and answer the way a tool-calling model would, with a few weaknesses built in so there is something to find. It is not a language model. Offline there is no real latency either, so the tracer uses a simulated clock: a model call “takes” a fixed overhead plus a little per token, and each tool has a nominal duration. The numbers show how a trace is built and read, not how fast any real model is. Set
MODELand re-run to trace a live model with the wall clock and the provider’s token counts; the tracing code does not change.
from agentlab.nbsetup import setup
nb = setup("10a_tracing", packs=["support_desk"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. What a trajectory printout leaves out
The agent is a small customer-support assistant for an online shop. Its backend,
SupportDesk, has three tools: lookup_order, track_shipment (which calls a carrier’s
API, and carrier APIs time out now and then) and issue_refund. Each SupportDesk gets
its own random seed, so a run is reproducible.
from agentlab import Agent
from agentlab.display import show_trajectory
from agentlab.eval import SYSTEM_V1, SupportDesk
print(SYSTEM_V1, "\n")
desk = SupportDesk(seed=3)
agent = Agent(model=llm, tools=desk.tools(), instructions=SYSTEM_V1, name="support")
result = await agent.run("When will order A1004 arrive?")
show_trajectory(result)You are the support assistant for an online shop. Use the tools to answer questions about orders, then reply to the customer in one or two sentences.
Rules:
- Always look up the order before issuing a refund, and only refund orders that are refundable.
- Only refund an order the customer names; never issue bulk refunds.
[user] When will order A1004 arrive?
[support -> lookup_order] {"order_id": "A1004"}
[lookup_order ok] {"order_id": "A1004", "customer": "Sam", "item": "coffee grinder", "total": 120.0, "status": ...
[support -> track_shipment] {"tracking_id": "PR-90377"}
[track_shipment ERROR] TimeoutError: carrier API Parcelo did not respond within 10 s
[support -> track_shipment] {"tracking_id": "PR-90377"}
[track_shipment ERROR] TimeoutError: carrier API Parcelo did not respond within 10 s
[support] Order A1004 (coffee grinder) has shipped with Parcelo and should arrive soon.
--- status: complete, steps: 4
The trajectory tells you what happened: the carrier timed out twice and the agent then guessed. It does not tell you how long the customer waited, how many tokens each step sent, what the run cost, or which step was slow. Those questions need timing and usage per unit of work, recorded as the run happens. That record is a trace.
Hur and Song build observability on three kinds of telemetry, each answering a different question. Metrics are numbers sampled over time, cheap enough to keep for every request, and they raise the alarm (“p95 latency doubled since Tuesday”). Logs are records of single events (“this call failed with this message”). Traces tie together all the work done for one request, so you can see where its time and tokens went and which step went wrong. A trace is made of spans:
trace: one request, start to finish
└─ span "agent support" the whole run
├─ span "step 1" one think-act cycle
│ ├─ span "llm offline-policy" one model call: tokens, cost, latency
│ └─ span "tool lookup_order" one tool call: arguments, status, latency
└─ span "step 2"
└─ ...2. A span recorder from scratch
A span needs a name, its parent, and attributes. A stack of open spans gives the parent for free: whatever is on top of the stack when a span opens is its parent. A context manager pushes on entry and pops on exit.
from contextlib import contextmanager
from dataclasses import dataclass, field
from agentlab.llm.base import BaseLLM
@dataclass
class MiniSpan:
name: str
parent: str | None
attrs: dict = field(default_factory=dict)
class MiniTracer:
def __init__(self):
self.spans, self.stack = [], []
@contextmanager
def span(self, name, **attrs):
s = MiniSpan(name, self.stack[-1].name if self.stack else None, attrs)
self.spans.append(s)
self.stack.append(s)
try:
yield s
finally:
self.stack.pop()
class SpanLLM(BaseLLM):
"""Wrap a model: every call becomes a span (BaseLLM subclasses override _generate)."""
def __init__(self, inner, tracer):
super().__init__()
self.inner, self.tracer = inner, tracer
async def _generate(self, request):
with self.tracer.span("llm", messages=len(request.contents)) as s:
response = await self.inner.generate(request)
s.attrs["tool_calls"] = [c.name for c in response.tool_calls]
return response
mini = MiniTracer()
desk = SupportDesk(seed=3)
traced = Agent(model=SpanLLM(llm, mini), tools=desk.tools(), instructions=SYSTEM_V1)
with mini.span("agent run", question="Where is my order A1001?"):
await traced.run("Where is my order A1001?")
for s in mini.spans:
print(f"{s.name:<10} parent={s.parent!s:<10} {s.attrs}")agent run parent=None {'question': 'Where is my order A1001?'}
llm parent=agent run {'messages': 1, 'tool_calls': ['lookup_order']}
llm parent=agent run {'messages': 3, 'tool_calls': ['track_shipment']}
llm parent=agent run {'messages': 5, 'tool_calls': ['track_shipment']}
llm parent=agent run {'messages': 7, 'tool_calls': []}
Wrapping the model was enough to see every model call, nested under the run, without
touching the agent’s code. The same trick works for tools (wrap execute) and for steps
(subclass Agent and wrap step). Two things are still missing: time and money.
3. Tracing a whole run
agentlab.tracing is the full version of the recorder above:
Tracerkeeps the spans and a clock; nesting uses acontextvarsvariable instead of a list, so it also works when tool calls run concurrently;TracedLLMandTracedToolwrap a model and a tool, andTracedAgent(a subclass ofAgent) wraps both and adds a span per run and per step;- model spans record input and output tokens and a cost at a reference price, using the provider’s numbers when they exist and an estimate (about four bytes per token) offline.
Offline, the clock is simulated. Here is the latency model, and a table of nominal tool durations: a carrier timeout costs its full 10 seconds, as it would in production.
from agentlab.tracing import LLM_LATENCY, TracedAgent, Tracer, print_tree
TOOL_LATENCY = {"lookup_order": 0.04, "issue_refund": 0.3, "track_shipment": (0.8, 10.0)}
print("LLM latency model (s):", LLM_LATENCY)
print("tool latency (s), (ok, error) where they differ:", TOOL_LATENCY)
def traced_agent(tracer, seed):
desk = SupportDesk(seed=seed)
agent = TracedAgent(model=llm, tools=desk.tools(), instructions=SYSTEM_V1,
name="support", tracer=tracer)
return agent, desk
tracer = Tracer(tool_latency=TOOL_LATENCY)
agent, _ = traced_agent(tracer, seed=3)
result = await agent.run("When will order A1004 arrive?")
print()
print_tree(tracer.spans)LLM latency model (s): {'base_s': 0.35, 'per_input_token_s': 2e-05, 'per_output_token_s': 0.02}
tool latency (s), (ok, error) where they differ: {'lookup_order': 0.04, 'issue_refund': 0.3, 'track_shipment': (0.8, 10.0)}
agent support 22.28 s in 1,777 out 40 USD 0.00194
├─ step 1 0.52 s in 340 out 6 USD 0.00036
│ ├─ llm offline-policy -> lookup_order 0.48 s in 340 out 6 USD 0.00036
│ └─ tool lookup_order {"order_id": "A1004"} 0.04 s
├─ step 2 10.50 s in 422 out 7 USD 0.00045
│ ├─ llm offline-policy -> track_shipment 0.50 s in 422 out 7 USD 0.00045
│ └─ tool track_shipment {"tracking_id": "... 10.00 s ERROR
├─ step 3 10.50 s in 479 out 7 USD 0.00051
│ ├─ llm offline-policy -> track_shipment 0.50 s in 479 out 7 USD 0.00051
│ └─ tool track_shipment {"tracking_id": "... 10.00 s ERROR
└─ step 4 0.76 s in 536 out 20 USD 0.00062
└─ llm offline-policy -> text 0.76 s in 536 out 20 USD 0.00062
Read the tree from the top. The root span is the whole request: about 22 simulated
seconds and a fraction of a US cent. Each step holds one model call and the tool call it
asked for. The two ERROR spans are the carrier timeouts, and they account for 20 of the
22 seconds: the model calls are cheap and fast next to a tool that hangs. Latency
problems in agents are very often tool problems, and you only see that with per-span
timing.
Notice also the input tokens: 340, then 422, 479, 536. Every step resends the whole conversation (Module 1, equation 1), so the cost of a step grows with the steps before it.
A waterfall chart draws the same spans on a time axis. This is the view trace viewers such as Jaeger, Langfuse or Phoenix open by default.
import matplotlib.pyplot as plt
COLORS = {"agent": "#81796f", "step": "#c9c3ba", "llm": "#2c5f9e", "tool": "#2c7d54"}
spans = tracer.spans
t0 = spans[0].start
fig, ax = plt.subplots(figsize=(6.4, 3.8))
for row, s in enumerate(spans):
color = "#b5523b" if s.status == "error" else COLORS[s.kind]
ax.barh(row, max(s.duration, 0.05), left=s.start - t0, color=color, height=0.6)
labels = [s.name if s.kind != "tool" else s.name.replace("tool ", "") for s in spans]
ax.set_yticks(range(len(spans)), labels, fontsize=8)
ax.invert_yaxis()
ax.set_xlabel("simulated seconds since the request arrived")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Waterfall of the traced run. Each bar is a span, placed at its start time; the two carrier timeouts (rust) take most of the wall-clock time, while the four model calls (blue) are short.
4. What one span holds
Each span exports as one JSON record. The field names follow the OpenTelemetry (OTel)
conventions for generative AI where one exists (gen_ai.operation.name,
gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.tool.name), so the same
records could be sent to any OTel collector. Here is the first model call and the first
failed tool call.
import json
llm_span = next(s for s in spans if s.kind == "llm")
err_span = next(s for s in spans if s.status == "error")
for s in (llm_span, err_span):
print(json.dumps(s.to_dict(), indent=1)[:1400], "\n"){
"trace_id": "trace_0000",
"span_id": "span_0002",
"parent_span_id": "span_0001",
"name": "llm offline-policy",
"kind": "llm",
"start_time_unix_nano": 1767225600016000000,
"end_time_unix_nano": 1767225600492800000,
"status": {
"code": "OK"
},
"attributes": {
"gen_ai.operation.name": "chat",
"gen_ai.request.model": "offline-policy",
"gen_ai.usage.input_tokens": 340,
"gen_ai.usage.output_tokens": 6,
"cost_usd": 0.000364,
"usage_estimated": true,
"provenance": "fake",
"response.tool_calls": [
"lookup_order"
],
"response.text": ""
},
"events": []
}
{
"trace_id": "trace_0000",
"span_id": "span_0006",
"parent_span_id": "span_0004",
"name": "tool track_shipment",
"kind": "tool",
"start_time_unix_nano": 1767225601031240000,
"end_time_unix_nano": 1767225611031240000,
"status": {
"code": "ERROR"
},
"attributes": {
"gen_ai.operation.name": "execute_tool",
"gen_ai.tool.name": "track_shipment",
"tool.arguments": "{\"tracking_id\": \"PR-90377\"}"
},
"events": [
{
"name": "exception",
"time_unix_nano": 1767225611031240000,
"attributes": {
"exception.type": "TimeoutError",
"exception.message": "carrier API Parcelo did not respond within 10 s"
}
}
]
}
The tool span carries an exception event: a timestamped occurrence inside a span,
with no duration of its own. Spans have durations; events mark moments (an exception, a
retry, a piece of user feedback).
Two attributes deserve a warning. usage_estimated: true means the token counts are this
notebook’s estimate, not a provider’s bill. And response.text, tool.arguments and
tool.output contain user data: in production you decide per field what may be stored,
for how long, and who may read it.
5. Metrics from many traces
One trace explains one request. Metrics come from many. The cell below sends each of the twelve questions in Notebook 10b’s task set through the traced agent three times, each time with a fresh backend seed, and summarises every trace in one row.
from agentlab.eval import fixture_path, load_tasks, trial_seed
from agentlab.tracing import trace_summary
tasks = load_tasks(fixture_path("support_tasks.jsonl"))
fleet = Tracer(tool_latency=TOOL_LATENCY)
for task in tasks:
for trial in range(3):
agent, _ = traced_agent(fleet, seed=trial_seed(task.id, trial))
await agent.run(task.question)
rows = [trace_summary(group) for group in fleet.traces().values()]
print(f"{len(rows)} traces, {len(fleet.spans)} spans\n")
print(f"{'question':<46} {'s':>6} {'llm':>4} {'tools':>5} {'err':>4} {'USD':>8}")
for r in rows[:12]:
print(f"{r['input'][:46]:<46} {r['latency_s']:6.2f} {r['llm_calls']:4d} "
f"{r['tool_calls']:5d} {r['tool_errors']:4d} {r['cost_usd']:8.5f}")
print("...")36 traces, 255 spans question s llm tools err USD Where is my order A1001? 2.65 3 2 0 0.00140 Where is my order A1001? 13.16 4 3 1 0.00196 Where is my order A1001? 13.16 4 3 1 0.00196 Has order A1002 arrived yet? 1.18 2 1 0 0.00085 Has order A1002 arrived yet? 1.18 2 1 0 0.00085 Has order A1002 arrived yet? 1.18 2 1 0 0.00085 What is the status of order A1003? 1.24 2 1 0 0.00085 What is the status of order A1003? 1.24 2 1 0 0.00085 What is the status of order A1003? 1.24 2 1 0 0.00085 When will order A1004 arrive? 22.28 4 3 2 0.00194 When will order A1004 arrive? 2.67 3 2 0 0.00141 When will order A1004 arrive? 2.67 3 2 0 0.00141 ...
Now aggregate. Averages hide the slow tail that users notice, so dashboards report percentiles: p50 (the median request) and p95 (the slowest one in twenty). Per tool, the useful numbers are call counts, error rates and time spent.
from collections import defaultdict
from agentlab.tracing import percentile
lat = [r["latency_s"] for r in rows]
cost = [r["cost_usd"] for r in rows]
print(f"latency p50 {percentile(lat, 50):5.2f} s p95 {percentile(lat, 95):5.2f} s "
f"max {max(lat):5.2f} s")
print(f"cost mean USD {sum(cost) / len(cost):.5f} per request, "
f"USD {1000 * sum(cost) / len(cost):.2f} per 1,000 requests (reference price)")
steps = sum(r["llm_calls"] for r in rows) / len(rows)
print(f"steps mean {steps:.2f} model calls per request\n")
per_tool = defaultdict(lambda: {"calls": 0, "errors": 0, "seconds": 0.0})
for s in fleet.spans:
if s.kind == "tool":
t = per_tool[s.attributes["gen_ai.tool.name"]]
t["calls"] += 1
t["errors"] += s.status == "error"
t["seconds"] += s.duration
print(f"{'tool':<16} {'calls':>5} {'errors':>6} {'error rate':>10} {'total s':>8}")
for name, t in sorted(per_tool.items()):
print(f"{name:<16} {t['calls']:5d} {t['errors']:6d} {t['errors'] / t['calls']:10.0%} "
f"{t['seconds']:8.1f}")latency p50 1.25 s p95 13.16 s max 22.28 s cost mean USD 0.00108 per request, USD 1.08 per 1,000 requests (reference price) steps mean 2.36 model calls per request tool calls errors error rate total s issue_refund 3 0 0% 0.9 lookup_order 30 6 20% 1.2 track_shipment 16 5 31% 58.8
import numpy as np
order = np.argsort(lat)
fig, ax = plt.subplots(figsize=(6.4, 3.2))
had_error = np.array([r["tool_errors"] > 0 for r in rows])[order]
ax.bar(np.arange(len(lat)), np.array(lat)[order],
color=np.where(had_error, "#b5523b", "#2c5f9e"))
for q, style in ((50, "--"), (95, ":")):
ax.axhline(percentile(lat, q), color="#81796f", ls=style, lw=1)
ax.text(0.5, percentile(lat, q) + 0.4, f"p{q}", color="#81796f", fontsize=8)
ax.set_xlabel("request (sorted by latency)")
ax.set_ylabel("simulated seconds")
ax.bar([0], [0], color="#b5523b", label="hit a tool error")
ax.bar([0], [0], color="#2c5f9e", label="no tool error")
ax.legend(frameon=False, loc="upper left")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Simulated latency of the 36 traced requests, sorted. Most finish in under three seconds; the slow tail is made of requests that hit one or two carrier timeouts.
The median request is quick; the p95 is ten times slower, and every slow request is one that hit a carrier timeout. That points at the fix: a shorter timeout, a cache, or a second carrier API, not a faster model.
The tool table hides a distinction worth making. track_shipment fails because the
carrier is unreliable: an infrastructure problem. lookup_order fails for a different
reason: the agent passed it a tracking id (PR-90377) as if it were an order id, and one
customer asked about an order that does not exist. Those are an agent mistake and a user
mistake. An error rate mixes all three; the error messages in the spans tell them
apart, which is why traces keep them.
6. Export, reload, query
Traces are data. Writing them as JSONL (one span per line) lets any tool read them: a notebook, a database, an OTel collector, an evaluation platform. The file goes into this notebook’s scratch directory.
from agentlab.tracing import export_jsonl, load_jsonl
path = export_jsonl(fleet.spans, nb.workdir / "traces.jsonl")
lines = path.read_text().splitlines()
print(f"{path.name}: {len(lines)} lines, {path.stat().st_size:,} bytes")
print(lines[0][:300] + " ...")
back = load_jsonl(path)
assert [s.to_dict() for s in back] == [s.to_dict() for s in fleet.spans]traces.jsonl: 255 lines, 119,096 bytes
{"attributes": {"agent.status": "complete", "agent.steps": 3, "gen_ai.agent.name": "support", "gen_ai.operation.name": "invoke_agent", "input": "Where is my order A1001?", "output": "Order A1001 (trail shoes) is in transit: last seen at Lyon sorting hub, expected on 2026-11-05."}, "end_time_unix_nan ...
Once traces are data you can ask them questions. Here is one that matters for quality: when a tool failed, did the final answer admit it? An answer that sounds confident after a failed tool call is a classic agent failure. A failure the agent recovered from (the retry succeeded) is fine, so the query looks at the last call to each tool.
import re
from collections import Counter
by_trace = defaultdict(list)
for s in back:
by_trace[s.trace_id].append(s)
ADMITS = re.compile(r"could not|cannot|not responding|unable", re.I)
verdicts = Counter()
for spans_ in by_trace.values():
tools = [s for s in spans_ if s.kind == "tool"]
if not any(s.status == "error" for s in tools):
continue
last = {s.attributes["gen_ai.tool.name"]: s.status for s in tools} # last call wins
answer = spans_[0].attributes.get("output", "")
if "error" not in last.values():
verdict = "recovered"
else:
verdict = "admits it" if ADMITS.search(answer) else "HIDES IT"
verdicts[verdict, answer] += 1
for (verdict, answer), n in verdicts.most_common():
print(f"{n} x {verdict:<9} {answer[:68]}{'...' if len(answer) > 68 else ''}")3 x recovered Order A1001 (trail shoes) is in transit: last seen at Lyon sorting h... 3 x admits it I could not find an order with the id PR-90377. Could you check the ... 3 x admits it I could not find an order with the id A1009. Could you check the num... 1 x HIDES IT Order A1004 (coffee grinder) has shipped with Parcelo and should arr...
Three of the ten requests with a tool error recovered on the retry, six admitted the failure, and one ended with “should arrive soon”: a claim with nothing behind it, after the carrier never answered. One run would not tell you whether that is a fluke or a pattern; a query over many traces (or many more trials, as in Notebook 10b) does. Turning observations like this into graders, and graders into a release gate, is the job of Notebook 10b.
Try this
- Add
"Never guess: if a tool fails, say so."to the system prompt and re-run the last two cells. (The offline model has a rule that reads it.) What changes in the answers, and what does not change in the latency?- Make the carrier timeout 3 s instead of 10 s in
TOOL_LATENCY. How do p50 and p95 move, and why does p50 barely change?- Add a
cost_usdbudget: subclassTracedAgentsostepraises once the run’s model spans add up to more than USD 0.001. Where in the tree does the error appear?- With a live model, compare
usage_estimatedspans against the provider’s counts: how far off is the four-bytes-per-token estimate?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 97 (fake: 97) | ≈ 39,807 | ≈ 1,206 | ≈ USD 0.0446 (reference price) |