Cache LLM Completions by Hashing the Prompt in Python
A simple in-memory cache that stores LLM completions keyed by a SHA-256 hash of the prompt to avoid recomputing identical requests.
Python code
37 linesimport hashlib
import json
class PromptCache:
def __init__(self):
self.cache = {}
def _hash_prompt(self, prompt: str) -> str:
return hashlib.sha256(prompt.encode("utf-8")).hexdigest()
def get(self, prompt: str) -> str | None:
key = self._hash_prompt(prompt)
return self.cache.get(key)
def set(self, prompt: str, completion: str) -> None:
key = self._hash_prompt(prompt)
self.cache[key] = completion
def stats(self) -> dict:
return {
"cache_size": len(self.cache),
"keys": list(self.cache.keys()),
}
if __name__ == "__main__":
cache = PromptCache()
prompt = "Explain quantum computing in one sentence."
completion = "Quantum computing uses qubits to process information in superposition."
cache.set(prompt, completion)
retrieved = cache.get(prompt)
miss = cache.get("Different prompt entirely")
print("Retrieved:", retrieved)
print("Miss result:", miss)
print("Stats:", json.dumps(cache.stats(), indent=2))
Output
Retrieved: Quantum computing uses qubits to process information in superposition.
Miss result: None
Stats: {
"cache_size": 1,
"keys": ["0c438ff931e402efafe9c8d63e1d31a27b259eaa1b1377a62e93e7df22b3c5cd"]
}
How it works
The _hash_prompt method computes a SHA-256 digest of the prompt string, which uniquely identifies the exact text. The get and set methods use this hash as the dictionary key, so identical prompts return the cached completion with O(1) lookup. Storing hashes instead of full prompts reduces memory and avoids storing sensitive prompt text. The cache is a plain dict, safe for single-threaded use; for concurrent access you'd add a lock or use functools.lru_cache. Stats exposes the current cache size and keys for debugging.
Common mistakes
- Forgetting to encode the string to UTF-8 before hashing (TypeError).
- Assuming the cache is persistent across program restarts — it's only in-memory.
- Not normalizing whitespace, so semantically identical prompts with different spacing get different hashes.
Variations
- Use `functools.lru_cache` on a wrapper function for automatic caching with maxsize limit.
- Persist the cache to disk (e.g., JSON or SQLite) to reuse across runs.
Real-world use cases
- Avoid duplicate OpenAI API calls when the same user prompt is sent repeatedly in a web app.
- Speed up batch processing scripts that process many identical prompt templates with different variables filled in.
- Provide instant response for frequent FAQ-style queries without hitting the LLM provider on each request.
Sponsored
More from AI & LLM integration patterns
- 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
- How to Append Few-Shot Examples to a Prompt in Python easy
Keep learning
Related tutorials and quizzes for this topic.