A support assistant gets the same questions in many wordings, and every model call costs money and a second of latency. Build the cache that serves a stored answer when a new query means the same thing as a cached one, without ever serving another tenant's answer, an answer from an older prompt, an expired answer or one built on a document that has since changed. Then pick its similarity threshold from labelled data.
Embeddings are given as lists of floats; no model is called. Similarity is cosine similarity, , taken as when either vector is all zeros. Times are plain numbers from a simulated clock.
Implement class SemanticCache(threshold, ttl):
put(tenant, version, embedding, answer, sources, now): store an entry and return its id. Ids are 0, 1, 2, ... in the order entries are stored. version names the model and prompt version that produced the answer; sources is a list of document ids the answer cited. An entry stored at time now is live while the clock is strictly below now + ttl.lookup(tenant, version, embedding, now): among live entries with the same tenant and the same version, find the one with the highest similarity to embedding (an exact tie goes to the larger id). If that similarity is >= threshold, it is a hit: return {"answer": ..., "entry": id, "similarity": s} with s rounded to 4 decimals. Otherwise it is a miss: return None.invalidate(doc_id, now): delete every entry whose sources contain doc_id, live or not, and return how many of the deleted entries were live at now.stats(): {"hits": h, "misses": m} counted over all lookups so far.Implement two functions for choosing the threshold. pairs is a list of (similarity, same_intent) tuples: the similarity of a new query to its nearest cached query, and whether the cached answer would have been right for it.
threshold_report(pairs, threshold): a pair is a hit when similarity >= threshold. Return {"hit_rate": hits / len(pairs), "false_hit_rate": wrong hits / hits}, where a wrong hit has same_intent false, rounded to 4 decimals. A rate whose denominator is 0 is 0.0.choose_threshold(pairs, candidates, max_false_hit_rate): the smallest candidate whose unrounded false-hit rate is <= max_false_hit_rate, returned as {"threshold": t, "hit_rate": ..., "false_hit_rate": ...}, or None if no candidate qualifies.