AI ENGINEERING · LLMS IN PRODUCTION · OPERATIONS · 31 OF 35

LLM Observability: Tracing Prompts, Tools and Costs

Why logs alone cannot explain LLM failures, and how tracing fixes it: spans for retrieval, every model call and every tool call, each carrying inputs, outputs, tokens, latency and cost. A worked agent trace showing where the time and money went, the dashboards that matter, OpenTelemetry generative AI conventions, sampling and redaction, linking user feedback, turning bad traces into eval cases, and alerting on drift.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
1 / 19

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Tree of spans
  • tokens, latency, cost per span
  • p95
  • cost per user
  • sample + redact
  • feedback → evals
  • drift

Notes

Logs are not enough

In a normal API, a request works or throws, and a log line tells you which. An LLM app fails quietly. It returns a fluent, confident, wrong answer with status two hundred. And one request is really many steps: a retrieval, several model calls, a couple of tool calls. To debug it you need the exact prompt each call saw, what was retrieved, which tool failed and what it cost, all tied together in order.

What a log line misses
  • one request = many steps: retrieval, 3 model calls, 2 tool calls
  • failures are quiet: a wrong
  • answer with status 200
  • you need: the exact prompt, what was retrieved, which tool failed, tokens and cost

The idea

The fix is tracing, borrowed from microservices. A trace is the full story of one request, with one trace id. It is made of spans. A span is one step, with a name, a start time, a duration, a parent and a set of attributes. The root span is the whole request. Under it sit child spans for retrieval, each model call and each tool call. Parent links let you redraw it as a tree, or a timeline.

Trace and span
trace: one request, one id
span: one step inside it
  name, start, duration,
  parent span, attributes

request (root span)
├ retrieval
├ model call 1
├ tool: get_payments
└ model call 2

What goes on a span

What goes on a model call span? The model and its version, settings like temperature, and the prompt template version. The rendered input messages and the output, either text or a tool request. Input and output tokens, total latency, time to first token, the computed cost, and why generation stopped. Tool spans carry the arguments, the result and any error. Retrieval spans carry the query and the ids and scores of the chunks returned.

One model-call span
name: chat (model call 2)
  model + version, temperature
  prompt_version: billing-v7
  input: rendered messages
  output: text or tool request
  input_tokens: 9000
  output_tokens: 120
  latency 1.6 s, ttft 0.4 s
  cost_usd: 0.0192
  finish_reason: tool_use

An agent run

Let's trace one real run. A user asks why they were charged twice. The agent searches the help docs. The first model call asks for the user's payments, and the tool returns them. A second model call asks for refunds, and that tool runs. A third model call writes the answer. That is seven spans under one trace id: the root, one retrieval, three model calls and two tool calls.

Spans recorded
request        1 root span
 retrieval     1 span
 model calls   3 spans
 tool calls    2 spans

7 spans, 1 trace id,
every child points to
its parent

Where the time went

Here is the timeline. Retrieval, zero point three seconds. Model call one, one point eight. Get payments, zero point two. Model call two, one point six. Get refunds, three point one, because the billing API timed out at two seconds and was retried. Model call three, two point four. Nine point four seconds in all. The single slowest span was a tool, not the model. A log saying slow request would never show that.

Timeline, 9.4 s total
retrieval       0.3 s
model call 1    1.8 s
get_payments    0.2 s
model call 2    1.6 s
get_refunds     3.1 s  ← slowest
  timed out at 2 s, retried
model call 3    2.4 s

models  5.8 s  (~62%)
tools   3.3 s  (~35%)

Where the money went

Now the money, at illustrative prices of two dollars per million input tokens and ten per million output. The three calls read six thousand, nine thousand and ten and a half thousand tokens. Output is under seven hundred tokens in total. The run costs about five point eight cents, and eighty eight percent of that is input. Why? The get payments span shows nearly three thousand tokens of raw JSON. Trim that result and every later call gets cheaper.

Cost, illustrative prices
in $2 / M, out $10 / M tokens
call   in      out   cost
 1     6,000   150   $0.0135
 2     9,000   120   $0.0192
 3    10,500   400   $0.0250
total 25,500   670   $0.0577

