Knowledge Bases

Semantic Caching for Enterprise Search

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:
  1. Embedding Model: Converts the user’s query into a high-dimensional vector.
  2. Vector Database: Stores previously seen queries and their corresponding LLM answers.
  3. Similarity Threshold: A cosine similarity score (e.g., 0.92) that determines if a cached answer is valid.
If the similarity between the new query and a cached query exceeds the threshold, the system returns the cached answer instantly. If not, it invokes the LLM, stores the result, and serves the response.

Implementation in Python

Below is a simplified implementation using openai 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))

Tuning the Similarity Threshold

The threshold is the most critical hyperparameter. A threshold too low (e.g., 0.80) may return irrelevant answers, damaging user trust. A threshold too high (e.g., 0.98) reduces cache hit rates, increasing costs. Start with 0.92 and monitor hit rates and user feedback. Use A/B testing to determine the optimal balance for your specific domain.

Handling Evolving Knowledge

Enterprise knowledge bases change. If the password reset policy updates, the cache must be invalidated. Implement TTL (Time-To-Live) on cache entries or tag entries with version numbers. When the source document updates, purge related cache entries to prevent serving stale information.

Conclusion

Semantic caching is a low-hanging fruit for optimizing LLM-based search systems. By leveraging vector similarity to serve frequent questions from cache, you significantly reduce latency and costs. Start with a prototype, tune your similarity threshold, and implement robust invalidation strategies to build a resilient, cost-efficient enterprise knowledge base.

Share: