Module 09 · Lesson 9.5
Caching, Model Selection and Token Optimization
On this page
- What you will learn
- Three ways to make an agent cheaper and faster
- What to cache: safe and unsafe answers
- Cache keys and expiry: when a stored answer goes stale
- Provider prompt caching: a different kind of cache
- Use smaller models for simple steps
- Trim tokens without losing what matters
- Build a small answer cache in Python
- Measure before and after
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
A baker who gets the same order fifty times a day does not mix fifty separate batches. They bake once and serve from the tray. But they would never reuse a birthday cake with one customer's name on it for another customer. Some things are safe to reuse and some are not.
An AI agent can save money and time in the same way. This lesson covers three levers: caching (reusing an answer you already have), model selection (using a smaller, cheaper model for easy steps) and token optimisation (sending the model less text). You will also learn to measure each change, because a saving you cannot see is only a guess. Most of the lesson needs no coding. One Python script shows a small cache.
What you will learn
- Decide which agent answers are safe to cache and which must never be cached.
- Explain cache keys and expiry, and what happens when a stored answer goes out of date.
- Choose a smaller model for simple steps such as routing, and keep a stronger one for hard steps.
- Run a Python script that shows cache hits, misses, expiry and a rule that refuses to cache order questions.
Before you start
- Monitoring Quality, Failures, Latency and Cost, because you need those numbers to prove a saving.
- No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
Three ways to make an agent cheaper and faster
Every model call costs time and money. A token is a small piece of text, roughly a short word or part of a word, and providers usually charge by the tokens you send and receive. Fewer calls, cheaper calls and shorter calls all lower the bill.
| Lever | What you do | Main risk |
|---|---|---|
| Caching | Reuse a stored answer for a repeated question. | Giving an old or someone else's answer. |
| Model selection | Use a smaller, cheaper model for easy steps. | A weaker model makes more mistakes on hard cases. |
| Token optimisation | Send less text: shorter prompts, fewer old messages, only the passages needed. | Cutting something the model really needed. |
What to cache: safe and unsafe answers
A cache is a short-term store of answers you have already worked out. When the same question comes in again, you hand back the stored answer without asking the model. A hit means the answer was found in the cache. A miss means it was not, so you ask the model and store the new answer.
The rule is simple. Cache answers that are the same for everyone and change rarely. Never cache answers that depend on one person or on live data.
| Question | Cache it? | Why |
|---|---|---|
| How long does standard delivery take? | Yes | Same answer for every customer. It comes from help page KB-01 and rarely changes. |
| What is your returns policy? | Yes | Public policy text (KB-03). Same for everyone. |
| Where is order QF-1042? | No | Depends on one customer and changes as the parcel moves. A stored answer would soon be wrong. |
| Has my return been approved? | No | Personal and live. It could also show one customer's data to another. |
Cache keys and expiry: when a stored answer goes stale
A cache key is the label you file an answer under. "How long does delivery take?" and "how long does delivery take" are the same question, so they should give the same key. A simple fix is to make the question lower case, drop punctuation and collapse extra spaces before using it as the key.
Expiry (often called time to live, or TTL) is how long a stored answer stays valid. Think of milk in a fridge with a date on the carton. After the date you throw it away and buy fresh. For a help-centre answer the expiry might be minutes or hours, depending on how often the page changes.
Three ways a cache goes wrong
- Stale answer: the help page changed but the cache still holds the old text. Fix: use an expiry, and clear the cache when you publish a new knowledge base version.
- Wrong key: two different questions share a key, so one gets the other's answer. Fix: keep the key close to the whole question, and include anything that changes the answer, such as the audience or the version of the instructions.
- Unsafe content stored: a personal or wrong answer gets cached and repeated many times. Fix: only store replies that passed your checks, and only for questions that pass the cacheability rule.
Include the version (from Versioning, Rollbacks and Production Operations) in the key or clear the cache on every release. Otherwise, after you change the instructions, customers keep receiving answers written under the old ones.
Provider prompt caching: a different kind of cache
So far the cache sits in your code and stores finished answers. Some model providers also offer prompt caching or context caching. Here the provider remembers a long, repeated part of your prompt, such as a big set of instructions, so it does not have to process it from scratch on every call.
- Your answer cache skips the model call completely. It is only safe for repeated, non-personal questions.
- A provider's prompt cache still calls the model, but the repeated prefix is cheaper or faster. It does not change the answer, and it can help any question, including personal ones.
- Each provider has its own rules for what can be cached, how long it lasts and how it is billed. Read the current pages for your provider, such as the ones listed in the references, before you rely on it.
A practical tip: provider caches work best when the long, unchanging part of the prompt (the instructions and tool descriptions) comes first and the changing part (the customer's message) comes last.
Use smaller models for simple steps
Not every step needs your strongest model. A supermarket does not send its best chef to stack shelves. In an agent, some steps are easy and well defined:
- Routing: picking one of three routes, as in Supervisor, Specialist and Handoff Patterns. The answer is one fixed word.
- Classifying a message as a question, a complaint or spam.
- Extracting an order number or a date from a message.
A smaller, cheaper model may do these well. Steps that need careful reading of several passages, or writing a reply that must be correct and polite, may need a stronger model.
Trim tokens without losing what matters
Most of the tokens in a run are context: instructions, history and retrieved passages. The earlier lesson Managing Context Windows and Conversation History showed how to choose what each step needs. Here are the same ideas with cost in mind.
- Return fewer passages. If
search_helpreturns three passages and the best one is enough, try returning two. Check that answers stay grounded. - Shorten tool results. Send the model the order status and date, not the whole order record.
- Keep the last few messages, and a short summary of older ones, instead of the full history.
- Tighten the instructions. Remove rules nobody needs. Long prompts are paid for on every call.
- Limit the reply length in the output contract, so the model does not write an essay.
The blog post How to Reduce AI Token Costs When Coding with Claude or ChatGPT covers similar habits for everyday use of AI assistants.
Build a small answer cache in Python
The script below uses a fake clock: the time in seconds is passed in as a number, so the output is the same on every run. It has a cache with expiry, a key builder and a rule that refuses to cache order questions. A fake function stands in for the model.
import re
TTL_SECONDS = 300
cache = {} # key -> (answer, stored_at)
stats = {"hit": 0, "miss": 0, "expired": 0, "skipped": 0}
def make_key(question):
words = re.sub(r"[^a-z0-9 ]", "", question.lower()).split()
return " ".join(words)
def is_cacheable(question):
personal = re.search(r"qf-\d{4}|my order|my return|my refund", question.lower())
return personal is None
def fake_model(question):
return "(model answer for: " + make_key(question) + ")"
def ask(question, now):
if not is_cacheable(question):
stats["skipped"] += 1
return "NOT CACHED " + fake_model(question)
key = make_key(question)
if key in cache:
answer, stored_at = cache[key]
if now - stored_at < TTL_SECONDS:
stats["hit"] += 1
return "HIT " + answer
stats["expired"] += 1
del cache[key]
stats["miss"] += 1
answer = fake_model(question)
cache[key] = (answer, now)
return "MISS " + answer
CALLS = [
(0, "How long does delivery take?"),
(10, "how long does delivery take"),
(20, "Where is QF-1042?"),
(30, "Where is QF-1042?"),
(400, "How long does delivery take?"),
]
for now, question in CALLS:
print("t=" + str(now), ask(question, now))
print(stats)Offline and deterministic. The "model" is a stand-in. Run it with python cache_demo.py.
What each part does
TTL_SECONDS = 300is the expiry: an answer is valid for 300 seconds after it was stored.cacheis a dictionary from key to a pair of the answer and the time it was stored.statscounts what happens.make_keylower-cases the question, removes everything except letters, digits and spaces, and joins the words with single spaces. Two spellings of one question give one key.is_cacheablereturnsFalsewhen the question contains an order number such asQF-1042or phrases such as "my order". This is the rule that keeps personal questions out of the cache.fake_modelstands in for a real model call. A real one would cost time and money.- In
ask, a non-cacheable question skips the cache completely. Otherwise the code checks the key, comparesnow - stored_atwith the expiry, and counts a hit, an expiry or a miss. CALLSis a list of pairs: the fake time and the question. The last call at time 400 comes after the 300-second expiry.
t=0 MISS (model answer for: how long does delivery take)
t=10 HIT (model answer for: how long does delivery take)
t=20 NOT CACHED (model answer for: where is qf1042)
t=30 NOT CACHED (model answer for: where is qf1042)
t=400 MISS (model answer for: how long does delivery take)
{'hit': 1, 'miss': 2, 'expired': 1, 'skipped': 2}Follow the five calls. The second one hits, because the key ignores capital letters and the question mark. The two order questions are never stored, so the model is asked each time. The last call finds the old entry too old, counts it as expired, removes it and asks the model again. In total, one of the five questions was answered from the cache, and that saved one model call. The two order questions went to the model on purpose, because correctness matters more than saving.
Measure before and after
Treat every optimisation as an experiment. Use the same evaluation cases and the same numbers before and after.
Step 1: Record the baseline: model calls per run, median time, slowest run and the evaluation score.
Step 2: Make one change, for example a cache or a smaller model for routing.
Step 3: Run the same cases again and record the same numbers.
Step 4: Check quality first. If the evaluation score dropped or a must-pass case broke, undo the change.
Step 5: Keep the change only if cost or time improved and quality held.
For a cache, also track the hit rate: hits divided by all cacheable questions. A cache that almost never hits is extra code with no benefit.
Conclusion and your next step
You can lower cost and waiting time in three ways: cache answers that are the same for everyone, use smaller models for easy steps, and send fewer tokens. Each has a risk, so keep personal answers out of caches, test cheaper models on your own cases and compare numbers before and after.
Your next step: list the ten most common questions your agent gets. Mark each as safe to cache or not, and name the expiry you would use. Then continue to Versioning, Rollbacks and Production Operations, where you learn to release changes like these safely and roll them back when they fail.
For related reading, see Understanding Context Windows and Token Limits: A Developer's Guide and Vector Search, Metadata Filters and Source Grounding.
Common errors and how to fix them
A customer sees another customer's order details.
Why it happens: An answer built from personal data was stored in a shared cache.
Fix: Add a code rule that refuses to cache questions containing order numbers or personal phrases, and test it with sample questions.
Customers get outdated help answers after a page was updated.
Why it happens: Cached answers have no expiry, or the cache was not cleared when the knowledge base changed.
Fix: Set an expiry, include the knowledge base version in the key and clear the cache on each release.
The cache never hits.
Why it happens: Keys are too exact: capital letters, spaces or question marks make every question look new.
Fix: Normalise the question before building the key, and check the hit rate after a day of real traffic.
The cheaper model saved money but answers got worse.
Why it happens: The switch was made without running the evaluation cases.
Fix: Compare both models on the same cases first, and only use the smaller one for steps where results match.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Decide what Quillfeather should cache
Sort six customer questions into cache or do not cache, choose an expiry for each cached one, and pick one step where a smaller model might be tried.
You will need
- Q1: "How do I size a frame?" (help page KB-06)
- Q2: "Where is QF-1044?"
- Q3: "How long is the warranty?" (help page KB-07)
- Q4: "Has my refund been paid?"
- Q5: "Do you take gift cards?" (help page KB-13)
- Q6: The agent decides whether a message goes to the orders or the help specialist.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Ask: would every customer get the same answer, today and next week?
- Help pages change rarely, so hours is a reasonable order of magnitude. A shorter expiry is safer, a longer one saves more.
- Routing returns one fixed word, which is easy to check against your evaluation cases.
Show a model answer
Cache Q1, Q3 and Q5: they come from fixed public help pages and give the same answer to everyone. An expiry of a few hours works, and the cache is cleared whenever the knowledge base version changes. Do not cache Q2 and Q4: they depend on one customer's live data, and a stored answer could be wrong or shown to the wrong person. Q6 is a good place to try a smaller model, because the answer is one of a few fixed values. Test it by running the routing cases from the evaluation set with both models and comparing how often the route is right. If the smaller model matches, switch and watch the numbers.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The returns policy is the same for every customer and changes rarely. The order and return questions depend on one person and on live data. They are tempting to cache because customers ask them often, but a stored answer could be wrong or leak to someone else.
Show the answer and explanation
Answer: B. A cache keeps serving the stored answer until it expires or is cleared. The model is not involved on a hit, so it cannot know about the new page. Capital letters would only matter if the key were not normalised, and that would cause misses, not old text.
Show the answer and explanation
Answer: B. Running the same cases with both models gives evidence before any customer is affected. Waiting for complaints finds problems late. The cheapest option can look attractive, but price says nothing about whether it routes correctly.
Frequently asked questions
What is caching in an AI agent?
Caching means storing an answer you already worked out and reusing it when the same question comes again. It skips the model call, so it is faster and cheaper. It is only safe for questions that have the same answer for everyone.
What is prompt caching?
Some model providers remember a long, repeated part of your prompt, such as big instructions, so they do not process it from scratch each time. It still calls the model and does not change the answer. Check your provider's current documentation for how it works and what it costs.
Can a smaller model replace a larger one in an agent?
Sometimes. Simple, well-defined steps such as routing or classifying often work well on a smaller model. Test it on your own evaluation cases before switching, and keep the stronger model for steps that need careful reasoning or writing.
How do I reduce token usage without hurting quality?
Send only what each step needs: fewer passages, shorter tool results, the last few messages plus a short summary, and tighter instructions. After each change, run the same evaluation cases to check that quality did not drop.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Context caching(opens in a new tab)
Google · Official documentation · How Google describes caching repeated context for the Gemini API. Check it for current rules.
- Prompt caching(opens in a new tab)
Anthropic · Official documentation · How Anthropic describes caching the repeated start of a prompt.
- Effective context engineering for AI agents(opens in a new tab)
Anthropic · Official documentation · Ideas for keeping the context small and useful.
- Understand and count tokens(opens in a new tab)
Google · Official documentation · What tokens are and how to count them.
- functools module(opens in a new tab)
Python Software Foundation · Official documentation · Python's built-in function cache, useful for simple in-process caching of non-personal results.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.