input share: $0.051 ≈ 88%
get_payments returned
~2,850 tokens of raw JSON

Open standards

You do not need to invent field names. OpenTelemetry, the open standard for traces and metrics, has semantic conventions for generative AI. Model calls are spans named chat plus the model, tool calls are execute tool, agent runs are invoke agent, with standard attributes for the model and the token counts. Recording message content is opt in. Instrument once, export in the background, and use any backend. The conventions are still changing, so pin a version.

OTel GenAI conventions
span names
  chat {model}
  execute_tool {tool}
  invoke_agent {agent}
attributes
  gen_ai.operation.name
  gen_ai.request.model
  gen_ai.usage.input_tokens
  gen_ai.usage.output_tokens
still evolving: pin a version

Latency percentiles

Now the dashboards, built from the spans. First, latency percentiles. Across a thousand requests, the median, p fifty, is two point four seconds. The p ninety five is eight seconds, so one user in twenty waits longer than that. The p ninety nine is nineteen seconds. The mean of three point one looks fine and hides all of it. For streaming apps, also chart time to first token, which is what users feel, and split latency by step type.

Latency, 1,000 requests
mean   3.1 s   looks fine
p50    2.4 s   typical user
p95    8.0 s   1 in 20 waits
               longer
p99   19.0 s   1 in 100

also chart:
  time to first token
  latency per step type
  per model + prompt version

Cost and quality rates

Second, cost. Chart cost per request, including the p ninety five, because one runaway agent loop can cost a hundred times the median. Chart cost per user too. In one example the top one percent of users drove about thirty percent of spend: a power user, a script, or abuse. Third, the quiet failure rates: errors and timeouts, refusals, tool failures per tool, guardrail triggers per rule, and thumbs down. These move before users complain.

The other dashboards
  • cost per request: p50 and p95
  • cost per user per day e.g. top 1% of users drive ~30% of spend
  • error and timeout rate
  • refusal rate
  • tool failure rate, per tool
  • guardrail triggers, per rule
  • thumbs-down rate

Sampling

LLM traces are heavy, since one model call can carry tens of thousands of prompt tokens. So sample. Keep every interesting trace: errors, slow runs, refusals, guardrail hits and bad ratings. Keep a small share, say one to ten percent, of normal ones. You only know a trace is interesting once it ends, so decide then. That is called tail based sampling. But compute cost and latency metrics from every request, never from the sample.

What to keep
  • traces are heavy: each model
  • call can hold 10k+ tokens
  • keep 100%: errors, slow runs, refusals, guardrail hits, thumbs-down keep ~1–10% of normal runs
  • decide when the trace ends
  • (tail-based sampling)
  • metrics: from 100% of requests

Redact personal data

Prompts and outputs hold whatever users type: names, emails, addresses, sometimes card numbers. Your trace store is now a copy of all of it. Redact before export. Mask emails, phone numbers and card numbers with pattern and entity detectors, and replace user ids with a keyed hash. Keep full content in a separate store with short retention and tight access, and be able to delete one user's traces on request.

Before export
email    → <EMAIL>
phone    → <PHONE>
card     → <CARD>
user id  → keyed hash

content in a separate store
short retention (~30 days)
access control + audit log
delete one user on request

Traces become eval cases

This is the loop that makes traces pay off. Find bad traces through thumbs down, failed online judge checks or guardrail hits. Triage by reading the spans. Did retrieval miss the right document, did the prompt mislead, did a tool return garbage? Copy the input and its context into the eval set, write down what good looks like, fix it, and gate future releases on that case. Production failures become the regression tests from the previous episode.

From trace to test
  • 1 find: thumbs-down, judge fail, guardrail hit
  • 2 triage: which span broke? retrieval, prompt or tool
  • 3 copy input + context into the eval set
  • 4 write what good looks like
  • 5 fix it, then gate releases on the case

Alert on drift

Finally, alert on drift. Users ask about a new product, a provider updates a model behind the same name, a teammate edits a prompt. Watch inputs, like topic mix and length. Watch outputs, like refusal rate, answer length and tool use. Watch quality, with an online judge on a sample of traffic. Alert when one moves well away from its baseline, like refusals jumping from two to six percent, and mark every deploy on the charts.

