AI Hints
Home›RAG Tutorial›Speed, Cost and Freshness
RAG · Lesson 94 of 120

Caching

Don't pay twice.

⏱ 2 min read▶ Video at 1:32:50🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Customers ask the same questions again and again. How much is delivery? Every repeat costs a model call, and makes someone wait. A cache stores answers, so repeats are instant and free.

Caching
From the video: Caching
  • Same questions repeat
  • Each one costs
  • Cache the answers

A simple answer cache

Key tidies the question, lower case, with no extra spaces or question mark. Cached answer checks the cache first, and only calls the model on a miss. We ask the same question twice, written slightly differently. Run it. The first call takes a moment. The second is almost instant.

cache.pypython
import time
from rag_kit import load_docs, make_chunks, Index
from llm import answer

index = Index(make_chunks(load_docs()))
cache = {}

def key(q):
    return " ".join(q.lower().strip(" ?").split())

def cached_answer(q):
    if key(q) not in cache:
        cache[key(q)] = answer(q, [c for s, c in index.search(q)])
    return cache[key(q)]

for q in ["How much is UK delivery?", "how much is UK delivery"]:
    start = time.perf_counter(); cached_answer(q)
    print(f"{q:28} {(time.perf_counter() - start) * 1000:.0f} ms")
Output
How much is UK delivery?     965 ms
how much is UK delivery      0 ms
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses llm.py
from langchain.chat_models import init_chat_model

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".

Context:
{context}

Question: {question}"""

def answer(question, chunks):
    context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
    return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()

What to cache

Cache embeddings of chunks, so you never embed the same text twice. Cache answers to common questions. Clear the answer cache whenever documents change. And a semantic cache matches questions by meaning, not just text.

keyvalue
Embeddingsnever twice
Answerscommon questions
Clearwhen docs change
Semantic cachematch by meaning

Summary

Caching stores embeddings and answers, so repeat work is instant and free. Next, where time and money go.

Key takeaways
  • Normalise the key
  • Check the cache
  • Clear on change
Next up: Cost and Speed — where time goes