Sub topic 8
Tracing LLM Calls: Inputs, Outputs, Tokens, and Latency
Assume you know Python, can call an LLM through an SDK or HTTP API, and understand basic production logging. This chapter focuses on tracing one request from your application to the model and back.
A trace is a record of what happened during one request. For an LLM application, the trace should connect the user request, prompt version, model call, retrieved context, output, token counts, latency, and errors. Without this connection, a slow or poor response is difficult to explain.
What a trace should capture
A useful trace has a unique identifier, such as trace_id. Every log entry created while handling the request includes that identifier. A request that calls several models or tools can then be reconstructed from its related entries.
Record the following fields:
| Field | Why it matters |
|---|---|
| `trace_id` | Connects all events for one request |
| Prompt and prompt version | Shows what instructions the model received |
| Model identifier | Distinguishes model behavior and pricing |
| Input and output tokens | Measures usage and cost |
| Latency | Shows how long the call took |
| Status and error | Separates successful, failed, and timed-out calls |
Inputs and outputs require special care. They can contain names, account numbers, confidential documents, or other personal data. Store full content only when your retention and access rules allow it. Otherwise, store a redacted version, a hash, or metadata such as character count.
A trace is different from an application log. A log is usually one event. A trace is the connected history of a request, often containing several spans. A span is one timed operation, such as retrieval, an LLM call, or a tool invocation.
Instrument the model boundary
Put tracing at the boundary where your application calls the model. This ensures every caller uses the same fields. The adapter should return normalized data even if different providers use different response formats.
import json
import time
import uuid
def traced_call(call_model, prompt_version, user_input, log):
start = time.perf_counter()
trace_id = str(uuid.uuid4())
status = "ok"
result = {}
try:
result = call_model(prompt_version, user_input)
return result
except Exception as error:
status = "error"
log(json.dumps({
"trace_id": trace_id,
"status": status,
"error_type": type(error).__name__,
}))
raise
finally:
log(json.dumps({
"trace_id": trace_id,
"prompt_version": prompt_version,
"model": "example-model-2026-01",
"latency_ms": round((time.perf_counter() - start) * 1000, 1),
"input_tokens": result.get("input_tokens"),
"output_tokens": result.get("output_tokens"),
"status": status,
}))The call_model adapter should return a dictionary containing text, input_tokens, and output_tokens. Token counts should come from the provider when available. Character counts are only an approximation because tokenization depends on the model.
Latency should be measured with a monotonic clock, such as time.perf_counter(). Wall-clock time can move when the system clock is adjusted. For user experience, also measure total request latency, which includes retrieval and application work. Model latency alone does not explain the full response time.
Use traces to find failures
Compare traces by model, prompt version, endpoint, and outcome. A rise in output tokens may explain a cost increase. A rise in retrieval latency may explain a slower response even when the model is healthy. Missing token counts can indicate a provider or adapter change, not zero usage.
Trace sampling can reduce storage costs. Keep all errors and slow requests, while sampling ordinary successful requests. Preserve enough successful traces to detect quality and latency changes.
Exercise
A response becomes slower after a prompt change, but model latency is unchanged. Which trace fields should you inspect first?
Show answer
Inspect retrieval latency, prompt assembly time, input token count, and total request latency. The prompt may have caused more context to be retrieved or assembled before the model call.