Spaces:
Paused
Paused
Download core/cache.py from 3SCError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 8.14 kB
-
https://huggingface.co/spaces/3SCError404/nexus/resolve/main/core/cache.py
- Command line
-
hf download hf://spaces/3SCError404/nexus/core/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/3SCError404/nexus/resolve/main/core/cache.py
8.14 kB
| import json | |
| import hashlib | |
| from typing import Any, Optional | |
| import redis.asyncio as redis | |
| from core.config import get_settings | |
| settings = get_settings() | |
| # Initialize a dedicated Redis client for search caching | |
| # This uses the CACHE_REDIS_URL to separate it from Arq (Upstash) | |
| _redis_client: Optional[redis.Redis] = None | |
| def get_redis_client() -> redis.Redis: | |
| """Singleton getter for the async Redis client.""" | |
| global _redis_client | |
| if _redis_client is None: | |
| _redis_client = redis.from_url( | |
| settings.CACHE_REDIS_URL, | |
| encoding="utf-8", | |
| decode_responses=True | |
| ) | |
| return _redis_client | |
| def generate_cache_key(prefix: str, workspace_id: str, query: str, filters: dict = None) -> str: | |
| """Generates a deterministic cache key based on query parameters.""" | |
| filter_str = json.dumps(filters, sort_keys=True) if filters else "{}" | |
| payload = f"{workspace_id}:{query}:{filter_str}".lower().strip() | |
| query_hash = hashlib.sha256(payload.encode()).hexdigest()[:16] | |
| return f"cache:search:{prefix}:{workspace_id}:{query_hash}" | |
| async def get_cached_search(key: str) -> Optional[Any]: | |
| """Retrieves a cached search result from Redis.""" | |
| try: | |
| client = get_redis_client() | |
| data = await client.get(key) | |
| if data: | |
| return json.loads(data) | |
| except Exception: | |
| # Fail safe - if Redis is down, just return None to trigger fresh search | |
| pass | |
| return None | |
| async def set_cached_search(key: str, data: Any, ttl: int = 3600) -> None: | |
| """Stores a search result in Redis with a Time-To-Live.""" | |
| try: | |
| client = get_redis_client() | |
| await client.set(key, json.dumps(data), ex=ttl) | |
| except Exception: | |
| # Fail safe | |
| pass | |
| async def delete_cached_search(key: str) -> None: | |
| """Removes a specific cache key from Redis.""" | |
| try: | |
| client = get_redis_client() | |
| await client.delete(key) | |
| except Exception: | |
| pass | |
| # --- Generic Object Caching for API responses --- | |
| async def get_cached_object(key: str) -> Optional[Any]: | |
| """Retrieves a JSON-serialized object from Redis.""" | |
| try: | |
| client = get_redis_client() | |
| data = await client.get(key) | |
| if data: | |
| return json.loads(data) | |
| except Exception: | |
| pass | |
| return None | |
| async def set_cached_object(key: str, data: Any, ttl: int = 300) -> None: | |
| """Stores a JSON-serializable object in Redis with TTL.""" | |
| try: | |
| client = get_redis_client() | |
| await client.set(key, json.dumps(data), ex=ttl) | |
| except Exception: | |
| pass | |
| async def invalidate_cache(key: str) -> None: | |
| """Explicitly purges a cache key.""" | |
| try: | |
| client = get_redis_client() | |
| await client.delete(key) | |
| except Exception: | |
| pass | |
| async def delete_by_pattern(pattern: str) -> None: | |
| """Purges all keys matching a specific glob pattern using SCAN for safety.""" | |
| try: | |
| client = get_redis_client() | |
| cursor = 0 | |
| while True: | |
| cursor, keys = await client.scan(cursor=cursor, match=pattern, count=100) | |
| if keys: | |
| await client.delete(*keys) | |
| if cursor == 0: | |
| break | |
| except Exception: | |
| pass | |
| class SemanticCacheManager: | |
| """ | |
| Manages semantic LLM response caching using pgvector. | |
| Bypasses entirely the LangGraph orchestration if an idential query was asked before. | |
| PARTITION KEY: (workspace_id, role_class) | |
| - role_class is normalized to 'staff' or 'customer' to prevent cross-persona cache leaks. | |
| """ | |
| def _normalize_role_class(user_role: str = "", is_agent: bool = False) -> str: | |
| """Normalize any role string to a strict partition class.""" | |
| role_lower = str(user_role).lower() | |
| if is_agent or "3sc" in role_lower or "agent" in role_lower or "lead" in role_lower or role_lower == "admin": | |
| return "staff" | |
| return "customer" | |
| async def check_cache(workspace_id: str, query: str, is_agent: bool = False, user_role: str = "customer_user", user_id: Optional[str] = None) -> Optional[str]: | |
| from core.llm import get_embeddings | |
| from core.database import async_session_factory | |
| from models.nexus_semantic_cache import NexusSemanticCache | |
| from sqlalchemy import select, update, and_, func | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| role_class = SemanticCacheManager._normalize_role_class(user_role, is_agent) | |
| try: | |
| # OPTIMIZATION: Skip embedding generation for very short queries (greetings, etc.) | |
| if len(query.strip()) < 4: | |
| return None | |
| embedder = get_embeddings() | |
| query_vector = await embedder.aembed_query(query) | |
| async with async_session_factory() as db: | |
| from sqlalchemy import text | |
| stmt = ( | |
| select( | |
| NexusSemanticCache, | |
| NexusSemanticCache.query_embedding.cosine_distance(query_vector).label("distance") | |
| ) | |
| .where( | |
| and_( | |
| NexusSemanticCache.workspace_id == workspace_id, | |
| NexusSemanticCache.is_agent == (role_class == "staff"), | |
| NexusSemanticCache.user_role == role_class, | |
| NexusSemanticCache.created_at >= (func.now() - text("INTERVAL '6 hours'")) | |
| ) | |
| ) | |
| .order_by("distance") | |
| .limit(1) | |
| ) | |
| res = await db.execute(stmt) | |
| row = res.first() | |
| # Check for > 0.90 similarity (distance < 0.10) - slightly more permissive | |
| if row and row.distance < 0.10: | |
| cache_hit = row[0] | |
| # Update hit count | |
| await db.execute( | |
| update(NexusSemanticCache) | |
| .where(NexusSemanticCache.id == cache_hit.id) | |
| .values(hit_count=NexusSemanticCache.hit_count + 1) | |
| ) | |
| await db.commit() | |
| logger.info(f"🧠 Semantic Cache HIT [{role_class}]: ws={workspace_id[:8]} q='{query[:40]}'") | |
| return cache_hit.response_text | |
| except Exception as e: | |
| logger.error(f"Semantic Cache Check Failed: {str(e)}") | |
| return None | |
| async def set_cache(workspace_id: str, user_id: str, query: str, response_text: str, is_agent: bool = False, user_role: str = "customer_user"): | |
| from core.llm import get_embeddings | |
| from core.database import async_session_factory | |
| from models.nexus_semantic_cache import NexusSemanticCache | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| role_class = SemanticCacheManager._normalize_role_class(user_role, is_agent) | |
| try: | |
| # OPTIMIZATION: Skip embedding generation for very short queries | |
| if len(query.strip()) < 10: | |
| return | |
| embedder = get_embeddings() | |
| query_vector = await embedder.aembed_query(query) | |
| async with async_session_factory() as db: | |
| cache_entry = NexusSemanticCache( | |
| workspace_id=workspace_id, | |
| user_id=user_id, # Keep user_id in record for audit, but not lookup | |
| is_agent=(role_class == "staff"), | |
| user_role=role_class, | |
| query_text=query, | |
| query_embedding=query_vector, | |
| response_text=response_text | |
| ) | |
| db.add(cache_entry) | |
| await db.commit() | |
| logger.info(f"🧠 Semantic Cache SET [{role_class}]: ws={workspace_id[:8]} q='{query[:40]}'") | |
| except Exception as e: | |
| logger.error(f"Semantic Cache Set Failed: {str(e)}") | |