RAG Caching
Purpose
RAG systems perform several expensive operations: query embedding generation, vector search, reranking, and LLM invocation. Caching enables the reuse of results from these operations for repeated or similar queries, reducing latency and cost.
Levels of Caching
| Level | What is Cached | Key |
|---|---|---|
| Embeddings | Query vector | Text hash of query |
| Search | Retrieval results | Query hash + parameters |
| LLM Response | Generated response | Prompt hash |
| Semantic | Response for similar queries | Query vector |
Strategies
- Exact caching: Match by text hash. Simple but inefficient for variant queries.
- Semantic caching: Search for similar queries in a vector database. Allows reuse of answers for rephrased questions.
- Caching intermediate results: Save retrieval results for reuse with identical queries.
class RAGCache:
def __init__(self, vector_store):
self.vector_store = vector_store
def get(self, query):
similar = self.vector_store.search(query, top_k=1)
if similar and similar[0].score > 0.95:
return similar[0].answer
return None