Semantic Cache: Skip Redundant LLM Calls by Similarity
Use SemanticCache to skip redundant LLM calls when a semantically equivalent prompt has already been answered, cutting latency and token spend.
LLMs are expensive. When users ask questions that are semantically equivalent — “What’s your return policy?” and “How do I return an item?” — there is no reason to run two separate model calls. SemanticCache stores responses keyed on embedding similarity rather than exact string matching, so a new prompt that is close enough to a cached one returns the stored answer instantly without touching the model.
When you call cache.get(prompt), SemanticCache embeds the prompt and queries the backing vector store for the nearest stored entry. If the top result’s cosine similarity exceeds the configured threshold (default 0.95) and the entry has not expired, it’s a cache hit and the stored response is returned. On a miss, your code calls the LLM as normal, then stores the response with cache.set() for future hits.The cache.wrap() convenience method handles the full get-or-produce flow in one call.
import { SemanticCache, HashEmbedder, SqliteVectorStore } from 'anvil/rag';const cache = new SemanticCache({ embedder: new HashEmbedder(), // swap for a semantic embedder in production store: await SqliteVectorStore.open(), // persists hits across restarts threshold: 0.92, // tune for your use case ttlMs: 1000 * 60 * 60 * 24, // 24-hour TTL});
The right threshold depends on how similar “equivalent” prompts need to be for your use case.
Threshold
Behavior
0.99
Near-exact matches only. Safe for factual Q&A with precise phrasing.
0.95
Default. Catches minor wording variations like “What’s” vs “What is”.
0.90
Catches paraphrases and common synonyms. May produce occasional false hits.
0.80
Aggressive caching. Good for narrow-domain FAQs; avoid for open-ended queries.
Using a HashEmbedder in production limits cache effectiveness because it tracks vocabulary overlap, not semantic meaning. Use a semantic provider embedder (OpenAI text-embedding-3-small, Gemini text-embedding-004) for accurate similarity scoring.