Lesson 7 of 8 · Real-World Use
Counting Tokens and Cost
Keep AI API bills predictable: read token usage, cost each request and feature, estimate before sending, and save with smaller models, caching and batching.
- 5 min read
- Beginner
- Reviewed
- How to record token usage and turn it into cost
- How to find which features drive your bill
- How to estimate cost before you build
- The main levers for lowering cost
Every response tells you what it cost
Each API response reports the input and output tokens it used, counted by the provider. That is exactly what you are billed for. Recording it on every call is the foundation of cost control.
The formula from earlier courses:
cost = input tokens × input price + output tokens × output price, with prices quoted per million tokens.
Find what drives the bill
The program below takes a day's usage log, recorded from real responses, and works out the cost per feature.
# Example prices in dollars per million tokens (check your provider's real prices)
prices = {
"large-model": {"input": 15.00, "output": 75.00},
"small-model": {"input": 1.00, "output": 5.00},
}
# Usage recorded from each API response during one day (made-up numbers)
log = [
{"feature": "chat", "model": "large-model", "input": 3200, "output": 450},
{"feature": "chat", "model": "large-model", "input": 5100, "output": 600},
{"feature": "tagging", "model": "small-model", "input": 800, "output": 5},
{"feature": "tagging", "model": "small-model", "input": 750, "output": 5},
{"feature": "summary", "model": "small-model", "input": 12000, "output": 300},
]
def cost(entry):
price = prices[entry["model"]]
return (entry["input"] * price["input"] + entry["output"] * price["output"]) / 1_000_000
by_feature = {}
for entry in log:
by_feature[entry["feature"]] = by_feature.get(entry["feature"], 0) + cost(entry)
total = sum(by_feature.values())
for feature in by_feature:
share = by_feature[feature] / total
print(f"{feature:8} ${by_feature[feature]:.4f} ({share:.0%} of the bill)")
print(f"{'total':8} ${total:.4f}")Tagging is many requests but almost free: a small model, tiny outputs. Chat uses the large model with long histories and is over 90% of the bill. That is where to look for savings. Without per-feature logging, you would only see one total.
Levers for lowering cost
| Lever | How | Typical effect |
|---|---|---|
| Smaller model | Use the cheapest model that passes your tests; route only hard requests to a big one | Often the biggest saving |
| Shorter input | Trim history, summarise old turns, retrieve only relevant document chunks, cut long instructions | Large when histories or documents are long |
| Shorter output | Ask for concise answers; set max tokens | Output tokens cost several times more |
| Prompt caching | Put a long, unchanging prefix first so repeated requests reuse it at a discount | Big savings for repeated system prompts or documents |
| Batch processing | Send non-urgent jobs through a batch endpoint, answered within hours | Often around half price |
| Avoid repeats | Store answers to identical questions and reuse them | Saves whole calls |
Common mistakes
Check a week of API spending against a daily budget, as an alert system would.
daily_costs = [4.20, 3.85, 5.10, 4.75, 12.40] # dollars spent on each of 5 days daily_budget = 6.00 # Print every day that went over budget, numbered from 1, like: # Day 5: $12.40 (over budget) # Then print the total, like: Total: $30.30
Your daily usage log shows one feature uses a large model with long chat histories and is 90% of the bill. What is a sensible first step?
Summary
- Every response reports usage; log it with the feature, model and user on every call.
- Cost = input tokens × input price + output tokens × output price (per million).
- Estimate costs before building, using realistic conversation lengths.
- Main levers: smaller models, shorter input and output, prompt caching, batch processing and reusing answers.
- Compare models on cost per completed task, especially reasoning models.
Next: keeping conversation history in your own app.
Finished reading? Tick it off to track your progress.