Problem

LLM API calls are expensive and slow. Traditional exact-match caching misses semantically identical queries phrased differently.

Solution

Embed each prompt using a fast embedding model, store the embedding alongside the cached response, and on new requests compare the query embedding against cached embeddings using cosine similarity. If the similarity exceeds a threshold (e.g., 0.95), return the cached response.

Implementation

  1. Hash the system prompt + user message
  2. Generate embedding via a lightweight model (e.g., text-embedding-3-small)
  3. Query vector store for nearest match above threshold
  4. Cache hit → return stored response; cache miss → call LLM, store result + embedding

Trade-offs

  • Pro: Every hit skips an LLM call, so the saving tracks your hit rate on repetitive workloads (customer support, FAQ)
  • Pro: A hit costs one embedding call and a vector lookup, which is usually much faster than generating a response
  • Con: Stale responses if underlying data changes — need TTL or invalidation
  • Con: Threshold tuning is domain-specific; too low = wrong answers, too high = low hit rate

When to use

High-volume, repetitive query patterns — chatbots, search, customer support.

When to avoid

Creative/generative tasks, real-time data queries, low-volume APIs.