What this is
What is observability?
Observability, for a program built on an AI language model, means recording every run in enough detail to replay it. The record of one run is a trace: a tree of timed steps, one for each call to the language model and each tool it used, with what went in and what came out. When the program gives a wrong answer, the trace shows which step went wrong, and so whether the fix belongs in the prompt, in a tool or in the documents it searched. Standard names for the steps and their fields let the same traces flow into the monitoring tools a team already runs.
Why it matters: You need it from the first day real people use the system, when a user reports a wrong answer from yesterday and the only evidence is the answer itself. The other sign is a bill you cannot explain, which only a record of every call to the language model can break down.
At a glance
Key takeaways
- A trace records one agent run as a tree of spans: the task at the root, then each model call, tool call and retrieval, with inputs, outputs, tokens, latency, cost, and model and prompt versions.
- Name the attributes with the OpenTelemetry GenAI conventions, and the traces flow into existing monitoring or LLM tracing tools without a converter for each.
- To debug a run, find its first error span. The fix may belong in a tool or in retrieval rather than the prompt.
- Store user feedback against the trace id, so a failure in production becomes a test: failure → trace → golden case → fix → CI → deploy.
How it works, from scratch
An aeroplane's flight recorder writes down every control input, every
instrument reading and every radio call, each stamped with the time. When
something goes wrong, investigators replay the flight instead of guessing.
A trace does the same for one run of an agent. The agent traced here
is a small support agent built on the tool-calling loop (see
The agent loop): it answers questions about orders with one
tool, lookup_order. Its model is scripted and its clock is fake, with a
model call taking 400 ms and a tool call 100 ms, so every trace below is
the same on every run.
Chapter 1
Spans: the steps of a run, as a tree
Each step of a run is a span: a named, timed unit of work with key-value attributes (model name, tokens, tool name and so on), a status (ok or error) and a parent. The top span is the whole task, and everything the agent does sits under it. All the spans of one run share a trace id, so they can be gathered back together.
The question "Where is order A100?" produces this trace:
invoke_agent support-agent 900 ms [ok]
├─ chat scripted-large 400 ms [ok] in=68 out=24 tokens
├─ execute_tool lookup_order 100 ms [ok]
└─ chat scripted-large 400 ms [ok] in=127 out=14 tokens
The model asked for a tool (the first chat), the tool ran, and the model
answered (the second chat). The durations add up: 400 + 100 + 400 = 900
ms. The second model call reads more input tokens than the first because
the whole conversation, now including the tool's result, is sent again at
every step.
Figure 1 · Diagram
flowchart TD R["invoke_agent support-agent<br/>trace id tr-0001, 900 ms"] --> C1["chat: model call 1<br/>400 ms, 68 in / 24 out"] R --> T1["execute_tool lookup_order<br/>100 ms, args: A100"] R --> C2["chat: model call 2<br/>400 ms, 127 in / 14 out"]
In code: Span holds one step, walk visits a tree parents first in
time order, and render prints the text tree above. View source
Chapter 2
Recording spans as the agent runs
A tracer builds the tree while the agent runs. Before each model or
tool call the loop opens a span; after it, the loop closes the span and
records what came back, such as the token counts, the model's name and why
it stopped. That is all instrumentation means. In Python it is a
with tracer.span(...): block, and an exception raised inside the block
marks the span as an error by itself.
Figure 2 · Diagram
sequenceDiagram participant U as User participant A as Agent loop participant T as Tracer participant M as Model participant K as Tool U->>A: Where is order A100? A->>T: open span invoke_agent A->>T: open span chat A->>M: messages + tools M-->>A: tool_use lookup_order(A100) A->>T: close span chat (tokens, model, finish reason) A->>T: open span execute_tool A->>K: lookup_order(A100) K-->>A: shipped A->>T: close span execute_tool A->>T: open span chat A->>M: messages + tool result M-->>A: "Order A100 has shipped." A->>T: close span chat A->>T: close span invoke_agent A-->>U: Order A100 has shipped.
invoke_agent span opens first and closes last, so it encloses the
other three. No arrow comes back from the tracer: it only records, and
never changes what the agent does.In code: Tracer.span opens a child of whichever span is open and
closes and times it when the block ends, and Span.fail marks an error
that didn't raise. FakeClock makes the timings repeat exactly, and
run_traced_agent is the loop in the diagram. View source
Chapter 3
Speaking a common language: OpenTelemetry
The step names in these trees, chat, execute_tool and invoke_agent,
come from OpenTelemetry (OTel), the open standard for traces, metrics
and logs. Its GenAI
semantic conventions fix the names of the attributes on model and agent
spans: gen_ai.request.model, gen_ai.usage.input_tokens,
gen_ai.tool.name and the rest. With these names, the same traces can go
into whatever monitoring the organisation already runs (Datadog, Grafana,
Honeycomb) or into tools built for language model traces (Langfuse,
LangSmith, Arize Phoenix, Braintrust), without a converter for each.
Attributes the standard doesn't cover, such as the prompt version and the
cost, get a prefix of your own; here it is app., as in
app.prompt.version and app.cost_usd.
| Attribute | Meaning | Example |
|---|---|---|
gen_ai.operation.name |
what kind of step | chat, execute_tool, invoke_agent |
gen_ai.request.model |
model asked for | claude-opus-5 |
gen_ai.usage.input_tokens / output_tokens |
tokens billed | 68 / 24 |
gen_ai.response.finish_reasons |
why the model stopped | ["tool_use"] |
gen_ai.tool.name, gen_ai.tool.call.id |
which tool, which call | lookup_order, toolu_1 |
app.prompt.version |
which prompt produced this call | support-v3 |
The spans reach those tools in two hops. The agent hands each finished span to an exporter, which sends it in the standard's own format, OTLP (the OpenTelemetry Protocol). A collector receives the spans and forwards them to every destination it is configured for. Changing vendors then means changing the collector's configuration, and the agent's code stays as it is.
Figure 3 · Diagram
flowchart LR A[Agent code<br/>+ tracer] -->|spans| X[Exporter] X -->|OTLP| C[Collector] C --> D[Existing monitoring<br/>Datadog, Grafana] C --> L[LLM tracing tools<br/>Langfuse, Phoenix] C --> W[Warehouse<br/>for evals and audits]
In code: to_otel turns a trace into OTLP-shaped span records. View source
Chapter 4
Debugging a failure from its trace
Like a flight recorder, a trace is read after something goes wrong. A user asks "Where is order A-100?", with a hyphen, and the agent answers "I couldn't find order A-100." From the answer alone, the order might not exist. The trace shows what happened in one line:
invoke_agent support-agent 900 ms [ok]
├─ chat scripted-large 400 ms [ok] in=68 out=24 tokens
├─ execute_tool lookup_order 100 ms [error] unknown order id A-100
└─ chat scripted-large 400 ms [ok] in=135 out=15 tokens
The model passed the id on as the user typed it, and the tool doesn't strip hyphens. To find this line in a bigger tree, walk the spans in time order and stop at the first one marked as an error. The fix belongs in the tool: normalise the id, or return an error the model can act on, such as "ids look like A100". A rewritten prompt would leave the bug where it is.
In code: first_error walks the tree and returns the first span marked
as an error. View source
Where the time and the tokens go
A trace also answers questions that arrive without a complaint: where a run spends its time, and what it is billed for. The next three charts come from the same agent asked about several orders at once.
Figure 4 · Chart
In a three-order run, four 400 ms model calls alternate back to back with three 100 ms tool calls, so model calls fill most of the 1,900 ms
Figure 5 · Chart
Input tokens climb with every model call, because each call resends the growing history
Figure 6 · Chart
In the six-order run, model calls take far more of the time than tool calls do
In code: trace_totals adds up a trace's duration, model and tool
calls, tokens, cost and errors, the numbers behind these charts. View source
Chapter 5
Closing the loop
Reading one trace fixes one failure. Keeping it fixed takes a link from the trace to the evaluation suite. When a user clicks thumbs-down, the feedback is stored against the trace id. An engineer opens that trace, finds what went wrong, and adds the run to the golden set, the fixed list of tasks with known good answers that every change is graded on (see Evaluation). Then the fix is made, the evaluation suite passes in CI (the checks that run automatically on every change), and the fix ships.
Figure 7 · Diagram
flowchart LR P[Production traffic] --> T[Traces] T --> F[Failures flagged<br/>by users or monitors] F --> G[Add to golden set] G --> X[Fix prompt, tools<br/>or retrieval] X --> E[Evals pass in CI] E --> D[Deploy] D --> P
In code: golden_case_from_trace turns a flagged trace into a new case
for the golden set. View source
Test yourself
4 questions
Answer each one out loud or on paper before you open it.
Question 1What would you record for every agent run?Think it through, then reveal
A tree of spans: the task at the root, and each model call, tool call and retrieval as children, with inputs and outputs (redacted of personal data), token counts, latency, cost, model id, prompt version, tool arguments and results, errors, and the user and tenant it ran for. That's enough to replay any decision and to aggregate cost and quality.
Question 2A user says the agent gave a wrong answer yesterday. How do you find out why?Think it through, then reveal
Look up the trace by conversation or user id and walk it: did retrieval return the right document, did the model pick the right tool with the right arguments, did a tool error, did a guardrail fire? The first error span or the first surprising output shows where the chain broke, and the trace becomes a new golden test case.
Question 3Why use OpenTelemetry instead of a vendor's SDK directly?Think it through, then reveal
Portability and fit: the organisation's existing monitoring already speaks OTel, the GenAI conventions give every tool the same attribute names, and changing vendors becomes a collector configuration change rather than a code change.
Question 4What should you be careful about when logging prompts and outputs?Think it through, then reveal
They contain user data. Redact personal data before export, restrict who can read traces, set retention limits, and keep tenants' traces separated.
Primary sources
The papers behind this lesson
Sigelman et al., Dapper, a Large-Scale Distributed Systems Tracing Infrastructure (Google technical report, 2010), Introduced the trace-and-span tree model with propagated trace ids that OpenTelemetry, and therefore agent tracing, is built on.
The paperResearcher's shelf
Further reading
- OpenTelemetry semantic conventions for generative AI: https://opentelemetry.io/docs/specs/semconv/gen-ai/
- OpenTelemetry concepts: traces and spans: https://opentelemetry.io/docs/concepts/signals/traces/
- Langfuse documentation: https://langfuse.com/docs
- Arize Phoenix documentation: https://arize.com/docs/phoenix
About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.