Spaces:
Paused
Paused
File size: 8,144 Bytes
b7980f7 ca7df66 235f8ef f70ee44 b7980f7 bc1617c b7980f7 bc1617c b7980f7 06f7381 b7980f7 7e2936d b7980f7 bc1617c b7980f7 ad4fe35 b7980f7 bc1617c b7980f7 be01d40 06f7381 bc1617c 06f7381 be01d40 b7980f7 2d0e9e3 b7980f7 bc1617c b7980f7 06f7381 b7980f7 bc1617c b7980f7 ad4fe35 b7980f7 2d0e9e3 bc1617c b7980f7 2d0e9e3 b7980f7 bc1617c b7980f7 bc1617c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | 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.
"""
@staticmethod
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"
@staticmethod
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
@staticmethod
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)}")
|