Sub topic 13
Practical Ways to Lower Cost
This chapter assumes you can read basic Python, have called a chat or completion API, and know the earlier chapters' ideas. Those ideas are tokens, the context window, per-million-token pricing, usage data, and history growth. Here you turn that knowledge into changes that shrink a bill.
Start with the cost formula
Every saving comes from one of four places. The cost of a call is:
cost = (input_tokens x input_price + output_tokens x output_price) / 1,000,000You can lower the number of tokens you send, the number the model writes, or the price you pay per token. You can also make fewer calls. The table maps each lever to the techniques in this chapter.
| Lever | Technique | Typical risk |
|---|---|---|
| Fewer input tokens | Trim history, summarize, retrieve only relevant text | Losing context the model needs |
| Cheaper input tokens | Prompt caching | Cache misses when the prefix changes |
| Fewer output tokens | Output caps, concise instructions | Truncated answers |
| Lower price per token | Smaller or cheaper model | Lower quality on hard tasks |
| Fewer calls | Application-side caching, batching | Stale answers, added latency |
Measure before you optimize
Optimizing without data wastes effort. Log the usage block from every API response, as covered in the usage reporting chapter. For a sample of real traffic, work out how the input splits into parts: system prompt, history, retrieved documents, tool results, and the new user message.
Also compare output cost with input cost. Output tokens usually cost several times more than input tokens. With the placeholder prices from earlier (3.0 for input, 15.0 for output per million), a call with 2,000 input tokens and 500 output tokens costs $0.0135. Output is only 20% of the tokens but 55.6% of the cost ($0.0075 of $0.0135).
Check what dominates your own traffic. A chatbot with long histories is usually input-heavy. A report generator is usually output-heavy.
Trim the history
A chat that resends its full history pays for every earlier turn again on each call. The total_input_tokens function from the history growth chapter showed that ten turns with a 500-token system prompt, 100-token user messages, and 300-token replies bill 24,000 input tokens.
The simplest fix is a sliding window that keeps only the most recent messages. This function keeps the newest messages that fit a token budget. You supply the counting function:
def trim_history(messages, count_tokens, budget):
kept = []
used = 0
for message in reversed(messages):
n = count_tokens(message)
if used + n > budget:
break
kept.append(message)
used += n
return list(reversed(kept))To see the effect on the earlier scenario, model a window that keeps only the last two completed exchanges, where an exchange is one user message and one reply:
def windowed_input_tokens(system_tokens, user_tokens, reply_tokens,
turns, keep_exchanges):
total = 0
for t in range(turns):
kept = min(t, keep_exchanges) # t exchanges are finished before turn t
total += system_tokens + kept * (user_tokens + reply_tokens) + user_tokens
return total
print(windowed_input_tokens(500, 100, 300, 10, 2)) # 12800Input drops from 24,000 to 12,800 tokens, a saving of about 47%. The gap widens as the conversation grows, because windowed cost grows linearly with turns while full-history cost grows quadratically.
Three edge cases cause bugs in real systems:
- Always keep the system prompt outside the trimmed list. If it falls out of the window, the model forgets its instructions.
- Never cut between paired messages. If a tool call is kept but its result is dropped, many APIs reject the request. Trim in whole exchanges.
- Remember that dropped messages are gone. If the user asks "what did I say earlier?", the model cannot answer.
Summarize and retrieve
Two alternatives keep the useful information while spending fewer tokens.
Summarizing replaces old turns with a short summary, for example 200 tokens in place of 3,000. The summary needs its own model call, so it pays off only when the saved tokens are resent over many later turns. Run the summarization with a cheaper model, and do it occasionally, for example once the history passes a threshold, not on every turn.
Retrieval stores documents or past messages outside the prompt and inserts only the pieces relevant to the current question. This suits large knowledge bases that could never fit in the window. The costs are an extra search step and the chance that the search misses the passage that mattered.
Use prompt caching
Many calls start with the same large prefix, such as a long system prompt, tool definitions, or a reference document. With prompt caching, the provider reuses its work on a prefix it has seen recently and bills those tokens at a reduced rate.
Details differ by provider, so check the current documentation. The common pattern is:
- The cached part must be an exact prefix, so put stable content first and changing content last.
- There is usually a minimum prefix length, and entries expire after a short time.
- Some providers charge extra the first time a prefix is written, and a lower price on each read.
Here is the arithmetic with placeholder prices: 3.0 for normal input, 3.75 for a cache write, and 0.30 for a cache read, all per million tokens. The prefix is 4,000 tokens, sent on 20 calls.
def cost_with_cache(prefix_tokens, calls, write_price, read_price):
write = prefix_tokens * write_price
reads = prefix_tokens * (calls - 1) * read_price
return (write + reads) / 1_000_000
without_cache = 4000 * 20 * 3.0 / 1_000_000
with_cache = cost_with_cache(4000, 20, 3.75, 0.30)
print(f"${without_cache:.4f}") # $0.2400
print(f"${with_cache:.4f}") # $0.0378The prefix cost falls by about 84%. Caching helps only if calls repeat the prefix before the entry expires, so a feature used once an hour may never hit the cache.
Control output length
Since output is the pricier side, shortening it pays well. Three tools help:
- Set the maximum output tokens parameter to a value that fits the task, not the model's maximum.
- Ask for the format you need. "Reply with one word: positive, negative, or neutral" costs a few tokens. A free-form explanation costs hundreds.
- Request structured output such as JSON with only the fields you need, and drop fields you will not read.
Halving the example call's output from 500 to 250 tokens changes the cost from $0.0135 to $0.00975, a saving of about 28%.
A cap is a hard stop, not a request for brevity. If the cap is too low, the answer is cut off mid-sentence. Check the finish reason in the response, which usually reports a length stop, and handle it. Also remember that hidden reasoning tokens count toward the output cap and are billed as output. A low cap on a reasoning model can leave no room for the visible answer.
Choose the right model
Model prices can differ by more than ten times between a small and a large model from the same provider. Many tasks do not need the largest one. Classification, extraction, simple rewriting, and routing are common examples. Illustrative prices:
| Model tier | Input per million | Output per million | Cost of 2,000 in, 500 out |
|---|---|---|---|
| Large (placeholder) | 3.00 | 15.00 | $0.0135 |
| Small (placeholder) | 0.25 | 1.25 | $0.001125 |
Work out the small row: 2,000 x 0.25 + 500 x 1.25 = 1,125, divided by 1,000,000 gives 0.001125. That is 12 times cheaper.
To choose safely, build a small test set of real inputs with known good answers. Run both models on it and compare quality. Move a task to the smaller model only if the results are acceptable. A common pattern is a cascade. The small model handles each request first, and only low-confidence or failed cases go to the large model.
Cut calls entirely
The cheapest call is the one you never make.
- Cache responses in your application when identical requests recur, for example the same FAQ question. Key the cache on the full prompt and model name.
- Use batch endpoints where offered. Many providers discount non-urgent jobs that can wait hours for results, but the rate and delay vary, so check current terms.
- Shrink tool and document output before it enters the prompt. A search result trimmed to the relevant 300 tokens is cheaper than a whole page.
- Limit retries and loops. An agent that retries a failing step ten times, each time resending a long history, can cost more than the task is worth. Set a maximum number of steps.
Verify each change
Each technique trades something away, so treat savings as a hypothesis. After a change, re-measure tokens and cost on real traffic, and check answer quality against your test set. A change that saves 40% but makes 10% of answers wrong is rarely a win. Apply one change at a time so you can see which one helped.
Exercise
A support bot sends a 3,000-token system prompt and a 200-token user message on every call, and the system prompt never changes. Normal input costs 3.0 per million tokens, cache reads cost 0.30 per million, and the first cache write costs 3.75 per million. Ignoring output, what is the input cost of 11 calls without caching, and with caching of the system prompt only (user messages billed at the normal rate)?
Show answer
Without caching, each call sends 3,200 tokens, so 11 calls send 35,200 tokens. 35,200 x 3.0 / 1,000,000 = $0.1056. With caching, the first call writes 3,000 tokens: 3,000 x 3.75 = 11,250. The other 10 calls read them: 3,000 x 10 x 0.30 = 9,000. The user messages total 200 x 11 = 2,200 tokens at 3.0, which is 6,600. The sum is 26,850, divided by 1,000,000, so about $0.0269. That is roughly a 75% saving.
Exercise
Your chat app trims history with a sliding window to keep only the last 2 exchanges, but you also use prompt caching on the whole prompt, and you see almost no cache hits. Why, and what is one fix?
Show answer
The window moves forward every turn, so the start of the history changes and the prompt prefix never matches an earlier request exactly. One fix is to cache only the fixed system prompt and documents placed before the history. Another is to trim in larger steps, so the prefix stays the same for many turns between trims.