|
| 1 | +"""Semantic cache for LLM responses, built on Moss. |
| 2 | +
|
| 3 | +A normal cache keys on the exact text of a request, so two ways of asking the |
| 4 | +same thing ("what are your hours?" / "when do you open?") miss and you pay the |
| 5 | +model twice. A *semantic* cache keys on meaning: embed the question, look up the |
| 6 | +nearest one you've already answered, and if it's close enough, return the stored |
| 7 | +answer without calling the model. |
| 8 | +
|
| 9 | +The whole thing is the SemanticCache class below. The one knob that matters is |
| 10 | +the similarity threshold. |
| 11 | +""" |
| 12 | + |
| 13 | +import asyncio |
| 14 | +import os |
| 15 | +import time |
| 16 | + |
| 17 | +from dotenv import load_dotenv |
| 18 | +from openai import AsyncOpenAI |
| 19 | + |
| 20 | +from moss import MossClient, DocumentInfo, QueryOptions |
| 21 | + |
| 22 | +load_dotenv() |
| 23 | + |
| 24 | +# cosine similarity above which a cached answer is "close enough" to reuse. |
| 25 | +# too low -> you answer questions people didn't quite ask; too high -> you miss. |
| 26 | +THRESHOLD = 0.92 |
| 27 | + |
| 28 | +moss = MossClient( |
| 29 | + project_id=os.getenv("MOSS_PROJECT_ID"), |
| 30 | + project_key=os.getenv("MOSS_PROJECT_KEY"), |
| 31 | +) |
| 32 | +llm = AsyncOpenAI() |
| 33 | + |
| 34 | + |
| 35 | +class SemanticCache: |
| 36 | + """A tiny vector index of past questions -> answers, queried by meaning.""" |
| 37 | + |
| 38 | + def __init__(self, index): |
| 39 | + self.index = index |
| 40 | + |
| 41 | + async def ask(self, question: str) -> tuple[str, bool]: |
| 42 | + # 1. look for the closest question we've already answered |
| 43 | + hit = await self.index.query(question, QueryOptions(top_k=1)) |
| 44 | + if hit.docs and hit.docs[0].score >= THRESHOLD: |
| 45 | + return hit.docs[0].metadata["answer"], True # cache hit — no LLM call |
| 46 | + |
| 47 | + # 2. miss: ask the model once |
| 48 | + resp = await llm.chat.completions.create( |
| 49 | + model="gpt-4o-mini", |
| 50 | + messages=[{"role": "user", "content": question}], |
| 51 | + ) |
| 52 | + answer = resp.choices[0].message.content |
| 53 | + |
| 54 | + # 3. remember it so any wording of it is instant next time |
| 55 | + await self.index.add_docs( |
| 56 | + [DocumentInfo(id=question, text=question, metadata={"answer": answer})] |
| 57 | + ) |
| 58 | + return answer, False |
| 59 | + |
| 60 | + |
| 61 | +async def main(): |
| 62 | + # a fresh in-memory session index acts as the cache for this run |
| 63 | + index = await moss.session("qa-cache") |
| 64 | + cache = SemanticCache(index) |
| 65 | + |
| 66 | + # the 2nd question means the same as the 1st, phrased differently -> cache hit |
| 67 | + questions = [ |
| 68 | + "What are your opening hours?", |
| 69 | + "when do you open?", |
| 70 | + "How do I reset my password?", |
| 71 | + ] |
| 72 | + for q in questions: |
| 73 | + t = time.perf_counter() |
| 74 | + answer, hit = await cache.ask(q) |
| 75 | + ms = (time.perf_counter() - t) * 1000 |
| 76 | + tag = "HIT " if hit else "MISS" |
| 77 | + print(f"[{tag} {ms:7.1f} ms] {q}\n -> {answer.strip()[:90]}\n") |
| 78 | + |
| 79 | + |
| 80 | +if __name__ == "__main__": |
| 81 | + asyncio.run(main()) |
0 commit comments