A thrifty coffee stall doesn't have the barista make every cup. Ordinary coffee comes from a sachet, and the barista only helps with special orders. Water that's already boiled is used again, not boiled again for every cup. And when ten people order the same iced tea, one jug is enough.
An AI API bill can be cut in the same three ways. The bill is tokens × price per token × number of requests, so optimising cost means lowering one of those three numbers. The price per token goes down when a small model does the simple tasks: that is the sachet. The tokens billed in full go down with prompt caching (the same part of the prompt billed for less) and an output cap. Prompt caching is the boiled water. The number of requests goes down with a response cache (the same answer stored and used again): that is the jug.
Tokens into money: compute it first
Prices on OpenAI's "Pricing" page, October 2026, in dollars per 1 million tokens (cache read: tokens read from the cache; cache write: tokens written to the cache):
| Model | Input | Cache read | Cache write | Output |
|---|---|---|---|---|
gpt-6-luna |
$0.10 | $0.01 | $0.125 | $0.50 |
gpt-6.1-sol |
$2 | $0.10 | $2.50 | $10 |
gpt-6-astra |
$10 | $1 | $12.50 | $50 |
At Anthropic, input / output prices per 1 million tokens: claude-haiku-5-5 $0.10 / $0.50, claude-sonnet-5-5 $2 / $10, claude-opus-5-5 $4 / $20 (Anthropic's "Pricing" and "Prompt caching" pages, October 2026).
The Lab uses assumptions for the Bookshop assistant. They are example numbers, so swap in your own usage. There is a fixed 1,100-token prefix: instructions, tool definitions and the shop FAQ (returns, shipping, opening hours). The prefix is the opening part of the prompt that is the same in every request. Then there are 100 tokens that change (<stock_data> and the question), so each question has 1,200 input tokens. The output is 40 tokens for a stock question and 200 for a recommendation. The Lab's log from 08:01 to 08:44 holds 20 questions: 18 ask about stock or price, and 2 ask for a recommendation. At 10,000 questions a day, a month is 10,000 × 30 = 300,000 questions, and 9 in 10 are stock questions. If all of them go to gpt-6.1-sol:
- stock on
gpt-6.1-sol: (1,200 × 2 + 40 × 10) / 1,000,000 = $0.0028 × 270,000 = $756 - recommendations: (1,200 × 2 + 200 × 10) / 1,000,000 = $0.0044 × 30,000 = $132
- total $888 a month
Before you read on, guess. There are three ways: a response cache, prompt caching, and sending stock questions to gpt-6-luna. Which one cuts this $888 the most?
Model routing: a small model for simple tasks
Routing means picking the model for each question. A small model can answer a stock question, because the answer is already in <stock_data>. The big model is only for questions that need it, such as recommendations. This is the routing pattern from Anthropic's "Building effective agents" (the AI Agent Patterns lesson). The pickModel function below sends questions that name a book title and a word such as "stock" or "price" to gpt-6-luna, and the rest to gpt-6.1-sol:
const TITLES = ["the rainbow troops", "this earth of mankind", "beauty is a wound", "the dancer"];
function pickModel(q) {
const t = q.toLowerCase();
const stockOrPrice = TITLES.some((title) => t.includes(title)) && /\b(stock|price|how much|have|left)\b/.test(t);
return stockOrPrice ? "gpt-6-luna" : "gpt-6.1-sol";
}
Stock questions move to gpt-6-luna, 20 times cheaper per token: (1,200 × 0.10 + 40 × 0.50) / 1,000,000 = $0.00014 × 270,000 = $37.80. Recommendations stay at $132. The total is $169.80, 81% saved. So routing matters most. Before you switch, run the eval set (the Evaluating AI Output lesson) on the small model. Cheaper is worthless if the stock numbers become wrong.
Prompt caching: the same prefix, billed for less
Prompt caching means the provider keeps its processed form of a prefix that several requests share. Later requests read that prefix from the cache at a much lower price. The rules differ per provider (checked October 2026). In the table, TTL (time to live) is how long the cache lasts:
| OpenAI, GPT-5.6 and later | Anthropic | |
|---|---|---|
| Turning it on | automatic; explicit mode with prompt_cache_breakpoint to choose where the prefix ends |
cache_control: { type: "ephemeral" } on a block, or once at the top level of the request |
| Minimum prefix | 1,024 tokens | 512 tokens on claude-haiku-5-5, Sonnet 5.5, Opus 5.5 |
| Writing to cache | 1.25× the input price | 1.25× (5-minute TTL), 2× (1-hour TTL) |
| Reading from cache | 0.1× (0.05× on gpt-6.1-sol) |
0.1× (0.05× on Opus 5.5 and Sonnet 5.5, 0.025× on Fable 5.2; checked November 2026) |
| Lifetime | at least 30 minutes since last use | 5 minutes, extended for free on each use |
In the OpenAI request below (explicit mode), the breakpoint sits at the end of RULES_AND_FAQ:
const res = await client.responses.create({
model: pickModel(q),
reasoning: { effort: "none" },
prompt_cache_options: { mode: "explicit" },
tools,
input: [
{ role: "developer", content: [{ type: "input_text", text: RULES_AND_FAQ, prompt_cache_breakpoint: { mode: "explicit" } }] },
{ role: "user", content: `<stock_data>${await stockData()}</stock_data>\n<question>${sanitize(q)}</question>` },
],
max_output_tokens: 300,
});
console.log(res.usage.input_tokens_details); // { cached_tokens, cache_write_tokens }
- Put the parts that stay the same (instructions, tools, FAQ) first, and the parts that change (stock, the question) last. One different character at the front and the prefix no longer matches.
- Top-level
instructionscan't hold a breakpoint, so the rules move into adevelopermessage. In explicit mode, what comes after the breakpoint isn't written to the cache, so it doesn't pay the 1.25× write price. OpenAI's guide does the same in its single-turn judge example (an LLM judge that grades one conversation). - Changing
toolsorreasoning.effortchanges the prefix too.
At Anthropic it looks like system: [{ type: "text", text: RULES_AND_FAQ, cache_control: { type: "ephemeral" } }], then check usage.cache_creation_input_tokens and usage.cache_read_input_tokens.
The Lab's sums assume 95% of requests find the prefix in the cache. So a stock question on gpt-6-luna drops to $0.0000473 (from $0.00014), and routing plus prompt caching totals $86.04. Turn the FAQ off in the Lab. The prefix shrinks to 300 tokens, under the 1,024 minimum, so nothing is cached, and no error appears. The total is $100.20, more than the cached 1,100-token prompt. OpenAI's guide calls this a cost trap: sometimes adding useful content until you pass 1,024 tokens is actually cheaper.
A response cache: question + stock version
Prompt caching still calls the model. A response cache doesn't call it at all: the same question is answered from a stored answer. The code below stores answers in a Map, with a key made from the stock version and the question:
const cache = new Map(); // in production: Redis or the Laravel cache
const cacheKey = (q, version) => version + ":" + q.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, "").replace(/\s+/g, " ").trim();
async function ask(q) {
const version = await stockVersion(); // goes up whenever stock changes
if (cache.has(cacheKey(q, version))) return cache.get(cacheKey(q, version));
const answer = await assistant(q);
cache.set(cacheKey(q, version), answer);
return answer;
}
- The key is normalised: all lowercase, no punctuation, no double spaces. So "is the rainbow troops still in stock" and "Is The Rainbow Troops still in stock?" become the same key.
- The stock version is in the key. The 08:12 sale raises version 41 to 42, so the old "12 in stock" answer is no longer used. Without a version, the cache answers with stale stock.
- Paraphrases (other sentences with the same meaning) don't match: "How many copies of Beauty Is a Wound are left?" has a different key from "Do you have Beauty Is a Wound?". A cache based on embedding similarity could catch them, but it's risky: "This Earth of Mankind stock" and "The Rainbow Troops stock" are similar sentences with different answers.
In the Lab's log, 8 of 20 questions (40%) are answered from the cache. The cost only drops from $86.04 to $80.36, because stock questions on gpt-6-luna are already cheap. The main gain is waiting time (an instant answer, with no request to the model) and staying under the rate limit.
Cap tokens, and use Batch for night jobs
max_output_tokensis an upper limit on the tokens the model generates, reasoning tokens included. One answer that runs too long, 4,000 tokens ongpt-6.1-sol, costs 4,000 × $10 / 1,000,000 = $0.04: nine times a normal recommendation. With a cap of 300, output costs at most $0.003.- Batch API: many requests are sent together, and their results may come later. OpenAI's Batch API and Anthropic's Message Batches are both 50% cheaper and finish within 24 hours. Re-summarising 5,000 synopses every night (300 tokens in, 150 out) on
gpt-6.1-sol: $10.50 becomes $5.25. A chat a customer is waiting on stays a normal request.
So the most effective ways to cut LLM API cost: cache responses, use a smaller model for simple tasks, and cap tokens. In the Lab, those three plus prompt caching turn $888 into $80.36 a month, about 91% saved.
⚠️ Savings that don't actually save
- Lowering temperature to get shorter answers. Temperature controls how random the answer is, not its length. Length is limited by
max_output_tokensand the instructions. - Thinking streaming is cheaper. Streamed tokens are billed exactly the same. Streaming only makes the answer feel faster.
- Putting the changing part at the front of the prompt. Stock or a date at the start makes the prefix different on every request, so the cache is never used.
- A response cache with no data version. "12 in stock" keeps being served after the book sells out.
- Thinking self-hosting is always cheaper. Self-hosting means running the model on your own machine. At the Bookshop's volume,
gpt-6-lunais already very cheap. The sums are in the next lesson, Self-hosted Models (Ollama).
TL;DR: Cost = tokens × price per token × number of requests. Compute it from usage first: with every question on gpt-6.1-sol, 10,000 questions a day cost $888 a month. Routing (picking the model per question: stock to gpt-6-luna, 20 times cheaper) saves the most, down to $169.80. Prompt caching (the provider stores the opening part of the prompt that stays the same, then bills it for less) brings it to $86.04, as long as the fixed part comes first and passes the minimum length. OpenAI GPT-5.6 and later: at least 1,024 tokens, cache write 1.25×, read 0.1× or 0.05× on gpt-6.1-sol, at least 30 minutes' lifetime. Anthropic cache_control: at least 512 tokens on Haiku 5.5, write 1.25×, read 0.1×, 5-minute TTL (how long the cache lasts). A response cache keyed by the normalised question (lowercase, no punctuation) + the stock version (a number that goes up whenever stock changes) answers 40% of the log without the model ($80.36). max_output_tokens limits answers that run too long, and the Batch API takes 50% off work that may finish within 24 hours. Temperature and streaming don't lower cost.
⚡ Routing: a small model for simple tasks
Write:
return stockOrPrice ? "gpt-6-luna" : "gpt-6.1-sol";
Guess first: with every question on gpt-6.1-sol, the cost is $888 a month. Stock questions (9 in 10) cost $756 of that $888. Move the stock questions to gpt-6-luna, 20 times cheaper per token: what's the total now?
$169.80, 81% less. Stock questions drop to $37.80, and recommendations stay at $132.
Meaning: Routing means picking the model for each question. stockOrPrice is true when the question names a book title and asks about stock or price. The answer is already in the <stock_data> sent in the prompt, so a small model is enough. Run the eval set (the test questions from the Evaluating AI Output lesson) before you switch.
⚡ Prompt caching: the fixed part goes first
Guess first: prompt caching (the provider stores the opening part of the prompt that stays the same, then bills it for less) only works when that opening part is at least 1,024 tokens. The Bookshop assistant's opening part is 1,100 tokens, including the shop FAQ. Remove the FAQ and it shrinks to 300 tokens. Does the cost go down?
Up. 300 tokens is under the 1,024 minimum, so nothing is cached. The total is $100.20, more than $86.04 with the 1,100 cached tokens.
Meaning: Put the fixed parts (instructions, tools, the FAQ) first, and stock and the question last. One different character at the front and that opening part no longer matches the cache.
⚡ An answer cache with the stock version
Write:
cache.set(cacheKey(q, version), answer);
Guess first: an answer cache (also called a response cache) stores the model's answers under a key. The key holds the stock version, a number that goes up every time stock changes. The 08:12 sale raises the stock version from 41 to 42. Is the old "12 in stock" answer still served?
No. The key now starts with 42, so the old answer isn't found.
Meaning: The same question is answered from the cache without calling the model. Key = stock version + normalised question (lowercase, no punctuation). In the Lab's log, 8 of 20 questions (40%) are answered without the model.
⚡ Cap the tokens
Write:
max_output_tokens: 300,
Meaning: max_output_tokens is an upper limit on the tokens the model generates. With a cap of 300, an output costs at most $0.003 on gpt-6.1-sol, not $0.04 for a 4,000-token answer that runs too long. So the most effective way to cut cost: cache answers, use smaller models for simple tasks, and cap tokens. Temperature and streaming don't lower cost.