Skip to content
Semantic Caching for LLMs: Cut Your Token Bill in Python — ContentBuffer guide

Semantic Caching for LLMs: Cut Your Token Bill in Python

K
Kodetra Technologies··10 min read Intermediate

Summary

Build a semantic cache that reuses answers for similar prompts and slashes LLM API costs.

On June 26, 2026, CNBC ran a story that landed hard across every engineering channel: the era of tokenmaxxing is over. Uber admitted it burned through its entire annual AI budget in four months. Lindy moved 100% of its traffic off Claude to a cheaper model because, in its CEO's words, it was "a matter of survival for the business." The message for everyone shipping LLM features is blunt: spend-at-all-costs is finished, and cost per request is now a first-class engineering metric.

Most of the advice you'll see is about routing: send easy work to a cheap model, escalate the hard stuff to a frontier model. That helps. But there's a cheaper lever that a lot of teams skip, and it's the one that pays off first in production: don't call the model at all when you already answered the same question a minute ago.

Exact-match caching catches almost nothing, because real users never phrase things identically. "How do I reset my password?" and "how can I reset the password" are the same request with a 0% string overlap that matters. Semantic caching fixes that. You embed the prompt, compare it to prompts you've already answered, and if something is close enough, you return the stored answer for free. This guide builds one from scratch in Python, verifies it runs, and shows the exact cost math.

What you'll build

A small, dependency-light SemanticCache class you can drop in front of any chat completion call. By the end you'll have:

  • An embedder-agnostic cache that works with OpenAI embeddings or a fully offline local embedder (no API key needed to test).
  • A cosine-similarity lookup with a tunable hit threshold, FIFO eviction, and optional TTL.
  • A one-line ask() wrapper that checks the cache before spending tokens.
  • A reproducible demo plus the real cost math at 2026 API prices.

It's about 60 lines of real code. The hard part isn't the code; it's choosing the threshold and knowing when not to cache. We'll cover both.

Prerequisites

  • Python 3.10+ (the examples use modern type hints).
  • pip install openai numpy for the production version.
  • An OPENAI_API_KEY if you want real embeddings. The offline demo needs only numpy.
  • Basic familiarity with calling a chat completions endpoint. Any OpenAI-compatible provider works (OpenAI, DeepSeek, Z.ai/GLM, Together, etc.) by setting base_url.

How semantic caching actually works

A normal cache uses the prompt string as the key. A semantic cache uses the meaning of the prompt as the key. The pipeline is four steps:

  1. Embed the incoming prompt into a vector with an embedding model.
  2. Search your stored prompt vectors for the most similar one using cosine similarity.
  3. Compare that best similarity score against a threshold (e.g. 0.92).
  4. Decide: above threshold, return the stored answer (a cache hit, $0); below it, call the model, then store the new prompt and answer.

Cosine similarity measures the angle between two vectors and ranges from -1 to 1. For text embeddings, near-identical meanings land close to 1.0, unrelated text lands near 0. The single most important knob you own is the threshold: too low and you serve wrong answers; too high and you never get a hit. We'll tune it deliberately later.

Step 1: The embedder

The cache doesn't care where vectors come from, so we keep the embedder pluggable. The production choice is OpenAI's text-embedding-3-small: 1536 dimensions, and at roughly $0.02 per million tokens it is so cheap that the embedding call is a rounding error next to the chat call it saves.

import os
import numpy as np
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
EMBED_MODEL = "text-embedding-3-small"   # 1536-dim, ~$0.02 / 1M tokens

def embed(text: str) -> list[float]:
    resp = client.embeddings.create(model=EMBED_MODEL, input=[text])
    return resp.data[0].embedding

def cosine(a, b) -> float:
    a, b = np.asarray(a, np.float32), np.asarray(b, np.float32)
    return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))

If you want to run everything with no API key (useful for tests and CI), here's a deterministic local embedder built from hashed character trigrams. It's lexical, not semantic, so it only catches close rewordings, but it lets the whole demo run offline with just numpy:

import re, hashlib
import numpy as np

DIM = 256
def embed_local(text: str) -> list[float]:
    v = np.zeros(DIM, dtype=np.float32)
    t = re.sub(r"\s+", " ", text.lower().strip())
    grams = [t[i:i+3] for i in range(max(len(t) - 2, 1))]
    for g in grams:
        h = int(hashlib.md5(g.encode()).hexdigest(), 16) % DIM
        v[h] += 1.0
    n = np.linalg.norm(v)
    return (v / n).tolist() if n else v.tolist()

Step 2: The SemanticCache class

This is the core. It stores each entry as a prompt, its vector, the answer, and a timestamp. get() embeds the query, finds the most similar non-expired entry, and returns the answer only if the best score clears the threshold. set() adds an entry and evicts the oldest one when full.

import time
import numpy as np

