If you are building AI agents for customer support, FAQ systems, or conversational interfaces, you will quickly notice a pattern: users ask the exact same questions over and over again using slightly different phrasing.
Standard backend architecture relies heavily on exact-match caching systems like Redis key-value stores. But exact-match caching falls short when dealing with natural language inputs.
Consider these two user queries:
- "What is your refund policy?"
- "How do I get my money back?"
To a traditional key-value cache indexed by the prompt string, these are two entirely different keys. The cache misses on the second query, forcing your system to make a full API call to your LLM provider. You end up paying full model inference costs and suffering unnecessary latency for an answer your application has already generated hundreds of times.
The Fix: Semantic Caching
Semantic caching shifts the evaluation from literal string matching to intent comparison. Instead of checking if two query strings match character for character, it converts incoming prompts into mathematical vector embeddings and compares their semantic similarity against cached entries.
Here is how the lifecycle of a semantic cache works:
- Query Ingestion: A new prompt arrives at your application gateway.
- Vector Embedding: The query is converted into a high-dimensional vector using a fast, low-cost embedding model.
- Similarity Lookup: Your cache queries existing vectors using cosine similarity or Euclidean distance.
-
Hit/Miss Evaluation:
- Cache Hit: If the highest similarity score meets or exceeds your defined threshold (e.g., 0.88), the system returns the pre-computed answer instantly.
- Cache Miss: If no match passes the threshold, the request is routed to your main LLM, and the new query vector along with the generated response is stored in the cache for future requests.
Because embedding API calls cost a tiny fraction of a main LLM call and resolve in milliseconds, replacing repetitive LLM calls with vector lookups drastically cuts both your inference bill and execution latency.
Implementing a Semantic Cache in Python
Here is a practical, lightweight example showing how to build a semantic cache using OpenAI embeddings and NumPy for vector similarity comparisons.
import numpy as np
from openai import OpenAI
client = OpenAI()
def get_embedding(text: str) -> np.ndarray:
response = client.embeddings.create(
model="text-embedding-3-small",
input=text
)
return np.array(response.data[0].embedding)
def cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
class SemanticCache:
def __init__(self, threshold: float = 0.88):
self.cache = [] # In production, back this with a vector database
self.threshold = threshold
def lookup(self, query_vector: np.ndarray):
for entry in self.cache:
similarity = cosine_similarity(query_vector, entry["vector"])
if similarity >= self.threshold:
return entry["response"], similarity
return None, 0.0
def store(self, query_vector: np.ndarray, response: str):
self.cache.append({
"vector": query_vector,
"response": response
})
cache = SemanticCache(threshold=0.88)
def handle_user_query(prompt: str) -> str:
prompt_vector = get_embedding(prompt)
# Check semantic cache first
cached_response, similarity = cache.lookup(prompt_vector)
if cached_response:
print(f"[CACHE HIT] Similarity: {similarity:.4f}")
return cached_response
# Fallback to main model on cache miss
print("[CACHE MISS] Requesting LLM response...")
llm_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}]
).choices[0].message.content
cache.store(prompt_vector, llm_response)
return llm_response
Architectural Considerations
Before deploying semantic caching to your production environment, consider these key implementation details:
1. Threshold Tuning
Setting your similarity threshold is a balancing act. Set it too high (e.g., 0.98), and you defeat the purpose of semantic caching by missing valid matches. Set it too low (e.g., 0.70), and your system might serve responses meant for entirely different questions (e.g., confusing "How do I upgrade?" with "How do I cancel?"). Test your threshold against real user query logs to find the right baseline.
2. Infrastructure Scaling
An in-memory list works well for lightweight scripts, but production workloads require specialized vector indices. Tools like Redis Vector Search, Qdrant, or Pgvector allow you to run sub-millisecond similarity searches across millions of cached queries.
3. Cache Invalidation
If your LLM answers depend on real-time data or policy updates, implement Time-To-Live (TTL) strategies or clear cache segments whenever underlying documentation changes to avoid serving stale answers.
About me
Tanmay builds AI agents and automation for businesses and is open to freelance projects. Invite readers to connect on LinkedIn.
Top comments (0)