Lesson 4 of 5 · Evaluating Agents
Agent Observability and Tracing
Make AI agents observable: traces and spans for every model and tool call, OpenTelemetry, dashboards, alerts, user feedback and privacy. With runnable Python.
- 7 min read
- Advanced
- Reviewed
- Explain traces and spans, and why agents need them
- Record the right details for model calls and tool calls
- Use a trace to find slow, costly and failing steps
- Monitor agents in production with metrics, alerts and feedback
- Keep traces useful without leaking private data
You can't fix what you can't see
A user reports: “The assistant took ages and then said it couldn't find my parcel.” Without a record of what the agent did, you're guessing. Was the model slow? Did a tool fail? Did it call the wrong tool? Observability means recording enough about every run that you can answer these questions afterwards.
A tiny tracer
Here's a minimal tracer that records spans as an agent answers a question. (The clock is simulated, so the demo prints the same numbers every time.)
import itertools
class Tracer:
"""Records spans: named, timed pieces of work, each with a parent, so one run becomes a tree."""
def __init__(self):
self.spans, self.stack, self.ids = [], [], itertools.count(1)
self.clock_ms = 0 # a pretend clock, so the demo prints the same every time
def span(self, name, kind, **attrs):
tracer = self
class Span:
def __enter__(self):
self.rec = {"id": next(tracer.ids), "name": name, "kind": kind, "attrs": attrs,
"parent": tracer.stack[-1]["id"] if tracer.stack else None,
"start": tracer.clock_ms, "error": None}
tracer.stack.append(self.rec)
tracer.spans.append(self.rec)
return self.rec
def __exit__(self, exc_type, exc, tb):
self.rec["ms"] = tracer.clock_ms - self.rec["start"]
if exc:
self.rec["error"] = str(exc)
tracer.stack.pop()
return True # record the error; the agent decides what to do next
return Span()
def work(self, ms):
self.clock_ms += ms # stands in for a real model or tool call taking time
tracer = Tracer()
with tracer.span("answer: 'Where is my order 881?'", "agent", user="u-17"):
with tracer.span("model: choose tool", "llm", input_tokens=1200, output_tokens=40):
tracer.work(900)
with tracer.span("tool: get_order(881)", "tool"):
tracer.work(120)
with tracer.span("tool: track_parcel(PX-55)", "tool"):
tracer.work(10_000)
raise TimeoutError("carrier API timed out")
with tracer.span("model: write reply", "llm", input_tokens=1650, output_tokens=120):
tracer.work(2_300)
children = {}
for s in tracer.spans:
children.setdefault(s["parent"], []).append(s)
def show(parent=None, depth=0):
for s in children.get(parent, []):
tokens = s["attrs"].get("input_tokens", 0) + s["attrs"].get("output_tokens", 0)
line = f"{' ' * depth}{s['name']:<{40 - 2 * depth}} {s['ms']:>6,} ms"
line += f" {tokens:,} tokens" if tokens else ""
line += f" ERROR: {s['error']}" if s["error"] else ""
print(line)
show(s["id"], depth + 1)
show()
slowest = max((s for s in tracer.spans if s["parent"]), key=lambda s: s["ms"])
print(f"\nSlowest step: {slowest['name']} ({slowest['ms'] / tracer.spans[0]['ms']:.0%} of the total time)")The tree answers the user's complaint at a glance. The carrier's tracking API took 10 seconds and timed out, 75% of the whole run. The agent recovered and replied, but the user waited over 13 seconds. The fix is a shorter timeout on that tool and a reply that says tracking is temporarily unavailable, not a better prompt.
What to record
For each span, record:
- Model calls: the model name, the prompt or a reference to it, the response, input and output tokens, time taken, and settings such as temperature.
- Tool calls: the tool name, arguments, result (or a summary if it's large), time taken and errors.
- The run: who it was for (a pseudonymous user ID), the agent and prompt version, total cost, the final outcome, and any user feedback.
Versions matter more than they seem. When success drops on Tuesday, you need to know which prompt, model and tool versions each run used.
From traces to monitoring
Individual traces explain single runs. Aggregated, they show how the agent is doing overall. A production dashboard for an agent usually tracks:
- Success signals: task completion, escalations, user ratings, and complaints.
- Cost: tokens and money per run, per user and per day.
- Speed: time per run, especially the slowest 5% of runs.
- Errors: tool failures, timeouts, invalid model outputs and step-limit stops.
- Behaviour: average steps per run, which tools are called, how often each guardrail fires.
Set alerts on sudden changes: cost per run doubling, a tool's error rate jumping, or escalations spiking after a release.
Closing the loop
Traces are also your best source of test cases. When a production run fails or a user complains, take its trace, turn the request into a test task with the correct outcome, and add it to your test suite (next lesson). Over time, your tests reflect what real users actually do, not what you imagined.
Sample some successful runs for review too. Agents can succeed in ways you don't want, like an unnecessary refund that the customer certainly won't complain about.
Common mistakes
Summarise a trace the way an observability dashboard does: total time and tokens for model calls versus tool calls.
# (kind, duration in ms, tokens) for each span of one agent run
spans = [("llm", 900, 1240), ("tool", 120, 0), ("tool", 10_000, 0), ("llm", 2_300, 1770)]
# Add up the time and tokens for each kind, then print one line per kind,
# in alphabetical order, in the form: <kind>: <ms> ms, <tokens> tokens
In the demo trace, what is the best first fix for the slow run?
Summary
- A trace records a whole agent run as a tree of spans: model calls, tool calls and steps, with timings, inputs, outputs and errors.
- Record tokens, arguments, errors and versions, so any run can be explained later.
- Use tracing tools and OpenTelemetry in production; aggregate traces into dashboards and alerts.
- Turn failed production runs into test cases, and review samples of successes too.
- Protect privacy: redact, restrict access and set retention limits.
Next: building an agent test suite.
Finished reading? Tick it off to track your progress.