Enterprise knowledge bases powered by Large Language Models (LLMs) are transformative, but the cost can become prohibitive at scale. In high-traffic environments, users often ask similar questions with slight variations in phrasing. Instead of paying for a new LLM inference for every unique string, semantic caching stores answers based on meaning rather than exact text matches. This approach can reduce API costs by 40–70% while maintaining low latency.
Why Exact-String Caching Fails
Traditional caching relies on deterministic keys. In search, "How do I reset my password?" and "What is the procedure for resetting credentials?" are distinct strings but semantically identical. If you cache the exact query, you miss the second request. Semantic caching bridges this gap by embedding queries into vector space, allowing the system to recognize intent similarity before hitting the expensive LLM.Architecture Overview
The semantic cache workflow involves three core components:- Embedding Model: Converts the user’s query into a high-dimensional vector.
- Vector Database: Stores previously seen queries and their corresponding LLM answers.
- Similarity Threshold: A cosine similarity score (e.g., 0.92) that determines if a cached answer is valid.
Implementation in Python
Below is a simplified implementation usingopenai for embeddings and chromadb as the vector store. In production, consider using dedicated vector databases like Pinecone, Weaviate, or Qdrant for better performance at scale.
import openai
import chromadb
import uuid
# Initialize clients
openai.api_key = "your-api-key"
db = chromadb.PersistentClient(path="./semantic_cache")
collection = db.get_or_create_collection(name="enterprise_search_cache")
def embed_text(text):
return openai.Embedding.create(input=[text], model="text-embedding-ada-002").data[0]["embedding"]
def semantic_cache_get_or_generate(query, llm_generate_fn, threshold=0.92):
# 1. Embed the incoming query
query_embedding = embed_text(query)
# 2. Search for similar cached queries
results = collection.query(
query_embeddings=[query_embedding],
n_results=1
)
# 3. Check similarity
if results['distances'][0][0] < 1 - threshold:
print("Cache HIT: Returning stored answer.")
return results['metadatas'][0][0]['answer']
# 4. Cache MISS: Call LLM
print("Cache MISS: Generating new answer.")
answer = llm_generate_fn(query)
# 5. Store in cache
collection.add(
ids=[str(uuid.uuid4())],
embeddings=[query_embedding],
metadatas=[{"query": query, "answer": answer}]
)
return answer
# Example usage
def mock_llm(question):
return "The password reset procedure is in Section 4.2 of the IT manual."
# Simulate two semantically similar questions
print(semantic_cache_get_or_generate("How do I reset my password?", mock_llm))
print(semantic_cache_get_or_generate("What is the procedure for resetting credentials?", mock_llm))