Semantic Caching
Overview
Semantic Caching is a caching method where the LLM response is stored and reused for queries that are semantically similar to the original query. It differs from exact caching in that it allows serving rephrased queries without re-calling the model.
How It Works
- The query is converted into an embedding.
- Vector search is performed on the cache.
- If a candidate with cosine similarity above the threshold is found — the stored response is returned.
- Otherwise — the LLM is called and the response is saved in the cache.
Example (Redis + embeddings)
import redis
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
r = redis.Redis()
query_vec = model.encode(query)
results = r.ft("idx").search(query_vec, query_params={"k": 1})