Sub topic 12
Reading usage data and attributing spend
This chapter assumes you can read basic Python and JSON, and that you know how input, output and cached tokens are priced. It shows how to turn raw usage data into a spend report you can act on.
What usage data contains
Most provider APIs return a usage object with every response. Field names differ by provider, but the shape is similar. The example below uses placeholder names. Check your provider's docs for the real ones.
{
"model": "mid-model",
"usage": {
"input_tokens": 4200,
"cache_read_tokens": 35000,
"cache_write_tokens": 0,
"output_tokens": 850
}
}Two points are easy to miss. Some providers report cached tokens separately from input_tokens, and others include them in the input count. If you add them twice, your totals will be too high. Reasoning tokens are usually billed as output tokens, so check whether they are already inside output_tokens or listed on their own.
Log every call with labels
Provider totals tell you how much you spent. They do not tell you why. To attribute spend, write one log line per request. Include the token counts and labels that describe the work: a task ID, the step kind, and the model.
import json
import time
def log_request(path, task_id, step_kind, model, usage):
record = {
"ts": time.time(),
"task_id": task_id,
"step_kind": step_kind,
"model": model,
**usage,
}
with open(path, "a") as f:
f.write(json.dumps(record) + "\n")Each line is a JSON record, so the file is easy to load later. Log the raw token counts, not only the dollar cost. Prices change, and with raw counts you can recompute old spend at new rates.
Compute cost and group it
Next, read the log, price each record, and sum by a label. Prices below are placeholders, in USD per million tokens.
import json
from collections import defaultdict
PRICES = {
"mid-model": {"input": 3.0, "cache_read": 0.3, "output": 15.0},
}
def record_cost(r):
p = PRICES[r["model"]]
return (
r.get("input_tokens", 0) * p["input"]
+ r.get("cache_read_tokens", 0) * p["cache_read"]
+ r.get("output_tokens", 0) * p["output"]
) / 1_000_000
def spend_by(path, key):
totals = defaultdict(float)
with open(path) as f:
for line in f:
r = json.loads(line)
totals[r[key]] += record_cost(r)
return dict(totals)
# Example: spend_by("usage.jsonl", "step_kind")Run it once with task_id, once with step_kind, and once with model. Each grouping answers a different question.
| Group by | Question it answers |
|---|---|
| `task_id` | Which tasks are the most expensive? |
| `step_kind` | Which kind of step uses the most tokens? |
| `model` | How much goes to each tier? |
Reading the result
Look for skew before you look for averages. A few tasks that loop for many turns often account for most of the spend. Also check each step kind's share of input tokens against its share of cost. If one step kind sends large tool outputs, it will show up here.
Check the cache numbers too. Divide cache_read_tokens by all input-side tokens for a task. A low ratio on a long task suggests the prefix is changing between turns, which defeats caching.
Common errors
- Counting cached tokens twice, or not at all.
- Logging only the final request of a task and missing the earlier turns.
- Leaving out subagent calls, so their cost is attributed to no one.
- Using one price for all models.
Exercise
A task log shows 20 turns. Total spend is high, but grouping by step_kind shows no single step kind dominates. Which other grouping would you try first, and what would you look for?
Show answer
Group by task_id. Look for a small number of tasks with many turns or very large contexts, since a few long loops can drive most of the spend even when no step kind stands out. Then check the cache read ratio for those tasks.