class SemanticCache:
    def __init__(self, embed_fn, threshold=0.92, max_size=5000, ttl=None):
        self.embed_fn, self.threshold = embed_fn, threshold
        self.max_size, self.ttl = max_size, ttl
        self._entries = []            # dicts: prompt, vec, answer, ts
        self.hits = self.misses = 0

    def _expired(self, e):
        return self.ttl is not None and (time.time() - e["ts"]) > self.ttl

    def get(self, prompt: str):
        q = self.embed_fn(prompt)
        best, best_s = None, -1.0
        for e in self._entries:
            if self._expired(e):
                continue
            s = cosine(q, e["vec"])
            if s > best_s:
                best, best_s = e, s
        if best is not None and best_s >= self.threshold:
            self.hits += 1
            return best["answer"], best_s
        self.misses += 1
        return None

    def set(self, prompt: str, answer: str):
        if len(self._entries) >= self.max_size:
            self._entries.pop(0)      # FIFO eviction
        self._entries.append({
            "prompt": prompt, "vec": self.embed_fn(prompt),
            "answer": answer, "ts": time.time(),
        })

    @property
    def hit_rate(self):
        total = self.hits + self.misses
        return self.hits / total if total else 0.0

The linear scan in get() is fine up to a few thousand entries. Past that you'll want a real vector index; see the Next steps section.

Step 3: Wrap your model call

Now put the cache in front of the chat call. The contract is simple: ask the cache first, and only hit the API on a miss. The CHAT_MODEL below is whatever you already use; with the new GPT-5.6 tiers, Terra is a sensible cost-conscious default, but the wrapper is model-agnostic.

CHAT_MODEL = os.environ.get("CHAT_MODEL", "gpt-5.6-terra")

def ask(cache: SemanticCache, prompt: str) -> str:
    cached = cache.get(prompt)
    if cached is not None:
        answer, sim = cached
        print(f"cache HIT  (sim={sim:.3f})  $0.00")
        return answer

    resp = client.chat.completions.create(
        model=CHAT_MODEL,
        messages=[{"role": "user", "content": prompt}],
    )
    answer = resp.choices[0].message.content
    cache.set(prompt, answer)
    return answer

cache = SemanticCache(embed, threshold=0.92)   # use embed_local offline
print(ask(cache, "How do I reset my password?"))
print(ask(cache, "how can I reset the password"))   # served from cache

Step 4: Run it and watch the savings

Here's a self-contained demo you can run with zero API keys using the local embedder. It replays a small support-style workload and reports hits, misses, and dollars saved at GPT-5.6 Terra pricing ($2.50 input / $15 output per 1M tokens):

def fake_llm(prompt):                 # stand-in for a real chat call
    return f"[answer to: {prompt[:40]}]"

cache = SemanticCache(embed_local, threshold=0.85)
IN_PRICE, OUT_PRICE = 2.50, 15.0      # $ per 1M tokens (GPT-5.6 Terra)
in_tok, out_tok = 600, 300            # avg tokens per real call

queries = [
    "How do I reset my password?",
    "How can I reset my password?",        # paraphrase
    "What is your refund policy?",
    "Tell me about your refund policy.",   # paraphrase
    "How do I reset the password?",        # paraphrase
    "What time zone is the server in?",    # new
    "How do I change my email address?",   # new
    "Can you tell me your refund policy?", # paraphrase
]

saved = 0
for q in queries:
    r = cache.get(q)
    if r is None:
        cache.set(q, fake_llm(q)); tag = "MISS -> called LLM"
    else:
        _, sim = r; saved += 1; tag = f"HIT  (sim={sim:.3f}) -> cache"
    print(f"{tag:38s} | {q}")

cost = (in_tok/1e6)*IN_PRICE + (out_tok/1e6)*OUT_PRICE
print(f"\nrequests={len(queries)} hits={cache.hits} "
      f"hit_rate={cache.hit_rate:.0%}")
print(f"cost without cache: ${cost*len(queries):.5f}")
print(f"cost with cache:    ${cost*cache.misses:.5f}")
print(f"savings:            {saved/len(queries):.0%}")

Actual output from this exact script:

MISS -> called LLM                     | How do I reset my password?
HIT  (sim=0.868) -> cache              | How can I reset my password?
MISS -> called LLM                     | What is your refund policy?
MISS -> called LLM                     | Tell me about your refund policy.
HIT  (sim=0.857) -> cache              | How do I reset the password?
MISS -> called LLM                     | What time zone is the server in?
MISS -> called LLM                     | How do I change my email address?
MISS -> called LLM                     | Can you tell me your refund policy?

requests=8 hits=2 hit_rate=25%
cost without cache: $0.04800
cost with cache:    $0.03600
savings:            25%

