Sub topic 9
Recording token usage
Token counts are the main cost and latency signal for an LLM app. This chapter shows how to put them on spans reliably. It assumes you can already wrap a model call in a client span with GenAI attributes, as in the previous chapter.
Why tokens belong on the span
A provider bills by tokens, and latency grows with them. A trace that shows a slow chat span without its token counts leaves you guessing. Was the prompt huge, or was the provider slow?
With counts on each span, you can answer questions like these:
- Which step of the agent run consumed the most input tokens?
- Did the agent loop grow its context on every iteration?
- Which model or route is responsible for most of the spend?
The attributes
The GenAI semantic conventions define two core attributes for a model call span.
| Attribute | Meaning | Type |
|---|---|---|
| `gen_ai.usage.input_tokens` | Tokens in the prompt sent to the model | int |
| `gen_ai.usage.output_tokens` | Tokens the model generated | int |
Record them as integers on the span for the individual model call, not on the agent span. Each chat span then carries exactly what that request cost.
Where the numbers come from
Take counts from the provider's response, not from your own tokenizer. The provider's usage field is what gets billed. A local tokenizer can differ from it, because of special tokens, tool definitions, and image inputs.
A local estimate is only a fallback. If you use one, mark it with a custom attribute such as app.usage.estimated = True, so nobody mistakes it for a billed number.
The diagram shows the path the numbers take.
A defensive helper
Providers sometimes omit usage. Streaming responses may send it only in the last chunk, or only if you ask for it. A helper that skips missing values avoids writing misleading zeros.
from opentelemetry.trace import Span
def record_usage(span: Span, input_tokens, output_tokens) -> None:
"""Set GenAI usage attributes, skipping values the provider did not report."""
if input_tokens is not None:
span.set_attribute("gen_ai.usage.input_tokens", int(input_tokens))
if output_tokens is not None:
span.set_attribute("gen_ai.usage.output_tokens", int(output_tokens))A missing attribute and a value of 0 mean different things. Missing means "unknown". Zero means "the provider reported none". Backends that sum attributes treat the two differently, so keep them separate.
Streaming responses
With streaming, the full text and the usage arrive over time. The span must stay open until the stream ends, and you set the usage attributes at the end.
The example below consumes a simulated stream inside the span and returns the joined text. It also uses an in-memory exporter, so you can run it and see the attributes without a Collector.
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import SpanKind, Status, StatusCode
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support_agent")
def record_usage(span, input_tokens, output_tokens):
if input_tokens is not None:
span.set_attribute("gen_ai.usage.input_tokens", int(input_tokens))
if output_tokens is not None:
span.set_attribute("gen_ai.usage.output_tokens", int(output_tokens))
def fake_stream():
# Stand-in for a streaming client. Usage arrives only in the final chunk.
yield {"text": "Hel", "usage": None}
yield {"text": "lo!", "usage": None}
yield {"text": "", "usage": {"input_tokens": 12, "output_tokens": 3}}
def streamed_chat(model="example-model"):
with tracer.start_as_current_span(f"chat {model}", kind=SpanKind.CLIENT) as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.request.model", model)
parts, usage = [], None
try:
for chunk in fake_stream():
parts.append(chunk["text"])
if chunk["usage"]:
usage = chunk["usage"]
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, str(exc)))
raise
if usage:
record_usage(span, usage["input_tokens"], usage["output_tokens"])
return "".join(parts)
print(streamed_chat())
span = exporter.get_finished_spans()[0]
print(dict(span.attributes))Running it prints Hello! and a dictionary containing gen_ai.usage.input_tokens: 12 and gen_ai.usage.output_tokens: 3.
If the provider needs a flag to include usage in streams, such as a stream options setting on some chat APIs, turn it on. Otherwise your streamed calls will have no token data.
Retries and multi-step runs
Every attempt that reaches the model consumes tokens, including attempts that later fail validation or time out. Create one chat span per attempt and record usage on each. Then the trace sums to what you actually paid. If you put usage only on the successful attempt, the retries disappear from your cost picture.
For an agent run, resist copying totals onto the parent. The same tokens would then be counted twice when a backend sums over all spans in a trace. Two safe options:
- Leave totals to the backend. Sum the usage attributes over
chatspans. - Put the total on the agent span under a custom name, such as
app.usage.total_tokens. Then it cannot be mistaken for, or summed with, the standard per-call attributes.
This snippet shows the backend-style sum over finished spans. It continues from the previous example and runs the call again to produce a second span.
streamed_chat()
total_in = total_out = 0
for s in exporter.get_finished_spans():
if s.attributes.get("gen_ai.operation.name") == "chat":
total_in += s.attributes.get("gen_ai.usage.input_tokens", 0)
total_out += s.attributes.get("gen_ai.usage.output_tokens", 0)
print(total_in, total_out) # 24 6Edge cases
- Cached and reasoning tokens. Providers differ on whether cached prompt tokens or hidden reasoning tokens are inside the input and output totals or reported separately. Read the provider's documentation. Do not add a separate count to the total if the provider already includes it.
- Cost in dollars. Avoid storing a computed price on spans. Prices change, and a stored value cannot be corrected later. Store tokens and model name, and apply the price table in the backend or in a dashboard.
- Wrong model names. Some providers return a more specific model name than the one you requested. Set
gen_ai.response.modelfrom the response so usage is attributed to the model that ran. - Token counts of zero on errors. If a call fails before the provider answers, set no usage. Do not write
0.
Tokens as metrics
Spans are good for per-request detail, but sampling can drop them. If you need exact totals for billing or alerts, record the same numbers as a metric as well. The GenAI conventions define a histogram named gen_ai.client.token.usage, with a gen_ai.token.type attribute whose values are input and output. A later chapter covers metrics alongside traces.
Exercise
An agent run makes three model calls, and the second call is retried once after a timeout. You record usage on each of the four chat spans and also copy the sum onto the parent invoke_agent span using gen_ai.usage.input_tokens. Your backend then sums that attribute across the whole trace. What goes wrong, and how do you fix it?
Show answer
The tokens are counted twice, because the parent's total is added on top of the four child values. Fix it by leaving the standard attributes on the chat spans only. If you want a total on the parent, store it under a custom name such as app.usage.total_tokens. Keep the span for the timed-out attempt, and record usage on it only if the provider reported any.