Sub topic 9
Recording token usage
This chapter assumes you can already wrap a model call in a client span, as in the previous chapter, and that you know what a span attribute is.
Why tokens belong on spans
Providers bill by tokens, and token counts also affect latency and context limits. If the counts sit on the same span as the call, you can answer questions like "which step of this run was expensive?" from one trace.
The GenAI semantic conventions define two attributes for this:
| Attribute | Meaning |
|---|---|
| `gen_ai.usage.input_tokens` | Tokens in the prompt sent to the model |
| `gen_ai.usage.output_tokens` | Tokens the model generated |
Both are integers. Set them on the model-call span, not on the agent span.
Record what the provider reports
Take the numbers from the response's usage field. Don't estimate them with a local tokenizer unless the provider gives you nothing, because tokenizer counts often differ from billed counts.
from opentelemetry import trace
from opentelemetry.trace import SpanKind
tracer = trace.get_tracer("support_agent")
def record_usage(span, usage):
"""Set token attributes only for values the provider returned."""
if usage is None:
return
if usage.get("input_tokens") is not None:
span.set_attribute("gen_ai.usage.input_tokens", usage["input_tokens"])
if usage.get("output_tokens") is not None:
span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"])
def traced_chat(messages, 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)
result = {"text": "Hello!", "usage": {"input_tokens": 12, "output_tokens": 3}}
record_usage(span, result["usage"])
return result["text"]The helper skips missing values instead of writing 0. A zero looks like a real measurement and pulls averages down. A missing attribute is honestly unknown.
Common pitfalls
- Streaming. Many APIs send usage only in the final chunk. Keep the span open until the stream ends, then call
record_usage. If the consumer abandons the stream, the counts may never arrive. - Retries. Give each attempt its own model-call span. Every attempt consumes tokens, so one span per attempt keeps the totals honest.
- Double counting. Don't copy a child's tokens onto the parent agent span. Sum child spans in your backend instead.
- Cached or reasoning tokens. Providers report these differently. Check whether your provider includes them in the input and output totals before building cost dashboards.
Checking the result
Run the Collector from the earlier chapter with the debug exporter, call traced_chat, and look for gen_ai.usage.input_tokens: 12 in the span output. If the attribute is missing, check that record_usage runs before the with block exits.
Exercise
A model call fails and your code retries it twice before succeeding. Each attempt reports usage. Where should the token counts go, and why?
Show answer
Put each attempt's counts on its own model-call span, so three spans in total. Every attempt consumed tokens, so summing across the spans gives the true usage. Putting only the final attempt's counts on one span would hide the cost of the failed attempts.