Sub topic 8
Reading usage from API responses
This chapter assumes you can read Python, have called a chat or completion API before, and know the earlier chapters' terms: input tokens, output tokens, context window, and per-million-token pricing. Here you will learn where the real token counts appear in an API response, how the field names differ between providers, and how to turn them into a reliable record of what you spent.
Why the response is the source of truth
A tokenizer library gives you an estimate before a call. The API gives you the number you are billed for after the call. The two often differ, for these reasons:
- Chat requests add formatting tokens around each message (role markers, separators) that your own count of the raw text does not include.
- Tool definitions, images, and structured-output schemas count as input but are easy to leave out of a local estimate.
- Some models produce hidden output, such as reasoning, that never appears in the text you receive.
- Your local tokenizer may not match the model's tokenizer.
So use a local count to decide whether a request is likely to fit, and use the usage data from the response for billing, logging, and budgeting.
What a usage object contains
Every major provider returns a small object with token counts. The names differ, but the core idea is the same: how many tokens went in, and how many came out.
| Concept | OpenAI Chat Completions | Anthropic Messages |
|---|---|---|
| Input tokens | `usage.prompt_tokens` | `usage.input_tokens` |
| Output tokens | `usage.completion_tokens` | `usage.output_tokens` |
| Total | `usage.total_tokens` | Not provided. Add input and output yourself. |
| Cached input read | `usage.prompt_tokens_details.cached_tokens` | `usage.cache_read_input_tokens` |
| Cache write | Not reported separately | `usage.cache_creation_input_tokens` |
| Reasoning tokens | `usage.completion_tokens_details.reasoning_tokens` | Included in `output_tokens`, not broken out |
| Why generation stopped | `choices[0].finish_reason` | `stop_reason` |
Field names change between API versions and between endpoints of the same provider. For example, OpenAI's newer Responses API uses input_tokens and output_tokens. Check the reference for the endpoint you call.
The table hides a difference that causes real billing errors. The two providers define "input" differently when caching is involved.
- OpenAI:
prompt_tokensis the full prompt. The cached tokens are a subset of it, socached_tokensis already counted inprompt_tokens. - Anthropic:
input_tokenscounts only the tokens that were not read from or written to the cache. The cache fields are separate, so the full prompt size isinput_tokens + cache_read_input_tokens + cache_creation_input_tokens.
If you add the cache fields to OpenAI's prompt_tokens, you double-count. If you ignore them for Anthropic, you under-count the prompt size.
Normalizing usage into one shape
When you use more than one provider, convert each response into a single internal format right at the boundary. The function below defines that format as non-overlapping buckets: fresh input, cached reads, cache writes, and output. Because the buckets do not overlap, you can multiply each one by its own price and add the results.
def normalize_usage(provider, usage):
"""Convert a provider's usage dict into non-overlapping buckets."""
if provider == "openai":
prompt_details = usage.get("prompt_tokens_details") or {}
output_details = usage.get("completion_tokens_details") or {}
cached = prompt_details.get("cached_tokens", 0)
return {
"input": usage["prompt_tokens"] - cached, # cached is a subset
"cached_read": cached,
"cache_write": 0,
"output": usage["completion_tokens"], # includes reasoning
"reasoning": output_details.get("reasoning_tokens", 0),
}
if provider == "anthropic":
return {
"input": usage["input_tokens"], # excludes cache fields
"cached_read": usage.get("cache_read_input_tokens") or 0,
"cache_write": usage.get("cache_creation_input_tokens") or 0,
"output": usage["output_tokens"],
"reasoning": 0, # not reported separately
}
raise ValueError(f"unknown provider: {provider}")
openai_usage = {
"prompt_tokens": 1200,
"completion_tokens": 450,
"total_tokens": 1650,
"prompt_tokens_details": {"cached_tokens": 1000},
"completion_tokens_details": {"reasoning_tokens": 200},
}
anthropic_usage = {
"input_tokens": 200,
"output_tokens": 300,
"cache_read_input_tokens": 1000,
"cache_creation_input_tokens": 0,
}
print(normalize_usage("openai", openai_usage))
print(normalize_usage("anthropic", anthropic_usage))Running it prints:
{'input': 200, 'cached_read': 1000, 'cache_write': 0, 'output': 450, 'reasoning': 200}
{'input': 200, 'cached_read': 1000, 'cache_write': 0, 'output': 300, 'reasoning': 0}Both calls have the same fresh and cached input, even though the providers report them differently.
The reasoning value is a subset of output, not an addition to it. Reasoning tokens are billed at the output rate and are already inside completion_tokens. Keep reasoning as an informational field. Do not add it to output when computing cost.
The or 0 on the Anthropic cache fields matters. Some responses return null for a field that is not in use, and None + 5 raises a TypeError.
Keeping a running ledger
A single response tells you about one call. To understand a conversation or a day of traffic, add each normalized record to a running total. A Counter does this in a few lines.
from collections import Counter
ledger = Counter()
for provider, usage in [("openai", openai_usage), ("anthropic", anthropic_usage)]:
ledger.update(normalize_usage(provider, usage))
ledger["calls"] += 1
print(dict(ledger))This code reuses normalize_usage, openai_usage, and anthropic_usage from the previous example. The output is:
{'input': 400, 'cached_read': 2000, 'cache_write': 0, 'output': 750, 'reasoning': 200, 'calls': 2}In a real service, write one record per call to a log or database, with a timestamp, the model name, and a request identifier. Totals can be recomputed later, but you cannot reconstruct per-call numbers from a total.
Checking why generation stopped
The usage numbers tell you how much was produced. The stop reason tells you whether the answer is complete. Always read both together.
- OpenAI sets
finish_reasonto"stop"for a natural ending and"length"when the output hit the token limit. - Anthropic sets
stop_reasonto"end_turn"for a natural ending and"max_tokens"when the limit was reached.
A truncated answer is still billed in full. If output_tokens equals your max_tokens setting, treat the response as suspect. This is the common cause of JSON that stops mid-object. A small guard makes the check explicit:
def was_truncated(stop_reason):
return stop_reason in ("length", "max_tokens")
print(was_truncated("length")) # True
print(was_truncated("end_turn")) # FalseUsage in streaming responses
When you stream a response, the text arrives in many small chunks, and the usage data arrives differently from a normal call.
- OpenAI: usage is not sent by default when streaming. Set
stream_options={"include_usage": True}. The API then sends one extra final chunk with an emptychoiceslist and a populatedusagefield. Every earlier chunk hasusageset toNone. - Anthropic: the
message_startevent carries the input token counts. Themessage_deltaevent near the end carriesoutput_tokens, and that number is cumulative for the whole response, not a per-event increment. Take the last value rather than summing them.
This example captures usage from an OpenAI stream. It needs the openai package and an OPENAI_API_KEY environment variable.
from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Name three prime numbers."}],
stream=True,
stream_options={"include_usage": True},
)
usage = None
for chunk in stream:
if chunk.usage is not None: # only the final chunk has it
usage = chunk.usage
print(usage)If the connection drops or you stop reading early, you may never see the final usage chunk. The provider may still bill for the tokens it generated. For critical accounting, compare your logs against the provider's usage dashboard or usage export.
Comparing estimates with reported usage
A useful habit is to log both your local estimate and the reported input count for the same request, then watch the gap. A small, steady difference is normal and comes from message formatting overhead. A gap that suddenly grows tells you something changed, such as a long tool schema being attached or a different tokenizer being used by a new model version.
For budgeting, apply the gap as a margin instead of expecting an exact match. For fitting a request into the context window, use the safer direction: assume the real count is a little higher than your estimate.
Common errors
- Using
total_tokensfor cost. Input and output have different prices, so a total cannot be priced correctly. Price each bucket separately. - Double-counting cached tokens. This happens with OpenAI when you add
cached_tokenstoprompt_tokens, as described above. - Adding reasoning tokens on top of output. They are already inside the output count.
- Reading only the text. Without checking the stop reason, you can ship a truncated answer without noticing.
- Summing Anthropic streaming deltas. The output count in
message_deltais cumulative, so summing it overstates usage. - Forgetting the final streaming chunk. Code that reads
chunk.choices[0]on every chunk crashes on the last OpenAI chunk, becausechoicesis empty. - Assuming a missing field means zero. A provider or model that does not report a field is different from one that reports zero. Use
.get()with a default, and note which providers omit what.
Exercise
Exercise
An OpenAI response reports prompttokens = 3000, completiontokens = 800, cachedtokens = 2000, and reasoningtokens = 300. Using the buckets from normalize_usage, what are the fresh input, cached read, and output counts? If the prices are 3.00 dollars per million for fresh input, 0.30 dollars per million for cached reads, and 15.00 dollars per million for output (placeholder prices), what is the cost?
Show answer
Fresh input is 3000 - 2000 = 1000 tokens, cached read is 2000 tokens, and output is 800 tokens (the 300 reasoning tokens are already inside it, so they are not added again). Cost = (1000 x 3.00 + 2000 x 0.30 + 800 x 15.00) / 1,000,000 = (3000 + 600 + 12000) / 1,000,000 = 0.0156 dollars.
Exercise
A streaming call to an Anthropic model emits messagedelta events with outputtokens values of 12, 40, and 95 as the response grows. How many output tokens should you record, and why?
Show answer
Record 95. The value in message_delta is cumulative for the whole response, so the last value is the total. Summing 12 + 40 + 95 = 147 would overstate usage.