812. Answer repeat questions from a semantic cache
Why it matters Gateways such as GPTCache and many LLM proxies use a similarity threshold cache to cut repeat-query cost.
A semantic cache saves LLM cost by reusing an earlier answer when a new prompt means the same thing, judged by embedding cosine similarity.
Write semantic_cache(events, threshold). events is a list of (embedding, answer_if_miss) pairs processed in order, starting with an empty cache. For each event, compute the cosine similarity between its embedding and every cached embedding. If the best similarity is >= threshold, it is a hit: return that cached answer (ties: the earliest cached entry). Otherwise it is a miss: return answer_if_miss and add (embedding, answer_if_miss) to the cache.
Return (outputs, hits) where outputs is the list of returned answers and hits is the number of hits.
def semantic_cache(events, threshold)Example 1
Input: semantic_cache([([1.0, 0.0], 'A'), ([0.99, 0.1], 'B'), ([0.0, 1.0], 'C')], 0.95)
Output: (['A', 'A', 'C'], 1)
Example 2
Input: events = [([1.0, 0.0], 'A'), ([2.0, 0.0], 'B')], threshold = 0.999
Output: (['A', 'A'], 1)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Normalise embeddings once when you store them.
Hint 2
Track the best similarity and its index; only a strictly larger score replaces the best, which keeps the earliest on ties.
Hint 3
Only misses are added to the cache.
Common mistakes
- Comparing raw dot products, which favours long vectors.
- Adding hits to the cache too, which fills it with duplicates.
Understand the idea
Normalise every embedding so a dot product is the cosine. A new prompt close enough to a cached one reuses its answer; otherwise it becomes a new cache entry. The threshold trades cost savings against wrong reuse.
[2, 0] points the same way as [1, 0], cosine 1, so it hits and returns 'A'.
hit if max cosine >= threshold, else insert