BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / LLM inference and serving35 of 36 in topic

812. Answer repeat questions from a semantic cache

MediumLLM inference and serving Pro

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.

Functiondef 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.

Worked example

[2, 0] points the same way as [1, 0], cosine 1, so it hits and returns 'A'.

hit if max cosine >= threshold, else insert
Topics
LLM inference and serving
Similar questions
  • Generate one token at a time with a KV cacheMedium
  • Allocate KV cache memory in pages, like vLLMMedium
  • Verify a draft model's guesses in speculative decodingMedium
  • Is decoding memory-bound? A roofline estimateMedium
All LLM inference and serving problems
Report
812 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def semantic_cache(events, threshold):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS