Sub topic 12
Reading Usage Data and Attributing Spend
This chapter assumes you know how input, output and cached tokens are priced, and why an agent loop resends its context on every turn. It also assumes you can read short Python and JSON. It covers how to turn the usage numbers an API returns into a spend report that says where the money went.
What a usage record contains
Every response from a model API includes a usage object, which holds the token counts the provider will bill for that call. These counts are the ground truth for spend. A count you estimate yourself with a tokenizer can differ from the billed count, because the provider adds formatting tokens, tool definitions and hidden prompt text.
Providers name the fields differently, and the differences change the arithmetic. Two common shapes:
| Concept | Style A fields | Style B fields |
|---|---|---|
| Uncached input | `input_tokens` (excludes cache reads and writes) | `prompt_tokens` (includes cached tokens) |
| Cache read | `cache_read_input_tokens` | `prompt_tokens_details.cached_tokens` |
| Cache write | `cache_creation_input_tokens` | usually not reported separately |
| Output | `output_tokens` | `completion_tokens` |
Check your provider's documentation before trusting these names. They illustrate the pattern and may not match the current API.
The important gotcha is whether the input count already includes cached tokens. If it does and you add the cache-read count on top, you count those tokens twice. If it does not and you subtract the cache-read count, you undercount. The first step of any usage pipeline is to normalize each provider's shape into one internal shape with four disjoint buckets: uncached input, cache read, cache write and output.
Reasoning (thinking) tokens usually need no bucket of their own for billing. Providers typically bill them at the output rate and fold them into the output count, and some also report them as a sub-count. Keep that sub-count if it is available, because it explains why output sometimes far exceeds the visible reply.
From response to report
The pipeline has five steps. The step that is easiest to skip is tagging, and tagging is what makes attribution possible.
Tags are the labels you attach to each call at the moment you make it. Useful ones for a coding agent:
- Session or task ID: groups every call that belongs to one job.
- Step kind: plan, edit, run tests, summarize tool output. These match the routing keys from the routing chapter, so spend and routing line up.
- Model name: needed because prices differ by model.
- Agent or subagent name: shows whether delegated work is cheap or expensive.
- Turn number: lets you plot how per-call cost grows over a session.
You cannot recover tags later from the invoice, which only shows totals per model and day. Put a thin wrapper around your client call that writes one log line per response, including calls that fail after the provider has started processing and calls inside retries.
A working report
The code below normalizes two usage shapes, prices each record with four rates, and aggregates by any tag. The prices are placeholders. Use your provider's current price list, and keep one price table per model.
from collections import defaultdict
# Placeholder prices in USD per million tokens, not real rates.
PRICE = {"input": 3.0, "cache_read": 0.30, "cache_write": 3.75, "output": 15.0}
FIELDS = ("input", "cache_read", "cache_write", "output")
def normalize(raw):
"""Map a provider usage object to four disjoint token buckets."""
if "prompt_tokens" in raw: # style B: prompt_tokens includes cached tokens
details = raw.get("prompt_tokens_details") or {}
cached = details.get("cached_tokens", 0)
return {
"input": raw["prompt_tokens"] - cached,
"cache_read": cached,
"cache_write": 0,
"output": raw["completion_tokens"],
}
return { # style A: input_tokens excludes cache reads and writes
"input": raw["input_tokens"],
"cache_read": raw.get("cache_read_input_tokens", 0),
"cache_write": raw.get("cache_creation_input_tokens", 0),
"output": raw["output_tokens"],
}
def cost_usd(u, price):
return sum(u[f] * price[f] for f in FIELDS) / 1_000_000
def summarize(records, key):
groups = defaultdict(lambda: {**dict.fromkeys(FIELDS, 0), "cost": 0.0, "calls": 0})
for r in records:
u = normalize(r["usage"])
g = groups[r[key]]
for f in FIELDS:
g[f] += u[f]
g["cost"] += cost_usd(u, PRICE)
g["calls"] += 1
return groups
def hit_rate(g):
"""Share of input tokens that were read from cache."""
total = g["input"] + g["cache_read"] + g["cache_write"]
return g["cache_read"] / total if total else 0.0
RECORDS = [
{"session": "s1", "step_kind": "plan",
"usage": {"input_tokens": 2000, "cache_creation_input_tokens": 8000,
"cache_read_input_tokens": 0, "output_tokens": 1500}},
{"session": "s1", "step_kind": "edit",
"usage": {"input_tokens": 1500, "cache_creation_input_tokens": 2000,
"cache_read_input_tokens": 8000, "output_tokens": 800}},
{"session": "s1", "step_kind": "run_tests",
"usage": {"input_tokens": 3000, "cache_read_input_tokens": 10000,
"output_tokens": 200}},
{"session": "s2", "step_kind": "edit",
"usage": {"prompt_tokens": 4000, "completion_tokens": 2500,
"prompt_tokens_details": {"cached_tokens": 0}}},
]
for key in ("session", "step_kind"):
for name, g in sorted(summarize(RECORDS, key).items()):
print(f"{key}={name} calls={g['calls']} "
f"cost=${g['cost']:.4f} hit_rate={hit_rate(g):.2f}")Running it prints:
session=s1 calls=3 cost=$0.0999 hit_rate=0.52
session=s2 calls=1 cost=$0.0495 hit_rate=0.00
step_kind=edit calls=2 cost=$0.0759 hit_rate=0.52
step_kind=plan calls=1 cost=$0.0585 hit_rate=0.00
step_kind=run_tests calls=1 cost=$0.0150 hit_rate=0.77Both groupings add up to the same total, $0.1494. That is a useful check: any breakdown you build should sum to the same number, and a mismatch means a record was dropped or counted twice.
Reading the numbers
The report answers different questions depending on the grouping.
- By session: which jobs are expensive. A few outliers usually account for most spend, so look at the top of the list before the average.
- By step kind: where in the loop the money goes. In the example, the plan step costs the most per call because it writes a cache and produces many output tokens. The test step is cheap per call because it reads a cached prefix and writes little.
- By model: whether a routing change moved work to cheaper tiers. Compare token counts too, not only dollars, so a price change is not mistaken for a behavior change.
Three derived measures are worth tracking over time:
- Cache hit rate:
cache_read / (input + cache_read + cache_write). A low rate in a long session suggests the prefix is changing between turns, for example by a timestamp or reordered tool list in the system prompt. - Output share of cost: output tokens times the output rate, divided by total cost. A high share points at reasoning tokens or verbose replies, not at context size.
- Input tokens per turn, plotted against turn number. A steep rising line means tool output and history are accumulating. A sawtooth line means compaction or a subagent reset is working.
Attribution problems
Several situations produce a report that looks right but is wrong.
- Retries and failed calls. If your wrapper logs only successful responses, the spend from timeouts and retried calls is missing. Log every attempt, with an attempt number tag.
- Subagent calls. A subagent makes its own API calls. If it uses a separate client, its usage never reaches the parent's log unless you pass the session ID down. Tag the subagent name and keep the parent's session ID so the cost rolls up to the right task.
- Streaming. With streamed responses, the final token counts often arrive in the last event, and some APIs require an option to include them. If a stream is cancelled early, you may have no usage object. Record the call anyway, flagged as incomplete, and reconcile later.
- Price changes. Store the token counts, not only the computed dollars, and price at report time with a dated price table. Then a rate change does not corrupt history.
- Shared prefixes. When many sessions read one cached prefix, one session pays the write and the others get cheap reads. Per-session cost then depends on which session ran first. For fair comparisons, look at totals across many sessions, not single ones.
Reconciling with the bill
Your own log is detailed but can be incomplete. The provider's invoice or usage dashboard is complete but coarse. Compare them regularly, for example once a day for each model. A gap of a few percent can come from rounding or the time zone used to cut days. A larger gap means a code path calls the API without going through your wrapper, such as a script, a test harness or an editor plugin using the same key. Using a separate API key per tool or team makes those gaps easy to find, because the provider's dashboard can then split spend by key.
What to do with the report
Reports matter when they change a decision. Use them to find the top cost drivers, then pick the matching technique from earlier in the tutorial:
| Symptom in the report | Likely cause | Technique |
|---|---|---|
| Input tokens per turn climb steadily | Large tool output and history | Scoped reads, truncation, compaction |
| Low cache hit rate | Unstable prefix | Keep the prefix fixed and append only |
| High output share | Reasoning or long replies | Lower thinking effort, shorter answers |
| One step kind dominates | Wrong model for that step | Route it to a cheaper tier |
The next chapters build on this data. Cost per resolved task needs the per-session totals from this chapter, divided by the number of tasks that were actually solved. Budgets and guardrails need the same numbers computed live, so a loop can stop itself when it passes a limit.
Exercise
A call returns style A usage with inputtokens 1000, cachereadinputtokens 9000, no cache creation, and output_tokens 500. Using the placeholder prices in this chapter (input 3.0, cache read 0.30, cache write 3.75, output 15.0 USD per million tokens), what does the call cost, and what is its cache hit rate?
Show answer
Input: 1000 × 3.0 = 3,000. Cache read: 9000 × 0.30 = 2,700. Output: 500 × 15.0 = 7,500. The sum is 13,200, divided by 1,000,000 gives $0.0132. The hit rate is 9000 / (1000 + 9000 + 0) = 0.90.
Exercise
Your daily report says total spend from your log is 40 percent lower than the provider's invoice. Name two likely causes and one way to find out which applies.
Show answer
Likely causes: calls that bypass the logging wrapper (scripts, plugins, or subagents using a separate client), and failed or retried attempts that were never logged. To find out, use a separate API key for each tool or team and compare the provider's per-key spend with your log for the same key.