Look closely at the misses. The local trigram embedder caught "reset my/the password" but missed "Tell me about your refund policy" versus "What is your refund policy" because those share few characters. That's the expected limit of a lexical embedder, and it's exactly why production uses a real embedding model: swap embed_local for embed and those refund-policy paraphrases also become hits, pushing the hit rate well past 50% on realistic traffic.

A worked real-world example: an FAQ endpoint

Picture a support assistant taking 50,000 questions a day. Support traffic is famously repetitive: people ask the same dozen things in a hundred different ways. With a real embedding model and a 0.92 threshold, a 55% semantic hit rate is realistic for this kind of workload.

At GPT-5.6 Terra pricing and 600 input / 300 output tokens per answer, one real call costs (600/1e6 x $2.50) + (300/1e6 x $15) = $0.00525. Run the numbers per day:

MetricNo cacheSemantic cache (55% hit)
Model calls / day50,00022,500
Chat cost / day$262.50$118.13
Embedding cost / day*$0.00~$0.30
Total / day$262.50~$118.43
Total / month$7,875~$3,553

*Embedding cost: 50,000 prompts x ~30 tokens x $0.02 / 1M ≈ $0.03/day for chat-side embeds; the table rounds up generously. The cache turns a ~$7.9k/month line item into ~$3.6k, and the embedding overhead is statistical noise. That's the tokenmaxxing-is-over story made concrete: same product, less than half the bill, no model downgrade.

Choosing the threshold

The threshold is the safety dial. With text-embedding-3-small, these ranges are good starting points; always confirm against your own traffic with a small labeled set.

ThresholdBehaviorUse it when
0.97 - 0.99Near-exact only; very few hitsAnswers are sensitive or personalized
0.92 - 0.95Catches genuine paraphrases; safe defaultGeneral FAQ / support / docs Q&A
0.85 - 0.90Aggressive; risks merging distinct intentsHigh-volume, low-stakes, tolerant content
below 0.85Frequent wrong hitsAlmost never

Tune empirically: collect 100 real prompts, label which pairs should share an answer, then pick the highest threshold that keeps false hits at zero. Re-check it whenever you change embedding models.

Common pitfalls and gotchas

  • Caching personalized or stateful answers. "What's my account balance?" must never be served from another user's cached reply. Namespace the cache per user, or simply skip caching for prompts that depend on private state.
  • Threshold set by vibes. A wrong cache hit is worse than a cache miss, because it returns a confidently incorrect answer. Validate the threshold against labeled pairs before shipping, and start conservative.
  • Ignoring system prompts and parameters. The same user text with a different system prompt, temperature, or tool set can warrant a different answer. Fold those into the cache key (embed the user text but bucket entries by a hash of the system prompt + model + temperature).
  • Caching non-deterministic or time-sensitive content. "What's the weather today?" or "latest news" should never be cached, or only with a short TTL. Use the ttl argument for anything that goes stale.
  • Embedding model drift. If you change the embedding model or its dimensions parameter, old vectors are no longer comparable. Version your cache and rebuild on model change.
  • Unbounded memory. The in-memory list works for a single process, but it dies on restart and won't scale across workers. For production, back it with Redis (store vectors) or a vector database so all workers share one cache.
  • Embedding cost denial. It's tiny, but it isn't zero. If your prompts are huge, truncate to the first few hundred tokens before embedding; the meaning that matters for cache matching is usually early.
  • Linear scan at scale. Comparing against every stored vector is O(n) per query. Past a few thousand entries, move to an approximate nearest-neighbor index (FAISS, hnswlib, pgvector) to keep lookups sub-millisecond.

Quick reference

ItemValue / note
Embedding modeltext-embedding-3-small (1536-dim, ~$0.02 / 1M tok)
Similarity metriccosine (range -1 to 1; ~1.0 = same meaning)
Safe default threshold0.92 with text-embedding-3-small
EvictionFIFO via list.pop(0); swap for LRU if needed
TTLSet ttl seconds for time-sensitive answers
When NOT to cachePersonalized, stateful, or fast-changing answers
Scale-out backendRedis or pgvector + ANN index (FAISS/hnswlib)
Cost leverAvoided chat calls x (in x in_price + out x out_price)

Next steps

  • Swap the in-memory list for Redis so every worker shares one cache and it survives restarts.
  • Add an ANN index (FAISS or hnswlib) once you cross a few thousand entries to keep lookups fast.
  • Add per-user namespacing and a deny-list of prompt patterns that should always bypass the cache.
  • Log hit rate and dollars saved as metrics so you can prove the savings and tune the threshold over time.
  • Pair the cache with model routing (cheap model first, escalate on hard tasks) for compounding savings, the full anti-tokenmaxxing stack.

Semantic caching is the rare optimization that's cheap to build, safe when you respect the gotchas, and visible on the invoice within a day. In a month where every team is being told to cut AI spend without cutting capability, it's the first lever to pull.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get