Sub topic 8
Tracing LLM Calls: Inputs, Outputs, Tokens, and Latency
This chapter assumes you can read and write Python, have used an LLM API or SDK, and know what structured logging is. It also assumes you have seen the PromptVersion idea from the chapter on versioned artifacts. After this chapter you should be able to instrument a model call, choose which fields to record, and avoid the common mistakes in tracing.
Why LLM calls need their own tracing
In a classic MLOps service, a prediction is cheap and deterministic. You usually log the request ID, the model version, and the score. If a prediction is wrong, you can often replay the same features and get the same wrong answer.
An LLM call differs in four ways:
- Output is free text. You cannot judge a response from a single score, so you need the actual text to debug quality.
- Output varies between runs. Replaying an input may not reproduce the failure. The recorded trace may be the only evidence you have.
- Cost depends on size. Billing is per token, so token counts are a cost metric, not a nice-to-have.
- Latency depends on output length. A response with 600 output tokens takes much longer than one with 20, even on the same model.
A trace is the record of one request as it moves through your application. It is the raw material for the monitoring, cost, and debugging work covered in later chapters.
What to record for each call
The table lists a practical minimum for every model call.
| Field | Why it matters |
|---|---|
| `trace_id` | Joins this call to logs from other components and to user feedback. |
| `prompt_version` | Links a behavior change to the exact prompt, model, and settings. |
| `model` | Providers retire and update models. You need to know which one answered. |
| `latency_ms` | Total wall-clock time. This is what the user waits for. |
| `input_tokens`, `output_tokens` | The basis for cost and for spotting oversized prompts. |
| `status` | Separates successes from timeouts, rate limits, and provider errors. |
| `input`, `output` (when allowed) | Needed to diagnose quality problems. Subject to privacy rules. |
You can derive some fields later. Cost in currency is one: compute it from token counts and a price table, so a price change does not require rewriting old logs.
A minimal tracing wrapper
The wrapper below sits around any model call. It does not depend on a particular provider. You write a small adapter that returns a dict with text, input_tokens, and output_tokens.
import json
import time
import uuid
def traced_call(call_model, prompt_version, user_input, log):
"""call_model(prompt_version, user_input) must return a dict with
'text', 'input_tokens', and 'output_tokens' (an adapter you write)."""
start = time.perf_counter()
status = "ok"
result = {}
try:
result = call_model(prompt_version, user_input)
return result
except Exception:
status = "error"
raise
finally:
log(json.dumps({
"trace_id": str(uuid.uuid4()),
"prompt_version": prompt_version.version_id,
"model": prompt_version.model,
"latency_ms": round((time.perf_counter() - start) * 1000, 1),
"input_tokens": result.get("input_tokens"),
"output_tokens": result.get("output_tokens"),
"status": status,
}))Three design choices matter here.
- The log line is written in
finally. Failed calls are logged too. Errors and timeouts are often the calls you most need to see. - The original exception is re-raised. Tracing observes the call. It must not change how failures reach the caller.
- Token fields are
Noneon failure. A missing value is honest. A zero would pull your averages down and hide the failure in cost reports.
You can run the wrapper with a fake model. The stand-in version object below only has the two attributes the wrapper reads.
from dataclasses import dataclass
@dataclass(frozen=True)
class FakeVersion:
version_id: str
model: str
def fake_model(prompt_version, user_input):
return {"text": "Customer was charged twice.", "input_tokens": 21, "output_tokens": 6}
def broken_model(prompt_version, user_input):
raise TimeoutError("upstream timeout")
version = FakeVersion("a1b2c3d4e5f6", "example-model-2026-01")
lines = []
traced_call(fake_model, version, "duplicate charge", lines.append)
try:
traced_call(broken_model, version, "duplicate charge", lines.append)
except TimeoutError:
pass
for line in lines:
print(line)The first line shows "status": "ok" with token counts. The second shows "status": "error" with null token counts and a latency that still reflects how long the failed attempt took.
Traces for multi-step pipelines
Most real applications make more than one model call per request. A request may retrieve documents, build a prompt, call the model, validate the output, and sometimes retry. If each step logs on its own with no shared ID, you cannot reconstruct what happened.
The usual structure is a trace (the whole request) made of spans (timed steps). Each span has a name, a start time, a duration, and a parent. The trace_id is shared by every span in the request.
The wrapper above produces one flat record per call. To move toward spans, generate the trace_id once at the start of the request and pass it into every step. Many teams then adopt a tracing library or the OpenTelemetry standard rather than writing this by hand. The field names above still apply.
Measuring latency correctly
A single latency_ms number hides where the time went. Consider recording these separately:
- Retrieval time, if you assemble context from a search or database.
- Time to first token, for streamed responses. This is what the user perceives as responsiveness.
- Total generation time, which grows with output length.
- Retry and queue time, when your client waits after a rate limit.
When you stream, the wrapper above would stop its clock when the stream object is returned, not when the last chunk arrives. That gives a latency near zero. For streaming, start the timer before the request and stop it when the stream is fully consumed. Record the time of the first chunk separately.
Report latency as percentiles (p50, p95, p99), not averages. LLM latency has a long tail, and one slow generation can hide behind a healthy mean.
Token counts: source and accuracy
Use the counts the provider returns in its response. These are what you are billed for. Counting tokens yourself with a local tokenizer is useful for estimating a prompt before sending it, but it can differ from the billed number because of special tokens, message formatting, and tokenizer differences between model versions.
Record input and output tokens separately. Output tokens are usually priced higher than input tokens, and they drive latency. A single combined total makes it impossible to tell whether a cost increase came from longer prompts, for example more retrieved context, or from longer answers.
Common errors
- Logging only successes. Your error rate then looks like zero. Log in
finallyor an equivalent. - Missing the prompt version. Without it you can see that quality dropped on Tuesday but not which change caused it. Always record the version ID from your versioned artifact.
- Recording zero for unknown tokens. Use null. Zero is a real value.
- Timing only the final attempt. If your client retries internally, users wait for all attempts. Record the total and the number of attempts.
- Unbounded log fields. Storing full prompts with long retrieved context on every call can make logs larger than the model bills. Store full text for a sample, or store a hash and a pointer to the text.
- Treating the trace as a replay. Because output is non-deterministic, rerunning the stored input may give a different answer. Store the output you actually returned.
Sampling and retention
Metrics are cheap and should cover every call. Full content is expensive and sensitive, so it is usually sampled. A common policy:
- Record the metric fields for 100% of calls.
- Record full input and output for a small random sample, for example 1–5%.
- Record full input and output for every call with
statusother thanok, for every call a user flagged, and for every call that failed an automated output check.
This keeps storage manageable and still gives you the cases you most need when something goes wrong.
Using traces
Once calls are traced, several questions become simple queries:
- Which prompt version has the highest error rate or p95 latency?
- Did the average input size grow after the retrieval change?
- Which requests cost the most, and why?
- Did a model identifier change appear in
modelwithout a matching deploy?
The next chapters build on these records. Monitoring watches them for drift. Cost and latency management uses the token and timing fields. Evaluation can reuse logged inputs as candidates for new golden cases.
Exercise
A team's dashboard shows an average latency of 1.8 seconds, yet users complain that the app feels slow, and the average cost per call looks lower than the provider invoice suggests. Name one change to the trace fields or the way they are aggregated that addresses each symptom.
Show answer
For the latency complaint, report percentiles (p95 and p99) instead of the mean, because a long tail of slow generations is hidden by the average. For streamed responses, also record time to first token, since that is what users perceive. For the cost gap, check that failed calls and retried attempts are logged with their token counts (not dropped or recorded as zero), and that input and output tokens come from the provider's response and are priced separately, because output tokens usually cost more.
Exercise
Why does traced_call write its log line in a finally block and set the token fields to None when the call fails?
Show answer
The finally block runs whether the call succeeds or raises, so errors and timeouts are logged, not silently missing from the data. Using None for tokens on failure records that the value is unknown. A zero would be treated as a real measurement and would distort average token and cost figures.