Three kinds of drift
  • inputs: new topics, new languages, longer prompts
  • outputs: refusals 2% → 6%, answers 30% longer, fewer tool calls
  • quality: online judge pass rate drops 5 points
  • compare to a 7-day baseline
  • mark deploys on every chart

Common mistakes

Common mistakes. Logging the prompt template, not the rendered prompt the model actually read. No prompt or model version on spans, so you cannot tell which release broke things. Dropping tool arguments and errors. Computing cost from sampled traces, which undercounts it. Exporting spans synchronously, adding latency to every request. And keeping raw personal data forever.

Avoid these
  • logging the template, not the rendered prompt
  • no prompt or model version on spans
  • dropping tool args + errors
  • cost from sampled traces
  • exporting synchronously, slowing every request
  • raw PII kept forever

Numbers worth knowing

Some ballparks. A simple chat request makes three to ten spans, an agent task tens to a couple of hundred. A trace with full prompts weighs from about ten kilobytes to a few megabytes. With background export, tracing costs around a millisecond per span, tiny next to seconds of model time. Keep every flagged trace and one to ten percent of the rest. Output tokens usually cost three to five times input tokens.

Ballparks
spans per chat request   3–10
spans per agent task     10–200
trace size        10 KB–few MB
tracing overhead  ~ms per span
  with async export
sample normal runs      ~1–10%
keep flagged traces      100%
output vs input price  ~3–5×
content retention  weeks, not
                   years

Say it like this

How to say it. Every request becomes a trace, with spans for retrieval, each model call and each tool call. Each span records tokens, cost, latency and the prompt and model version, using the OpenTelemetry generative AI conventions. We keep every flagged trace and five percent of the rest, with personal data masked before export. We watch p ninety five latency, cost per user and refusal rates, alert on drift, and every bad trace becomes an eval case.

In the interview
  • "Every request is a trace, with spans for retrieval, each model and tool call: tokens, cost, latency and prompt version, on the OTel GenAI conventions. We keep flagged traces plus 5%, PII masked. Bad traces become eval cases."

Interview questions

Q1Why are logs alone not enough for an LLM application?

LLM apps fail quietly: a wrong answer still returns 200, and one request spans retrieval, several model calls and tool calls. You need those steps tied together under one id, with the exact inputs, outputs, tokens and timings of each, which is what a trace gives you.

Q2What is the difference between a trace and a span?

A trace is one end-to-end request, identified by a trace id. A span is one timed step inside it, with a name, start, duration, parent span and attributes. Parent links let you rebuild the request as a tree or a timeline.

Q3What would you record on a model-call span?

Model and version, sampling settings, prompt template version, the rendered input and the output, input and output token counts, latency and time to first token, computed cost, and the finish reason. Tool spans add arguments, results and errors; retrieval spans add the query and returned chunk ids and scores.

Q4An agent request is slow and expensive. How do you find out why?

Open its trace and read the timeline and token counts per span. Often a single slow tool or a retry dominates the time, and a tool that returns a large raw result inflates the input tokens of every later model call, which dominates the cost.

Q5Which dashboards matter most for an LLM feature in production?

Latency percentiles (p50, p95, p99) and time to first token; cost per request and per user; error, refusal and per-tool failure rates; guardrail trigger counts; and user feedback rates, all sliceable by model and prompt version.

Q6What are the OpenTelemetry GenAI semantic conventions?

Standard span names and attributes for generative AI operations, such as chat and execute_tool spans with gen_ai.request.model and gen_ai.usage.input_tokens and output_tokens. They let any OTel-compatible backend read your traces; message content capture is opt-in, and the conventions are still evolving.

Q7How do you handle sampling and personal data in LLM traces?

Use tail-based sampling: keep all errors, slow, refused, guardrail-flagged and badly rated traces plus a small share of normal ones, while computing metrics from all requests. Mask emails, phones and card numbers and hash user ids before export, keep content in a short-retention, access-controlled store, and support per-user deletion.

Q8How do traces connect to evals and drift detection?

Return the trace id with each answer so feedback attaches to the exact trace. Triage bad traces, copy their inputs and context into the eval set with the expected behaviour, and gate releases on them. Alert when input mix, output stats like refusal rate or online judge scores move away from a baseline.