Savings from a Semantic Cache
Problem Statement
A semantic cache serves a query from cache when a prior query's similarity exceeds a threshold, saving the cost of an LLM call. Given queries with pairwise similarity to earlier queries, compute total cost saved.
Background
Process queries in order. Query i is a cache hit if any earlier query j < i has similarity[i][j] >= threshold; then it costs nothing and saves cost dollars. Otherwise it is a miss: it costs cost and is added to the cache. The first query is always a miss. Return total dollars saved (num_hits * cost), rounded to 4 decimals.
Your Task
def cache_savings(similarity, threshold, cost):
- similarity: n x n nested list; similarity[i][j].
- Return dollars saved.
Input Format
- similarity (nested list), threshold (float), cost (float).
Output Format
- A float rounded to 4 decimals.
Sample
sim = [[1,0,0],[0.95,1,0],[0.1,0.2,1]]
print(cache_savings(sim, 0.9, 0.01))
Output:
0.01
Example
sim = [[1,0,0],[0.95,1,0],[0.1,0.2,1]] print(cache_savings(sim, 0.9, 0.01))
0.01
- Query 0 (Index 0): As the first query, there are no prior queries to compare against, so it is a miss. It is added to the cache.
- Query 1 (Index 1): Compare with Query 0. The similarity is . Since (the threshold), this is a hit. No cost is incurred, and the query is not added to the cache.
- Query 2 (Index 2): Compare with prior queries in the cache (only Query 0 exists). The similarity with Query 0 is . Since , it is a miss. It costs and is added to the cache.
- Calculate Total Savings: There was 1 hit. The savings are calculated as .
- The final output is 0.01
Constraints
- Query i hits if any j<i has similarity[i][j] >= threshold.
- First query is always a miss; hits save
costeach. - Round the total to 4 decimals.