Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (9)
90 unmodified lines91929390 unmodified lines# -----------------------------------------------------------------------------# Set to `development` to enable extra debug logging in some services.ENV=production90 unmodified lines91929394959697989910010110290 unmodified lines# -----------------------------------------------------------------------------# Set to `development` to enable extra debug logging in some services.ENV=production# -----------------------------------------------------------------------------# Redis Inference Cache (Issue #131)# -----------------------------------------------------------------------------# When true, cache DistilBERT classifications and sentence-transformer embeddings.USE_REDIS_CACHE=falseREDIS_URL=redis://127.0.0.1:6379/0REDIS_CACHE_TTL_SECONDS=3600
63 unmodified lines64656667686946 unmodified lines116117118119120121266 unmodified lines38838939039139239363 unmodified linesfrom backend.services.rag_service import RagServicefrom backend.services.sla_engine import SLAEngine, compute_sla_breach_at, get_sla_policyfrom backend.services.semantic_duplicate_service import SemanticDuplicateService# ---------------------------------------------------------------------------46 unmodified linesdef classify_ticket_text(text: str) -> dict:"""Run the local classifier cascade with ONNX as the offline fallback path."""try:classification_v3_res = classifier_v3.predict(text)if "error" not in classification_v3_res:266 unmodified linesasync def lifespan(app: FastAPI):"""Load all models at startup."""print("[Startup] Loading AI models ...")try:classifier_service.load()except FileNotFoundError as e:63 unmodified lines6465666768697046 unmodified lines117118119120121122123124125126127128129130131132266 unmodified lines39940040140240340440540640740863 unmodified linesfrom backend.services.rag_service import RagServicefrom backend.services.sla_engine import SLAEngine, compute_sla_breach_at, get_sla_policyfrom backend.services.semantic_duplicate_service import SemanticDuplicateServicefrom backend.services.redis_cache import redis_cache# ---------------------------------------------------------------------------46 unmodified linesdef classify_ticket_text(text: str) -> dict:"""Run the local classifier cascade with ONNX as the offline fallback path."""cached = redis_cache.get_classification(text)if cached:return cachedresult = _classify_ticket_text_uncached(text)redis_cache.set_classification(text, result)return resultdef _classify_ticket_text_uncached(text: str) -> dict:try:classification_v3_res = classifier_v3.predict(text)if "error" not in classification_v3_res:266 unmodified linesasync def lifespan(app: FastAPI):"""Load all models at startup."""print("[Startup] Loading AI models ...")try:redis_cache.connect()except Exception as e:print(f"[WARNING] Redis cache not available: {e}")try:classifier_service.load()except FileNotFoundError as e:
16 unmodified lines17181920212216 unmodified linesslowapi>=0.1.9supabase==2.22.4storage3==2.22.4pytestpytest-asynciohttpx16 unmodified lines1718192021222316 unmodified linesslowapi>=0.1.9supabase==2.22.4storage3==2.22.4redis>=5.0.0pytestpytest-asynciohttpx
100 unmodified lines101102103104105106107108109110111112100 unmodified linesdef generate_embedding(self, text: str) -> list[float] | None:"""Generate a 384-d embedding for the provided ticket text."""self.load()if not self.is_available():return Noneembedding = self.model.encode(text, convert_to_tensor=False, normalize_embeddings=True)return [float(value) for value in embedding.tolist()]def _build_result(self,100 unmodified lines101102103104105106107108109110111112113114115116117118119120100 unmodified linesdef generate_embedding(self, text: str) -> list[float] | None:"""Generate a 384-d embedding for the provided ticket text."""from backend.services.redis_cache import redis_cachecached = redis_cache.get_embedding(text)if cached is not None:return cachedself.load()if not self.is_available():return Noneembedding = self.model.encode(text, convert_to_tensor=False, normalize_embeddings=True)values = [float(value) for value in embedding.tolist()]redis_cache.set_embedding(text, values)return valuesdef _build_result(self,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Redis cache for AI inference (classification + embeddings)."""
from __future__ import annotations
import hashlibimport jsonimport loggingimport osfrom typing import Any
logger = logging.getLogger(__name__)
CLASSIFICATION_PREFIX = "helpdesk:cls:"EMBEDDING_PREFIX = "helpdesk:emb:"
def _truthy(value: str | None) -> bool: return (value or "").strip().lower() in {"1", "true", "yes", "on"}
def _text_key(prefix: str, text: str) -> str: digest = hashlib.md5(text.strip().lower().encode("utf-8")).hexdigest() return f"{prefix}{digest}"
class RedisInferenceCache: """Optional Redis layer for DistilBERT classifications and ST embeddings."""
def __init__(self) -> None: self._client: Any | None = None self.enabled = _truthy(os.getenv("USE_REDIS_CACHE")) self.allow_degraded = _truthy(os.getenv("ALLOW_DEGRADED_STARTUP")) self.ttl_seconds = int(os.getenv("REDIS_CACHE_TTL_SECONDS", "3600"))
@property def available(self) -> bool: return self.enabled and self._client is not None
def connect(self) -> None: if not self.enabled: logger.info("[RedisCache] Disabled (USE_REDIS_CACHE=false)") return
try: import redis
url = os.getenv("REDIS_URL", "redis://127.0.0.1:6379/0") client = redis.from_url(url, decode_responses=True, socket_connect_timeout=2) client.ping() self._client = client logger.info("[RedisCache] Connected") except Exception as error: self._client = None message = f"[RedisCache] Unavailable: {error}" if self.allow_degraded: logger.warning("%s — bypassing cache", message) else: raise RuntimeError(message) from error
def get_classification(self, text: str) -> dict | None: if not self.available: return None try: raw = self._client.get(_text_key(CLASSIFICATION_PREFIX, text)) return json.loads(raw) if raw else None except Exception as error: logger.warning("[RedisCache] classification get failed: %s", error) return None
def set_classification(self, text: str, payload: dict) -> None: if not self.available: return try: self._client.setex( _text_key(CLASSIFICATION_PREFIX, text), self.ttl_seconds, json.dumps(payload), ) except Exception as error: logger.warning("[RedisCache] classification set failed: %s", error)
def get_embedding(self, text: str) -> list[float] | None: if not self.available: return None try: raw = self._client.get(_text_key(EMBEDDING_PREFIX, text)) if not raw: return None values = json.loads(raw) return [float(v) for v in values] except Exception as error: logger.warning("[RedisCache] embedding get failed: %s", error) return None
def set_embedding(self, text: str, embedding: list[float]) -> None: if not self.available: return try: self._client.setex( _text_key(EMBEDDING_PREFIX, text), self.ttl_seconds, json.dumps(embedding), ) except Exception as error: logger.warning("[RedisCache] embedding set failed: %s", error)
redis_cache = RedisInferenceCache()65 unmodified lines6667686970717273747565 unmodified linesGenerate a 384-dimensional embedding vector for the given text.Returns None if the model isn't loaded."""if not self.model:return Nonetry:return self.model.encode(text).tolist()except Exception as e:logger.error(f"[SemanticDuplicate] Embedding error: {e}")return None65 unmodified lines66676869707172737475767778798081828365 unmodified linesGenerate a 384-dimensional embedding vector for the given text.Returns None if the model isn't loaded."""from backend.services.redis_cache import redis_cachecached = redis_cache.get_embedding(text)if cached is not None:return cachedif not self.model:return Nonetry:embedding = self.model.encode(text).tolist()redis_cache.set_embedding(text, embedding)return embeddingexcept Exception as e:logger.error(f"[SemanticDuplicate] Embedding error: {e}")return None
265 unmodified lines266267268269270271272265 unmodified lines@pytest.fixture(autouse=True)def mock_ai_services():import backend.main as mainwith patch.object(main.classifier_service, "predict") as mock_v1_predict, \265 unmodified lines266267268269270271272273274275276277278279280265 unmodified lines@pytest.fixture(autouse=True)def mock_ai_services(request):if request.node.fspath.basename in {"test_redis_cache.py","test_semantic_duplicates.py","test_auth_cookie.py",}:yieldreturnimport backend.main as mainwith patch.object(main.classifier_service, "predict") as mock_v1_predict, \
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Tests for Redis inference cache (issue #131)."""
from unittest.mock import MagicMock, patch
import pytest
from backend.services.redis_cache import RedisInferenceCache, _text_key, CLASSIFICATION_PREFIX, EMBEDDING_PREFIX
@pytest.fixture(autouse=True)def reset_env(monkeypatch): monkeypatch.delenv("USE_REDIS_CACHE", raising=False) monkeypatch.delenv("REDIS_URL", raising=False) monkeypatch.delenv("ALLOW_DEGRADED_STARTUP", raising=False) monkeypatch.delenv("REDIS_CACHE_TTL_SECONDS", raising=False)
def test_text_key_is_stable(): assert _text_key(CLASSIFICATION_PREFIX, "Hello") == _text_key(CLASSIFICATION_PREFIX, " hello ") assert _text_key(CLASSIFICATION_PREFIX, "A") != _text_key(EMBEDDING_PREFIX, "A")
def test_cache_disabled_by_default(): cache = RedisInferenceCache() cache.connect() assert cache.available is False assert cache.get_classification("ticket") is None
def test_classification_roundtrip(monkeypatch): monkeypatch.setenv("USE_REDIS_CACHE", "true") client = MagicMock() client.ping.return_value = True store = {}
def setex(key, ttl, value): store[key] = value
client.get.side_effect = lambda key: store.get(key) client.setex.side_effect = setex
cache = RedisInferenceCache() with patch("redis.from_url", return_value=client): cache.connect()
payload = {"category": "Billing", "priority": "High"} assert cache.get_classification("payment failed") is None cache.set_classification("payment failed", payload) assert cache.get_classification("payment failed") == payload
def test_embedding_roundtrip(monkeypatch): monkeypatch.setenv("USE_REDIS_CACHE", "true") client = MagicMock() client.ping.return_value = True store = {}
client.get.side_effect = lambda key: store.get(key) client.setex.side_effect = lambda key, ttl, value: store.update({key: value})
cache = RedisInferenceCache() with patch("redis.from_url", return_value=client): cache.connect()
vector = [0.1, 0.2, 0.3] cache.set_embedding("duplicate ticket", vector) assert cache.get_embedding("duplicate ticket") == vector
def test_degraded_startup_bypasses_redis(monkeypatch): monkeypatch.setenv("USE_REDIS_CACHE", "true") monkeypatch.setenv("ALLOW_DEGRADED_STARTUP", "1")
cache = RedisInferenceCache() with patch("redis.from_url", side_effect=ConnectionError("down")): cache.connect()
assert cache.available is False assert cache.get_embedding("x") is None16 unmodified lines17181920212216 unmodified linesslowapi>=0.1.9supabase==2.22.4storage3==2.22.4pytestpytest-asynciohttpx16 unmodified lines1718192021222316 unmodified linesslowapi>=0.1.9supabase==2.22.4storage3==2.22.4redis>=5.0.0pytestpytest-asynciohttpx
backend/.env.example+9
backend/main.py+15
backend/requirements.txt+1
backend/services/duplicate_service.py+9-1
backend/services/redis_cache.pyAdded+108
backend/services/semantic_duplicate_service.py+9-1
backend/tests/conftest.py+9-1
backend/tests/test_redis_cache.pyAdded+79
requirements.txt+1