Spaces:
Running on T4
Running on T4
Download AI-coach-agent/src/ai_coach/cache.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 5.27 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/AI-coach-agent/src/ai_coach/cache.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/AI-coach-agent/src/ai_coach/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/AI-coach-agent/src/ai_coach/cache.py
5.27 kB
| """Response cache: identical session + prompt version + model -> no API call. | |
| Only LLM notes that passed the guardrails are cached. Entries expire after a TTL, and any prompt edit, | |
| guardrail change or model change produces a different key, so stale wording is never served. | |
| A damaged or unreadable cache is a miss, never an error: the app must keep working without it. | |
| """ | |
| from __future__ import annotations | |
| import contextlib | |
| import hashlib | |
| import logging | |
| import sqlite3 | |
| import threading | |
| import time | |
| from collections.abc import Iterator | |
| from pathlib import Path | |
| from pydantic import ValidationError | |
| from .schemas import CoachNote | |
| log = logging.getLogger(__name__) | |
| SECONDS_PER_DAY = 86_400 | |
| def cache_key(version: str, model: str, canonical_input: str) -> str: | |
| """`version` should combine every behaviour-changing version (prompt hash, guardrails version).""" | |
| return hashlib.sha256(f"{version}\x00{model}\x00{canonical_input}".encode()).hexdigest() | |
| class ResponseCache: | |
| def __init__(self, path: Path | str, ttl_days: float): | |
| self.path = Path(path) | |
| self.ttl_s = ttl_days * SECONDS_PER_DAY | |
| self._lock = threading.Lock() | |
| self._ready = False | |
| self._init() | |
| def _connect(self) -> Iterator[sqlite3.Connection]: | |
| db = sqlite3.connect(self.path, timeout=5) | |
| try: | |
| with db: | |
| yield db | |
| finally: | |
| db.close() | |
| def _init(self) -> None: | |
| try: | |
| self.path.parent.mkdir(parents=True, exist_ok=True) | |
| with self._lock, self._connect() as db: | |
| db.execute("CREATE TABLE IF NOT EXISTS notes (key TEXT PRIMARY KEY, created REAL, note TEXT)") | |
| db.execute("CREATE TABLE IF NOT EXISTS failures (key TEXT PRIMARY KEY, expires REAL, reason TEXT)") | |
| self._ready = True | |
| except (sqlite3.Error, OSError) as exc: | |
| log.warning("response cache unavailable (%s); continuing without it", exc) | |
| def get(self, key: str, now: float | None = None) -> CoachNote | None: | |
| if not self._ready: | |
| return None | |
| now = time.time() if now is None else now | |
| try: | |
| with self._lock, self._connect() as db: | |
| row = db.execute("SELECT created, note FROM notes WHERE key = ?", (key,)).fetchone() | |
| except sqlite3.Error as exc: | |
| log.warning("cache read failed: %s", exc) | |
| return None | |
| if row is None or now - row[0] > self.ttl_s: | |
| return None | |
| try: | |
| return CoachNote.model_validate_json(row[1]) | |
| except ValidationError: | |
| log.warning("cache row no longer matches the CoachNote schema; dropping it") | |
| self.delete(key) | |
| return None | |
| def put(self, key: str, note: CoachNote, now: float | None = None) -> None: | |
| if not self._ready: | |
| return | |
| now = time.time() if now is None else now | |
| try: | |
| with self._lock, self._connect() as db: | |
| db.execute("INSERT OR REPLACE INTO notes VALUES (?, ?, ?)", (key, now, note.model_dump_json())) | |
| except sqlite3.Error as exc: | |
| log.warning("cache write failed: %s", exc) | |
| def put_failure(self, key: str, reason: str, ttl_s: float, now: float | None = None) -> None: | |
| """Remember for a short time that this exact request ended in the rule-based note (negative cache).""" | |
| if not self._ready or ttl_s <= 0: | |
| return | |
| now = time.time() if now is None else now | |
| try: | |
| with self._lock, self._connect() as db: | |
| db.execute("INSERT OR REPLACE INTO failures VALUES (?, ?, ?)", (key, now + ttl_s, reason)) | |
| except sqlite3.Error as exc: | |
| log.warning("cache failure write failed: %s", exc) | |
| def get_failure(self, key: str, now: float | None = None) -> str | None: | |
| """The reason of a remembered failure that has not expired, else None.""" | |
| if not self._ready: | |
| return None | |
| now = time.time() if now is None else now | |
| try: | |
| with self._lock, self._connect() as db: | |
| row = db.execute("SELECT expires, reason FROM failures WHERE key = ?", (key,)).fetchone() | |
| except sqlite3.Error as exc: | |
| log.warning("cache failure read failed: %s", exc) | |
| return None | |
| return row[1] if row and row[0] > now else None | |
| def delete(self, key: str) -> None: | |
| if not self._ready: | |
| return | |
| try: | |
| with self._lock, self._connect() as db: | |
| db.execute("DELETE FROM notes WHERE key = ?", (key,)) | |
| except sqlite3.Error as exc: | |
| log.warning("cache delete failed: %s", exc) | |
| def purge_expired(self, now: float | None = None) -> int: | |
| if not self._ready: | |
| return 0 | |
| now = time.time() if now is None else now | |
| try: | |
| with self._lock, self._connect() as db: | |
| db.execute("DELETE FROM failures WHERE expires <= ?", (now,)) | |
| return db.execute("DELETE FROM notes WHERE ? - created > ?", (now, self.ttl_s)).rowcount | |
| except sqlite3.Error as exc: | |
| log.warning("cache purge failed: %s", exc) | |
| return 0 | |