Sub topic 8
Reading usage from API responses
This chapter assumes you can read basic Python and have called a chat API before. You should also know what input and output tokens are, and that providers bill for both.
Why read usage instead of estimating
A tokenizer library gives you a count before you send a request. The API gives you the count it actually billed, after the request runs. Billing uses the provider's number, so that is the number to log. Local estimates can drift because of message formatting overhead, tool definitions, images, or a tokenizer that doesn't match the model.
What a usage object contains
Every major provider returns a small usage object with each response. The core fields are the number of input tokens and the number of output tokens. The names differ by provider:
| Meaning | Common field names |
|---|---|
| Tokens you sent | `input_tokens`, `prompt_tokens` |
| Tokens the model produced | `output_tokens`, `completion_tokens` |
| Sum of both | `total_tokens` (not always present) |
Many APIs also report extra detail. Examples are tokens served from a prompt cache, tokens written to a cache, and reasoning tokens. These details are usually nested inside the usage object or listed as separate fields. Check your provider's reference for exact names, because they change between providers and versions.
Normalizing and costing usage
If you support more than one provider, convert each usage object to one shape as soon as it arrives. The example below uses two sample usage objects as plain dictionaries. It runs without network access. The prices are placeholders, not real rates.
def normalize_usage(usage):
"""Return (input_tokens, output_tokens) for either field naming."""
if "input_tokens" in usage:
return usage["input_tokens"], usage["output_tokens"]
return usage["prompt_tokens"], usage["completion_tokens"]
def estimate_cost(input_tokens, output_tokens,
input_price_per_million, output_price_per_million):
return (
input_tokens * input_price_per_million
+ output_tokens * output_price_per_million
) / 1_000_000
responses = [
{"input_tokens": 2000, "output_tokens": 500},
{"prompt_tokens": 2400, "completion_tokens": 350, "total_tokens": 2750},
]
total_in = total_out = 0
for usage in responses:
n_in, n_out = normalize_usage(usage)
total_in += n_in
total_out += n_out
print(f"{n_in} in, {n_out} out, ${estimate_cost(n_in, n_out, 3.0, 15.0):.5f}")
print(f"Total: {total_in} in, {total_out} out")
print(f"Total cost: ${estimate_cost(total_in, total_out, 3.0, 15.0):.5f}")The script prints a cost of $0.01350 for the first call and $0.01245 for the second. The total is 4400 input tokens, 850 output tokens, and $0.02595.
Common mistakes
- Using only the last response. In a multi-turn chat, each call reports only its own usage. Add up every call to get the cost of the conversation.
- Trusting the local count over the API count. Use the tokenizer to decide whether a request fits. Use the usage object to decide what you were billed.
- Ignoring the stop reason. A response that stopped because it hit the output limit has an output count equal to the limit you set. The text is probably cut off. Many APIs return a stop or finish reason next to the usage, so log it too.
- Missing streaming usage. When you stream a response, usage may arrive only in the final chunk, or only if you ask for it in the request options. If your totals are zero for streamed calls, check for this.
- Pricing cached tokens at the full rate. If the provider reports cached input tokens separately, they are usually billed at a different rate. Compute them as their own line.
What to log
For each call, record the model name, input tokens, output tokens, any cache or reasoning fields, the stop reason, and a request identifier. With these you can reconstruct the cost of any call later. You can also spot a prompt that has grown too large before it hits the context window.
Exercise
Your app logs usage for each call in a 5-turn chat. The usage objects show input tokens of 600, 1000, 1400, 1800, and 2200, and 200 output tokens each. Prices are $3 per million input tokens and $15 per million output tokens. What did the whole conversation cost?
Show answer
Total input is 600 + 1000 + 1400 + 1800 + 2200 = 7000 tokens. Total output is 5 x 200 = 1000 tokens. Cost = (7000 x 3 + 1000 x 15) / 1,000,000 = (21,000 + 15,000) / 1,000,000 = $0.036. You must sum all five calls, because each usage object covers only its own call.