What this is
What do cost and latency mean here?
Every request to an AI language model costs money and takes time. It is charged by the token, a piece of a word, for the text the language model reads and writes, and the wait for its answer is its latency. What decides the bill is the cost per successful task, with failed attempts and their clean-up counted in. A cheap language model that fails often, leaving a person to fix its work, can cost seven times as much per task as a dearer one that gets it right. The levers that lower the cost come in order of their risk, with the ones that cannot change the answers first.
Why it matters: The day the bill grows faster than the value, or before the first big customer arrives, the question is what one finished task costs, retries and human clean-up included. A monthly spend figure does not answer it.
At a glance
Key takeaways
- Measure cost per successful task, not per call. A cheap model that fails often can cost more per task than a dear one.
- First take the levers that cannot change quality: prompt caching, trimming tool output and chunks, and concise answers.
- Then route easy tasks to a small model, checked against an evaluation set.
- Batch work no one waits on, at about half price; run independent tool calls together; stream answers so the wait feels shorter.
- Cap steps and tokens per task and spend per customer; alert on sudden jumps in tokens per task.
- A semantic cache can answer a different question with confidence; measure its wrong-hit rate before using it.
How it works, from scratch
A language model's bill is the sum of its calls, and each call is priced by its tokens. Lowering the bill takes three steps: work out what one call costs, work out what a finished task costs once failures are counted, and then pull the levers that bring it down, starting with the ones that cannot change the answers.
All prices here are illustrative, chosen for round arithmetic: a "large" model at $5 per million input tokens and $25 per million output tokens, and a "small" one at $1 and $5. They show the shape of the trade-offs. For real numbers, check your provider's current price list.
Chapter 1
How a request is priced
A model charges per token (a word piece, about 4 characters of English), at one rate for the tokens you send (input) and a higher rate for the tokens it writes (output). Output costs more because the model writes it one token at a time (see Inference).
Take a large-model call with 10,000 input tokens and 500 output tokens. Input costs 10,000 × $5 / 1,000,000 = $0.05 and output costs 500 × $25 / 1,000,000 = $0.0125, so the call costs $0.0625. Now suppose 8,000 of those input tokens are a stable prefix, the same system prompt and tool definitions sent on every call. The prompt cache reuses the work already done on a prefix it has seen, and bills it here at 10% of the input price. Input becomes 8,000 × $0.50/M + 2,000 × $5/M = $0.014, and the call costs $0.0265, 58% less.
The formula and its symbols
Symbols
| Symbol | Meaning here | Worked example |
|---|---|---|
| input tokens sent | 10,000 | |
| input tokens served from the prompt cache | 8,000 | |
| output tokens generated | 500 | |
| price per million input / output tokens | $5, $25 | |
| cached-read price as a fraction of normal input price (Greek rho) | 0.1 | |
| prices are per million tokens |
In words: cached input at its discounted rate, plus the rest of the input at full rate, plus output at the output rate, all per million.
On the worked example: (8,000 × 0.1 × 5 + 2,000 × 5 + 500 × 25) / 10⁶ = (4,000 + 10,000 + 12,500) / 10⁶ = $0.0265.
In Python
n_in, c, n_out = 10_000, 8_000, 500
p_in, p_out, rho = 5, 25, 0.1
cost = (c * rho * p_in + (n_in - c) * p_in + n_out * p_out) / 10**6
round(cost, 4) # → 0.0265
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
Two things follow. An output token costs five times as much as an input token here, so asking for concise answers pays. A cached prefix is nearly free, so put the content that never changes at the start of the prompt (see Context engineering). Some providers charge a small premium the first time a prefix is written to the cache; the arithmetic here leaves it out.
In code: request_cost is the formula above. View source
Chapter 2
Cost per successful task
A call's price is not what a task costs: a failed attempt is paid for, and so is the retry or the person who fixes the result. Take a small model at $0.002 an attempt that succeeds 60% of the time and a large one at $0.010 that succeeds 95% of the time.
The formula and its symbols
Symbols
| Symbol | Meaning here | Small model | Large model |
|---|---|---|---|
| model cost of one attempt | $0.002 | $0.010 | |
| chance an attempt succeeds | 0.60 | 0.95 | |
| expected number of attempts until one succeeds | 1.67 | 1.05 | |
| cost of a person fixing one failure (illustrative: a few minutes of staff time) | $2.00 | $2.00 |
In words: if you can simply retry, you pay one attempt's cost for every expected attempt; if failures need a person, every task pays its attempt plus the chance of failure times the cost of the fix.
On the worked example: retrying, the small model costs 0.002 / 0.60 = $0.0033 per success and the large one 0.010 / 0.95 = $0.0105, so the small model is cheaper. With a person fixing failures, the small model costs 0.002 + 0.40 × 2.00 = $0.802 per task and the large one 0.010 + 0.05 × 2.00 = $0.110: the cheap model costs seven times as much.
In Python
def per_success(c, p):
# retry until it works
return c / p
def per_task(c, p, h=2.00):
# a person fixes each failure
return c + (1 - p) * h
round(per_success(0.002, 0.60), 4), round(per_success(0.010, 0.95), 4) # → (0.0033, 0.0105)
round(per_task(0.002, 0.60), 3), round(per_task(0.010, 0.95), 3) # → (0.802, 0.11)
# small vs. large, with cleanup
round(per_task(0.002, 0.60) / per_task(0.010, 0.95)) # → 7
Figure 1 · Chart
With automatic retries the small model is cheaper per success (0.3 vs 1.1 cents); if a person fixes each failure the large model wins, 11 cents vs 80
Every lever below is judged by this number. One that cuts the price of a call but raises the failure rate can make tasks dearer, so the levers that can change answers are checked against an evaluation set (see Evaluation).
In code: cost_per_success_with_retries is and
cost_per_success_with_cleanup is . View source
Chapter 3
Route each task to the cheapest model that can do it
The first lever is which model runs the task. Many requests are simple: classify a ticket, pull a date out of an email. A small model handles those at a fifth of the large model's price per token. A router sits in front of every request and sends the simple ones to the small model and the hard ones (planning, analysis, reasoning over several steps) to the large one.
The sample workload has 10 tasks, 7 simple and 3 complex (planning a migration). On the large model it costs $0.671. Routing the 7 simple tasks to the small model brings it to $0.314, 53% less, with the hard tasks still on the large model.
Figure 2 · Diagram
flowchart LR
T[Incoming task] --> R{Router<br/>rules or a small classifier}
R -->|classify, extract,<br/>format, short| S[Small, fast model]
R -->|plan, analyze,<br/>multi-step reasoning| L[Large model]
S --> O[Result]
L --> O
In code: route is the rule-based router, and workload_cost prices
the sample workload with any combination of levers switched on. View source
Chapter 4
Response caching and semantic caching
Routing makes a call cheaper; a cache skips it. An exact response cache stores each answer under its question and returns it when the same question comes again (ignoring case and spacing). It costs nothing and is never wrong, but it misses every rewording. A semantic cache also answers questions similar to a stored one. It turns each question into an embedding (a vector in which closeness means similar meaning, see Similarity) and returns the stored answer when the nearest stored question is close enough. But similar is not the same: "How many sick days do I get?" sits very close to "How many vacation days do I get?" and needs a different answer.
Here are four pairs scored by a small demonstration embedder:
| Stored question | New question | Similarity | Same intent? |
|---|---|---|---|
| How do I reset my password? | I forgot my password, how do I recover it? | 0.88 | yes |
| How many vacation days do I get? | How many sick days do I get? | 0.97 | no |
| Request a new laptop | Request a new monitor | 0.96 | no |
| What does ERR-4012 mean? | What does ERR-4013 mean? | 0.56 | no |
The two pairs that ask different things score higher than the genuine rewording, so a threshold high enough to reject them also rejects it. Two cheap guards catch some wrong matches before the threshold is tried: identifiers and numbers must match exactly (ERR-4012 is not ERR-4013), and negation must match ("cancel my order" is not "don't cancel my order"). Neither guard can tell sick days from vacation days, which share a topic and differ by one word.
Figure 3 · Diagram
flowchart TD
Q[New question] --> E{Exact match<br/>in response cache?}
E -->|yes| A1[Return stored answer]
E -->|no| V[Embed and find the<br/>nearest stored question]
V --> T{Similarity above<br/>threshold?}
T -->|no| M[Call the model]
T -->|yes| G{IDs, numbers and<br/>negation identical?<br/>entry not expired?}
G -->|no| M
G -->|yes| A2[Return stored answer]
M --> S[Store the new answer]
Figure 4 · Chart
On twelve labelled pairs, wrong hits stay at 40 to 60% from 0.4 through 0.95, above the paraphrase hit rate, and reach 0 only where paraphrase hits do too
Twelve hand-written pairs and a toy embedder are a demonstration, not a measurement of semantic caching in general. What they show is the check to run first: label pairs from your own traffic and measure the wrong-hit rate at the threshold you plan to use. Keep the cache to narrow traffic, such as a curated FAQ, with the guards and a TTL.
In code: ResponseCache is the exact cache and SemanticCache the
semantic one, guards and TTL included. semantic_cache_sweep draws the
figure from the labelled pairs in CACHE_PAIRS. View source
Chapter 5
Trim tokens
Caching and routing lower the price of tokens; trimming sends fewer of them. Cut tool results down to the fields the next step needs (see Context engineering), send the top few reranked chunks instead of dozens, remove repeated boilerplate from the system prompt, and ask for concise answers, since output is the expensive direction.
In code: workload_cost models trimming as cutting each task's tool
output to 500 tokens, and concise output as cutting long answers by a third. View source
Chapter 6
Run independent tool calls at the same time
Latency, the wait for an answer, has a lever of its own. An agent that calls three tools one after another waits for each in turn. When the calls do not depend on each other, start them together, and the wait is the time of the slowest: three lookups of 100 ms each take about 300 ms in sequence and about 100 ms together.
Figure 5 · Diagram
sequenceDiagram
participant A as Agent
participant T1 as Weather API
participant T2 as Calendar API
participant T3 as CRM API
Note over A,T3: Sequential: about 300 ms
A->>T1: call
T1-->>A: result
A->>T2: call
T2-->>A: result
A->>T3: call
T3-->>A: result
Note over A,T3: Parallel: about 100 ms
par
A->>T1: call
and
A->>T2: call
and
A->>T3: call
end
T1-->>A: result
T2-->>A: result
T3-->>A: result
A model can ask for several tools in one turn (parallel tool use). Run them concurrently and send all the results back in one message. This shortens the wait, not the bill: the tokens are the same.
Figure 6 · Chart
Three 100 ms tool calls take 300 ms end to end when run one after another, but only 100 ms when started together
In code: run_sequential awaits each call before starting the next;
run_parallel starts them all with Python's asyncio gather and waits once. View source
Streaming, showing the answer as it is generated, does not shorten the total time either, but the user sees progress at once, so the system feels faster.
Chapter 7
Batch what isn't interactive
Some work has no one waiting on it: nightly evaluation runs, reprocessing a backlog of documents, classifying a pile of old tickets. Providers offer batch APIs for it. You submit many requests at once and collect the results later, within a day, at about half the normal price.
In code: batch_cost prices a list of requests at half price. View source
Chapter 8
Budgets and alerts
The levers so far lower the normal bill. Budgets guard against an abnormal one, from an agent stuck in a loop or a customer whose usage runs away.
A task budget caps the steps and tokens one task may use, so a confused agent stops instead of looping all night. A tenant spend cap (a tenant is one customer organisation on a shared platform) stops one customer's runaway usage from turning into a surprise invoice. An anomaly alert fires when a task uses far more tokens than usual:
The formula and its symbols
Symbols
| Symbol | Meaning here | Worked example |
|---|---|---|
| tokens used by the task just finished | 10,000 | |
| mean tokens per task over this tenant's recent history (Greek mu) | 1,000 | |
| standard deviation of that history: the typical distance from the mean (Greek sigma) | ≈ 71 | |
| how many standard deviations count as unusual | 3 |
In words: alert when a task uses more tokens than the usual amount plus three times the usual spread.
On the worked example: history 1000, 1100, 900, 1050, 950, 1000 has mean 1,000 and standard deviation ≈ 71 (the squared distances from the mean add up to 25,000; divided by 6 − 1 = 5 that's 5,000, whose square root is 70.7), so the line is 1,000 + 3 × 70.7 ≈ 1,212. A 10,000-token task is far above it, so the alert fires. A jump like that points to a loop or a bad deploy.
In Python
import statistics
history = [1000, 1100, 900, 1050, 950, 1000]
mu = statistics.mean(history)
# divides by 6 - 1, as above
sigma = statistics.stdev(history)
mu, round(sigma, 1) # → (1000, 70.7)
z = 3
# the alert line
round(mu + z * sigma) # → 1212
# alert?
10_000 > mu + z * sigma # → True
In code: TaskBudget stops a task at its step or token limit, and
TenantSpend keeps each tenant's total and raises the cap and anomaly
alerts. View source
Chapter 9
The levers in order
Take the levers that cannot hurt quality first:
- Prompt caching: reorder the prompt so the stable prefix is reused. The answers do not change.
- Trim tokens: compress tool results and send fewer chunks.
- Concise output: ask for shorter answers where length adds nothing.
- Route easy tasks to the small model: the first lever that can change the answers, so check it against the evaluation set before and after.
- Batch the work no one is waiting on.
Figure 7 · Chart
Workload cost falls from 67 to 8 cents as levers stack: caching 2.2x, trimming 3.6x, concise output 3.9x, routing 7.8x, batching 8.4x
In code: five_x_plan switches the levers on one at a time, in this
order, and reports the cost and cumulative reduction after each. View source
Test yourself
4 questions
Answer each one out loud or on paper before you open it.
Question 1How would you cut the cost per task by 5x without hurting quality?Think it through, then reveal
First measure: cost per successful task, broken down by step, model, input vs. output, and cached vs. uncached tokens, with an eval set to hold quality fixed. Then, in order: restructure prompts for prompt caching; compress tool results and send only the top reranked chunks; ask for concise output; route simple steps (classification, extraction, formatting) to a small model, checking the eval before and after; move anything non-interactive to a batch API; cap steps and tokens per task. On the sample workload here that's about 8x, and every step after the first three is checked against the eval set.
Question 2Why can a cheaper model cost more?Think it through, then reveal
Because failures cost money too: retries, human cleanup, lost customers. At 60% success with a $2 human fix, a $0.002 call costs $0.80 per task; a $0.010 call at 95% costs $0.11.
Question 3What are the risks of a semantic cache?Think it through, then reveal
Returning a confident, wrong answer to a question that's similar but not the same ("sick days" vs "vacation days"), and serving stale answers after facts change. Mitigate with high thresholds, exact-match guards on IDs, numbers and negation, per-intent scoping, a TTL, and a measured wrong-hit rate on labelled pairs before enabling it.
Question 4Your average tokens per task doubled overnight. What do you check?Think it through, then reveal
Whether a deploy changed a prompt or a tool (a bigger tool output, a new retrieval setting), whether an agent is looping (the same tool called with the same arguments), and whether the prompt cache hit rate dropped (something volatile moved to the top). Traces make this a lookup rather than a guess (Observability).
Primary sources
The papers behind this lesson
Hinton, Vinyals & Dean, Distilling the Knowledge in a Neural Network (2015), Showed how to train a small model to imitate a large one, the technique behind making the cheap model good enough to take more of the routed traffic.
Read on rumblr →The paperChen, Zaharia & Zou, FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance (2023), Studied prompt adaptation, caching and cascades that try cheap models first and escalate to expensive ones only when needed.
The paperResearcher's shelf
Further reading
- Anthropic prompt caching docs: https://docs.claude.com/en/docs/build-with-claude/prompt-caching
- Anthropic Message Batches docs: https://docs.claude.com/en/docs/build-with-claude/batch-processing
- Anthropic, parallel tool use: https://docs.claude.com/en/docs/agents-and-tools/tool-use/implement-tool-use
- Python
asyncio.gather: https://docs.python.org/3/library/asyncio-task.html#asyncio.gather
About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.