AI Agent Semantic Cache 2026
The same weather question, phrased two ways, hits the model twice. Semantic caching shares answers across paraphrases, at the cost of tuning thresholds, TTLs and tenant isolation. A runnable implementation and a production checklist.
📜 Table of Contents
📖 Keep reading
Semantic Caching for Agents: Stop Paying Twice for the Same Question
"How's the weather in Beijing" and "what temperature is it in Beijing today" are different strings and identical questions. Exact caching misses both. Semantic caching embeds the query and reuses the answer above a similarity threshold.
The bigger win is latency, not just cost: a cache hit returns in milliseconds. But caching is also the fastest way to spread a wrong answer, so threshold, TTL and isolation come first.
Exact vs semantic
| Type | Hit condition | Risk |
|---|---|---|
| None | — | full model cost |
| Exact (hash) | identical input | almost none |
| Semantic (vector) | similarity above threshold | answering a different question |
Hit rates depend entirely on the domain. Support traffic repeats heavily; creative work barely repeats. Ignore borrowed percentages.
The threshold is the whole game
0.90-0.95 is a common starting range, but short Chinese questions need more care: "how many days for a refund" and "what documents for a refund" look similar and mean different things. Start at 0.95 and lower only after measuring.
To calibrate, label 100 real queries, then sweep 0.85 / 0.90 / 0.93 / 0.95 / 0.97 and plot precision against hit rate.
Minimal implementation
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("BAAI/bge-small-zh-v1.5")
def norm(v):
return v / (np.linalg.norm(v) + 1e-9)
def get(query, store, tenant, threshold=0.95):
q = norm(model.encode(query, normalize_embeddings=True))
best, sim_best = None, 0.0
for vec, ans, t in store:
if t != tenant:
continue
sim = float(np.dot(q, vec))
if sim > sim_best:
best, sim_best = ans, sim
return best if sim_best >= threshold else None
Linear scan, no TTL, no capacity limit: fine for a prototype, not for production.
Four things production needs
- A real index: Qdrant, Milvus, Redis vector search, or pgvector with a tenant filter.
- TTLs by content type: prices, stock, policy and weather must expire.
- Tenant isolation in the query, not just in application logic.
- Only cache deterministic answers: anything personalised per user stays out.
Measuring
Hit rate = hits / requests, reported per scenario. Improve it with query normalisation (drop filler words, unify abbreviations), clustering of paraphrases, and coreference resolution before lookup. Each of those trades precision for recall, so evaluate separately.
Two dangerous categories
- Wrong answers get amplified. Gate writes on quality checks: citations present, schema valid, no fallback phrasing.
- Stale content becomes misinformation. Short TTL or no caching for time-sensitive data.
FAQ
Is this the same as prompt caching? No. Prompt caching reuses prefix computation to save input tokens; semantic caching reuses whole answers.
Which embedding model? A small bilingual or Chinese model is enough for short queries. Keep cache vectors in a separate collection from retrieval vectors.
Redis or a vector DB? Often both: vectors for similarity, Redis for answer text and TTL, joined by id.
What hit rate is normal? No universal number. Support agents can exceed 30%; tool agents are often far lower. Measure a week first.
Model and vector-store capabilities change; check official docs.
Related
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.