Module 5 · Evaluation & production
Semantic caching, latency and cost control
6 min read
An advanced RAG chains many steps: embedding the question, retrieval, re-ranking, sometimes rewriting or an agent, generation, verification. Each adds latency and cost. This lesson does the math, then presents the levers for saving — prompt caching, semantic caching, model choice — with a quantified warning about semantic caching, which is more dangerous than it looks.
The budget of a query
Orders of magnitude for one query, measured on Prism (laptop CPU) or typical for LLM calls:
| Step | Latency | Cost |
|---|---|---|
| Embedding the question (local) | A few ms | None |
| Hybrid search (in-memory index) | < 1 ms on Prism, a few ms at scale | None |
| Re-ranking 20 candidates (CPU) | ≈ 750 ms | None locally |
| Rewrite / HyDE (small model) | A few hundred ms | Low |
| Generation (large model) | 1 to several seconds | The main item |
| Verification (judge) | Like a generation | Doubles the LLM bill |
Two lessons. Retrieval itself is negligible; re-ranking (without a GPU) and LLM calls dominate. And every technique that adds an LLM call must justify its cost with a measured gain (modules 3 and 4).
Prism counts tokens per task, including prompt cache tokens:
def add(self, task: str, usage) -> None:
self.calls[task] = self.calls.get(task, 0) + 1
if usage is not None:
self.input_tokens += usage.input_tokens or 0
self.output_tokens += usage.output_tokens or 0
self.cache_read_tokens += getattr(usage, "cache_read_input_tokens", 0) or 0
self.cache_write_tokens += getattr(usage, "cache_creation_input_tokens", 0) or 0
This per-task breakdown (rewrite, generation, judge…) tells you where the money goes — the first question to ask before optimizing.
Prompt caching
Prompt caching reuses an identical prefix from one call to the next: system instructions, tool definitions, a reference document. Tokens read from the cache cost a fraction of the normal price and are processed faster. For a RAG:
- put everything stable first (instructions, tools, examples), then what varies (passages, question);
- for contextual retrieval, the whole document is the prefix shared by all its passages (lesson 3.4);
- for an agent, the system prompt and tools are a prefix shared by every turn (lesson 4.2).
Reminder: below the model's minimum (512 tokens for Claude Opus 5.5 and Haiku 5.5), nothing is cached, without an error. Check the counters.
Semantic caching
Semantic caching goes further: if a similar question has already been asked, the previously generated answer is returned, with no retrieval or generation.
def lookup(self, question: str, scope: str = "default") -> CacheEntry | None:
vector = self.embedder.embed([question])[0]
now = time.time()
best, best_score = None, -1.0
for entry in self.entries:
if entry.scope != scope or now - entry.created > self.ttl:
continue
score = float(entry.vector @ vector)
if score > best_score:
best, best_score = entry, score
if best is not None and best_score >= self.threshold:
self.stats.hits += 1
return best
Three safeguards are already in the code: the scope (scope: a customer, a language, a permission level — never serve one customer an answer computed for another), the time to live (ttl), and invalidation by source: when an article changes, every answer that cited it is removed.
def invalidate_sources(self, changed: set[str]) -> int:
"""Un article modifié invalide toutes les réponses qui le citaient."""
The threshold: the measurement that gives pause
Everything rests on the similarity threshold. Here are the similarities measured, with the course's embedding model, between « Combien coûte la livraison express ? » (how much does express delivery cost?) and other questions:
| Question | Similarity | Same answer? |
|---|---|---|
| What is the price of express delivery? | 0.956 | Yes |
| how much does express delivery cost (no accents, no question mark) | 0.889 | Yes |
| How much does pickup point delivery cost? | 0.883 | No |
| How much does standard delivery cost? | 0.854 | No |
| How much is express delivery? (asked in English) | 0.835 | Yes |
| How much is express, then? (casual) | 0.818 | Yes |
| How long does express delivery take? | 0.801 | No |
| How much does returning a parcel cost? | 0.561 | No |
(The questions were asked in French, except the one marked as English.) No threshold separates the right answers from the wrong ones. At 0.88, you serve the express price to someone asking for the pickup point price — a factual error, served with confidence. At 0.92, you avoid that error but miss almost every rephrasing: the same question without accents (0.889) is not recognized. Questions that differ by a single decisive word (express/standard) are precisely those the embeddings judge closest.
In practice:
- Normalize the question first (lowercase, accents, spaces, punctuation) and start with an exact cache on the normalized form: risk-free, it captures pure repetitions.
- For the semantic cache, choose a high threshold, measured on real annotated pairs ("same answer?"), and accept a modest hit rate.
- In domains where an error is costly, add a verification: a re-ranker or a small model confirms that the cached question and the new one really ask the same thing.
- Measure the real hit rate: in customer support, many questions repeat; in a documentation assistant, very few do. A cache with a 3% hit rate is not worth its complexity.
Model choice
The simplest lever is often choosing the model per task: a small fast model for rewriting, classification, descriptions and passage grading; the large model for the final generation and for judging. Prism follows this principle with fast=True. Measure each task's quality with the small model before switching.
Key takeaways
- Retrieval is negligible; re-ranking without a GPU and LLM calls dominate latency and cost.
- Track tokens per task, including prompt cache reads and writes.
- Prompt caching: stable prefix first, above the 512-token minimum.
- Semantic caching: scope, time to live, invalidation by source — and a threshold that cannot tell "express delivery" from "standard delivery". Start with an exact cache on the normalized question.
- One model per task: small for simple tasks, large for the answer and the judgment.
Practice
- Measure the similarities of 20 question pairs from your domain, annotated "same answer?", and look for a threshold with no false positive.
- Add to
SemanticCachean exact cache on the normalized question, checked first. - With an API key, run the full test bench and read
llm.USAGE: which task consumes the most tokens?