Spaces:
Paused
Paused
G Rohit Sudarsen
Claude Sonnet 5
Retry bypasses the cache; only the final chosen version gets cached
3349053 Download cache.py from KaarTechUK/KaartechUK_SLM: direct link, hf CLI and curl.
- Browser
- Download file 8.09 kB
-
https://huggingface.co/spaces/KaarTechUK/KaartechUK_SLM/resolve/main/cache.py
- Command line
-
hf download hf://spaces/KaarTechUK/KaartechUK_SLM/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/KaarTechUK/KaartechUK_SLM/resolve/main/cache.py
8.09 kB
| """ | |
| Real self-hosted semantic cache - RedisVL's SemanticCache backed by a | |
| Redis Stack instance running inside this same container (see the | |
| Dockerfile and start.sh). Replaces db.py's old Postgres-cosine-similarity | |
| cache (a real, working full-table-scan-in-Python implementation, kept in | |
| db.py's schema for now as unused history, not dropped). | |
| Chosen over Redis Cloud / Redis LangCache (a real, current, fully-managed | |
| REST product - confirmed live via redis.io before building this) | |
| specifically so every cached question/answer stays inside this Space's | |
| own container boundary instead of leaving to an external managed | |
| service - the same real boundary discipline this deployment already | |
| applies to retrieved document content (see redact.py's own docstring). | |
| The real cost of that choice: LangCache's managed vector index is | |
| presumably faster to operate at scale than a self-run one, and this | |
| cache is now ephemeral (resets on container restart) rather than | |
| Postgres-durable - the same real tradeoff this deployment's own | |
| in-memory daily-usage tracker (main.py's _usage_by_client) already | |
| accepts, just newly true for the semantic cache too. | |
| Same degrade-gracefully contract as db.py/retrieval.py throughout: if | |
| Redis isn't reachable (still starting up per start.sh's own readiness | |
| wait, or genuinely down), every function here returns None/no-ops | |
| rather than raising - /predict must keep working whether or not the | |
| cache is available. | |
| """ | |
| import json | |
| import os | |
| REDIS_URL = os.environ.get("REDIS_URL", "redis://127.0.0.1:6379") | |
| # Same real embedding model retrieval.py already uses for the knowledge- | |
| # graph vector search - not because the cache's query-to-query similarity | |
| # space needs to match retrieval's query-to-chunk space (it doesn't, these | |
| # are two independent indexes), but so this container isn't holding two | |
| # different embedding models in memory for no real reason. | |
| CACHE_EMBED_MODEL = "nomic-ai/nomic-embed-text-v1.5" | |
| # High bar deliberately, matching db.py's old CACHE_SIMILARITY_THRESHOLD | |
| # (0.96 cosine similarity) - caching means reusing a stored answer | |
| # verbatim for a "close enough" question, a much stricter real | |
| # requirement than retrieval.py's MIN_SIMILARITY=0.5 relevance floor. | |
| # RedisVL's distance_threshold is COSINE DISTANCE (0 = identical, 2 = | |
| # opposite), not similarity, so this is the real conversion | |
| # (1 - similarity) for normalized vectors, not a separately-tuned number. | |
| CACHE_SIMILARITY_THRESHOLD = float(os.environ.get("CACHE_SIMILARITY_THRESHOLD", "0.96")) | |
| CACHE_DISTANCE_THRESHOLD = round(1 - CACHE_SIMILARITY_THRESHOLD, 6) | |
| _cache = None | |
| _unavailable = False # sticky - once init fails, stop retrying every request this container's life | |
| def _get_cache(): | |
| global _cache, _unavailable | |
| if _cache is not None or _unavailable: | |
| return _cache | |
| try: | |
| from redisvl.extensions.cache.llm import SemanticCache | |
| from redisvl.utils.vectorize import HFTextVectorizer | |
| # Pinned to CPU deliberately, same real reasoning as retrieval.py's | |
| # own embedding model - this container's GPU is already shared | |
| # between the 3.3B-param LLM and its LoRA adapter, and a real CUDA | |
| # OOM from an unpinned embedding model has already happened once | |
| # in this exact deployment (see retrieval.py's own comment). | |
| vectorizer = HFTextVectorizer(model=CACHE_EMBED_MODEL, trust_remote_code=True, device="cpu") | |
| _cache = SemanticCache( | |
| name="slm_query_cache", | |
| redis_url=REDIS_URL, | |
| distance_threshold=CACHE_DISTANCE_THRESHOLD, | |
| vectorizer=vectorizer, | |
| ) | |
| print(f"[cache] Connected to self-hosted Redis at {REDIS_URL}.", flush=True) | |
| except Exception as exc: | |
| print(f"[cache] Redis Stack unavailable ({exc}) - semantic cache disabled for this container's life.", flush=True) | |
| _unavailable = True | |
| _cache = None | |
| return _cache | |
| def available(): | |
| return _get_cache() is not None | |
| def set_similarity_threshold(similarity): | |
| """Real live update, called from main.py's POST /admin/config when | |
| the cache_similarity_threshold key changes. RedisVL bakes | |
| distance_threshold into the SemanticCache object at construction, not | |
| into each .check() call, so there's no per-call knob to just flip - | |
| this updates the module-level threshold globals and drops the | |
| singleton, so the next real cache_lookup()/cache_store() rebuilds a | |
| fresh SemanticCache against the SAME Redis index ("slm_query_cache") | |
| with the new threshold. Real, honest limitation worth stating: this | |
| does not re-embed or re-score entries already stored under the old | |
| threshold - it only changes the bar future lookups are compared | |
| against.""" | |
| global CACHE_SIMILARITY_THRESHOLD, CACHE_DISTANCE_THRESHOLD, _cache | |
| CACHE_SIMILARITY_THRESHOLD = float(similarity) | |
| CACHE_DISTANCE_THRESHOLD = round(1 - CACHE_SIMILARITY_THRESHOLD, 6) | |
| _cache = None | |
| def cache_lookup(question): | |
| """Real semantic lookup - returns the cached {answer, reasoning, | |
| sources, grounding, verification} dict on a real high-similarity | |
| hit, else None. Never raises - a Redis problem just means no cache | |
| this request, same as caching being disabled entirely.""" | |
| cache = _get_cache() | |
| if cache is None: | |
| return None | |
| try: | |
| results = cache.check(question, num_results=1) | |
| except Exception as exc: | |
| print(f"[cache] lookup failed: {exc} - continuing without it.", flush=True) | |
| return None | |
| if not results: | |
| return None | |
| # Real, confirmed behaviour (checked against RedisVL's own docs before | |
| # writing this, not assumed): metadata round-trips through Redis as a | |
| # JSON string, not an already-parsed dict - .store() below hands it a | |
| # real Python dict, .check() hands back the same thing serialized. | |
| raw_meta = results[0].get("metadata") | |
| if isinstance(raw_meta, str): | |
| try: | |
| meta = json.loads(raw_meta) | |
| except (TypeError, ValueError): | |
| meta = {} | |
| else: | |
| meta = raw_meta or {} | |
| return { | |
| "answer": results[0].get("response"), | |
| "reasoning": meta.get("reasoning"), | |
| "sources": meta.get("sources"), | |
| "grounding": meta.get("grounding"), | |
| "verification": meta.get("verification"), | |
| } | |
| def cache_store(question, answer, reasoning, sources, grounding, verification=None): | |
| cache = _get_cache() | |
| if cache is None: | |
| return | |
| try: | |
| cache.store( | |
| prompt=question, | |
| response=answer, | |
| metadata={ | |
| "reasoning": reasoning, | |
| "sources": sources, | |
| "grounding": grounding, | |
| "verification": verification, | |
| }, | |
| ) | |
| except Exception as exc: | |
| print(f"[cache] store failed: {exc}", flush=True) | |
| def cache_replace(question, answer, reasoning, sources, grounding, verification=None): | |
| """Real 'this is now the answer for this question' - used by | |
| main.py's POST /cache/commit when the user settles on a retried | |
| version rather than the one that (may have) already auto-cached | |
| itself on the first real generation. Drops any existing entry for | |
| this exact question first, then stores the new one - RedisVL's | |
| SemanticCache.store() has no confirmed dedup-on-identical-prompt | |
| behaviour (checked directly against RedisVL's own docs before | |
| writing this, not assumed), so calling plain cache_store() again | |
| here could leave two near-identical entries competing for future | |
| lookups instead of the chosen one winning outright.""" | |
| cache = _get_cache() | |
| if cache is None: | |
| return | |
| try: | |
| existing = cache.check(question, num_results=1) | |
| if existing: | |
| entry_id = existing[0].get("entry_id") | |
| if entry_id: | |
| cache.drop(ids=[entry_id]) | |
| except Exception as exc: | |
| print(f"[cache] drop-before-replace failed: {exc} - storing the new version anyway.", flush=True) | |
| cache_store(question, answer, reasoning, sources, grounding, verification) | |