Sub topic 13
Practical ways to lower cost
This chapter assumes you can read basic Python, have called an LLM chat API, and know that cost is input tokens and output tokens multiplied by per-million-token prices. It also assumes you have seen history trimming and prompt caching introduced earlier. Here they are combined into a checklist you can apply in order.
Start from where the tokens go
Optimizing without measurement wastes effort. Read the usage data from your API responses and split the bill into three parts: input tokens, output tokens, and cached input tokens if your provider reports them. Output tokens usually cost several times more per token than input tokens. Input tokens are usually far more numerous, especially in chats.
The earlier history example shows the pattern. Ten turns of a chat with a 500-token system prompt, 100-token user messages, and 300-token replies bill 24,000 input tokens. The new text written during those turns is only 4,000 tokens. Most of the bill is repeated history, so that is the first place to look.
Reduce what you send
Cut input tokens before anything else, because every token is billed on every call.
- Remove instructions the model does not need. A 500-token system prompt that could be 200 tokens costs 300 extra tokens on every turn.
- Send only the relevant parts of a document. Retrieve the few passages that answer the question instead of pasting the whole file.
- Trim history with a token budget. The
trim_historyfunction from earlier keeps the newest messages that fit.
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))
# Stand-in counter: roughly one token per four characters.
def rough_count(message):
return max(1, len(message) // 4)
history = ["a" * 400, "b" * 400, "c" * 400, "d" * 400]
print(len(trim_history(history, rough_count, 250))) # 2With a budget of 250 tokens and 100 tokens per message, only the two newest messages fit. Trimming caps how much history each call pays for, so input cost stops growing with every turn.
Trimming discards information. If older messages matter, summarize them into a short message first and keep that summary at the start of the trimmed history.
Reduce what you receive
Output tokens are the expensive side, so control them directly.
- Set a maximum output length that matches the task. A classifier needs a few tokens, not a few hundred.
- Ask for a format that is short. "Answer with one word" or a compact JSON object costs less than a paragraph.
- Watch reasoning tokens. If a model produces hidden reasoning that is billed as output, lower the reasoning effort setting for easy tasks.
Cache the stable prefix
If every request starts with the same long system prompt, examples, or document, prompt caching lets the provider bill that repeated prefix at a reduced rate. Caching only works when the start of the prompt is identical, so put fixed content first and changing content last.
Match the model to the task
Models differ in price by large factors. Use the cost function to compare options on a real workload instead of guessing.
def estimate_cost(input_tokens, output_tokens,
input_price_per_million, output_price_per_million):
return (
input_tokens * input_price_per_million
+ output_tokens * output_price_per_million
) / 1_000_000
# Placeholder prices in dollars per million tokens, not real rates.
large = estimate_cost(2000, 500, 3.0, 15.0)
small = estimate_cost(2000, 500, 0.25, 1.25)
calls = 100_000
print(f"large: ${large * calls:,.2f}") # large: $1,350.00
print(f"small: ${small * calls:,.2f}") # small: $112.50A common design sends easy requests to the small model and hard ones to the large model. Check quality on a sample first. A cheaper model that fails and forces a retry can cost more than the model it replaced.
Summary of techniques
| Technique | Reduces | Main risk |
|---|---|---|
| Shorter prompts | Input tokens | Lost instructions |
| History trimming | Input tokens | Lost context |
| Output limits | Output tokens | Cut-off answers |
| Prompt caching | Input price | Cache misses from changing prefixes |
| Smaller model | Both prices | Lower quality |
Exercise
A chat resends 3,000 tokens of history on each call. Caching bills the repeated prefix at a lower rate, but only if the prompt starts identically each time. The app inserts the current time as the first line of the system prompt. Why does caching fail, and what is the fix?
Show answer
The timestamp changes on every call, so the beginning of the prompt is never identical and the cached prefix cannot be reused. Move the timestamp to the end of the prompt, after the stable system prompt and history, so the long fixed prefix stays the same.
Exercise
Using the placeholder prices above, a task averages 1,000 input tokens and 200 output tokens. The large model costs $3 input and $15 output per million tokens. The small model costs $0.25 and $1.25. How much cheaper per call is the small model?
Show answer
Large: (1000 x 3 + 200 x 15) / 1,000,000 = 6,000 / 1,000,000 = $0.0060. Small: (1000 x 0.25 + 200 x 1.25) / 1,000,000 = 500 / 1,000,000 = $0.0005. The small model is $0.0055 cheaper per call, which is 12 times cheaper.