How to Build a Simple Semantic Cache for Similar Prompts in Python
Mock a semantic cache that finds the closest matching prompt using word-overlap similarity and returns cached results above a threshold.
Python code
37 linesprompt_cache = [
"What is the capital of France?",
"How does recursion work?",
"Best practices for Python logging?",
"Explain binary search in one line.",
"How to reverse a string in Python?"
]
def normalize(text):
return " ".join(text.lower().split())
def similarity(a, b):
a_words = set(normalize(a).split())
b_words = set(normalize(b).split())
if not a_words or not b_words:
return 0.0
return len(a_words & b_words) / max(len(a_words), len(b_words))
def semantic_lookup(query, threshold=0.4):
query_norm = normalize(query)
best_match = None
best_score = 0.0
for cached in prompt_cache:
score = similarity(query_norm, cached)
if score > best_score:
best_score = score
best_match = cached
if best_score >= threshold:
return best_match, best_score
return None, 0.0
if __name__ == "__main__":
test_query = "What is the capital city of France?"
match, score = semantic_lookup(test_query)
print(f"Query: {test_query!r}")
print(f"Best match: {match!r}")
print(f"Similarity score: {score:.2f}")
Output
Query: 'What is the capital city of France?'
Best match: 'What is the capital of France?'
Similarity score: 0.75
How it works
This example simulates a semantic cache without external ML libraries. The normalize function lowercases text and collapses whitespace so punctuation and case differences don't hurt matching. similarity computes Jaccard-style overlap between word sets, dividing shared words by the larger set size to penalize mismatched lengths. semantic_lookup scans the cache, keeps the highest score, and only returns a hit when it clears a threshold. This is a lightweight stand-in for embedding-based semantic search used in production LLM systems.
Common mistakes
- Forgetting to normalize punctuation and case before comparing words
- Using a fixed threshold that's too high for short, sparse prompts
- Returning partial matches with low confidence instead of None to indicate a cache miss
Variations
- Replace word-set similarity with TF-IDF cosine similarity from sklearn
- Store a compact hash like SHA-256 of the normalized prompt for exact-duplicate detection first
Real-world use cases
- Serving repeated LLM API calls from a cache to cut cost and latency.
- Deduplicating user question paraphrases in a support bot.
- Reducing rate-limit pressure by matching near-identical requests in a gateway.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.