Semantic cache lab
Build the first working lookup-and-store path
Page 3 advances one concrete tenant-scoped semantic answer cache: explain the decision, run the code, inspect failure, measure evidence, and keep only what is ready to ship.
Before you start
Why this matters
Predict the first successful artifact ID or key this happy-path fixture should print for the tenant-scoped semantic answer cache. Which intermediate value proves the core path ran, not just that the process started?
1Learn the idea
Read
Build focus
Now implement the shortest complete path for the tenant-scoped semantic answer cache. Keep every intermediate value available for inspection; hiding it behind a heavy framework would make this lesson harder to reason about. The output should be deterministic for the fixture (or schema-deterministic when a model is involved). Only after this path works should you generalize.
Implement lookup before the LLM call and store after a successful safe answer. Print hit/miss and the winning similarity. Keep an offline numpy fixture so tests do not need a giant vector DB.
The artifact's user-facing goal is specific: reuse answers for paraphrases only when tenant, policy key, and similarity thresholds all match. Its accepted input is normalized question, tenant, policy key, corpus version, and embedding vector. Those statements are intentionally narrower than “build an AI system.” Narrow scope lets us inspect every input and expected result, and it prevents a toy result from being presented as a production claim. System shape for this chapter: a request normalizer derives policy fields, an embedding model maps the question to a vector, a tenant-scoped cache retrieves the nearest entry, and a threshold plus exact policy-key match decides hit or miss before the normal LLM path stores a versioned result. Keep model calls behind adapters, keep authorization and validation in deterministic code, and carry stable IDs and versions through every response. That separation lets you decide whether a bad result came from input handling, retrieval, inference, validation, or deployment. This page's job is the implementation step: now implement the shortest complete path for the tenant-scoped semantic answer cache. Setup baseline for the chapter (run once per machine, not secrets in git):
python -m venv .venv && source .venv/bin/activate
pip install numpy
export CACHE_THRESHOLD=0.92 CACHE_TTL_SECONDS=3600
If hardware or a hosted provider differs, preserve the interface and expected behavior. Do not present provider syntax as universal—when a vendor adapter is unavoidable, keep it behind a thin boundary and test with a fake first. The deliverable is not “it ran once”; it is a reproducible artifact another developer can inspect, including expected output and one deliberate failure related to false hit that reuses the wrong policy answer. Operationally, write down the owner of this stage, the command you ran, the observed output, and the next page's dependency on that output. If you cannot point to a file, fixture, metric, or config key, the stage is not done. Prefer small, reviewable increments: one contract, one path, one metric, one failure, one gate. When tradeoffs appear—latency versus quality, hit rate versus false hits, local privacy versus cloud quality—record both numbers instead of moving the threshold until the report looks green. The chapter ships only when evidence for false-hit rate 0 on high-risk intents in the test set, with measured hit rate and token savings and a rehearsed recovery path exist beside semantic cache with TTL, versioned keys, and SEMANTIC_CACHE_ENABLED kill switch.
Read
Run the example
Save this as lesson.py and run python3 lesson.py. Prefer the standard library or the pinned packages from the setup block so the example stays reproducible.
import numpy as np
def cosine(a,b): return float(a@b/(np.linalg.norm(a)*np.linalg.norm(b)))
a=np.array([1.0,0.0]); b=np.array([0.97,0.24]); c=np.array([0.0,1.0])
print(round(cosine(a,b),3), round(cosine(a,c),3))
Expected output: high similarity for paraphrase-like vectors and low for orthogonal. Exact floating-point formatting may vary slightly, but the asserted behavior must not. Read the output as evidence about this stage, not merely proof that the interpreter started.
Read
Debug the stage
Print intermediate IDs, scores, or statuses before the user-visible answer. Fluent wrong outputs usually start as a wrong intermediate. At the implementation stage, save the smallest failing fixture beside the expected result. Change one cause at a time and rerun the exact command printed above; that makes the repair reviewable and keeps this chapter's progressive artifact reproducible.
Read
Evaluate before continuing
After the happy path works, freeze the fixture as a regression oracle before adding queues, caches, or fancy UX. For this implementation page, preserve the fixture and result as evidence for the next page. Label observations separately from conclusions: a passing assertion establishes the behavior it names, while broader usefulness requires the chapter's full evaluation set and stated operating limits. Primary metrics for the chapter remain false-hit rate 0 on high-risk intents in the test set, with measured hit rate and token savings.
Continue learning · glossary & guides
- [ ] Can I narrate every intermediate value?
- [ ] Is the fixture deterministic or schema-deterministic?
- [ ] Did I avoid framework behavior I cannot yet explain?
- [ ] Does the path still serve: reuse answers for paraphrases only when tenant, policy key, and similarity thresholds all match?
Glossary: semantic cache · Glossary: model routing · Glossary: cosine similarity