Spaces:
Sleeping
Sleeping
Download app/utils/cache.py from yabeskn/briga-core-api: direct link, hf CLI and curl.
- Browser
- Download file 5.09 kB
-
https://huggingface.co/spaces/yabeskn/briga-core-api/resolve/main/app/utils/cache.py
- Command line
-
hf download hf://spaces/yabeskn/briga-core-api/app/utils/cache.py
-
curl -L -o cache.py https://huggingface.co/spaces/yabeskn/briga-core-api/resolve/main/app/utils/cache.py
5.09 kB
| """In-memory cache with TTL for AI responses. | |
| Reduces API calls by ~60% and mitigates network latency between separated services. | |
| For hybrid deployment: Main API <-> AI Router communication. | |
| """ | |
| import hashlib | |
| import json | |
| import time | |
| from typing import Any, Dict, Optional, Tuple | |
| from loguru import logger | |
| class TTLCache: | |
| """Thread-safe in-memory cache with time-to-live (TTL) expiration. | |
| Used to cache AI responses between services to reduce: | |
| - Network latency between Main API and AI Router (~50-200ms saved) | |
| - API calls to external services (Gemini, Groq, OpenRouter) | |
| - Cold start impact on HF Spaces | |
| """ | |
| def __init__(self, default_ttl: int = 600, max_size: int = 1000): | |
| """ | |
| Args: | |
| default_ttl: Default TTL in seconds (default: 600 = 10 minutes) | |
| max_size: Maximum cache entries (prevents memory bloat) | |
| """ | |
| self._cache: Dict[str, Tuple[Any, float]] = {} | |
| self._default_ttl = default_ttl | |
| self._max_size = max_size | |
| self._hits = 0 | |
| self._misses = 0 | |
| def get(self, key: str) -> Optional[Any]: | |
| """Get a value from cache if it exists and hasn't expired.""" | |
| if key in self._cache: | |
| value, expiry = self._cache[key] | |
| if time.time() < expiry: | |
| self._hits += 1 | |
| logger.debug(f"[Cache] HIT: {key[:50]}...") | |
| return value | |
| else: | |
| # Expired - remove it | |
| del self._cache[key] | |
| self._misses += 1 | |
| return None | |
| def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None: | |
| """Set a value in cache with optional TTL override.""" | |
| # Evict oldest entries if at capacity | |
| if len(self._cache) >= self._max_size: | |
| self._evict_oldest() | |
| expiry = time.time() + (ttl or self._default_ttl) | |
| self._cache[key] = (value, expiry) | |
| logger.debug(f"[Cache] SET: {key[:50]}... (TTL: {ttl or self._default_ttl}s)") | |
| def _evict_oldest(self) -> None: | |
| """Remove the oldest 25% of entries when cache is full.""" | |
| if not self._cache: | |
| return | |
| # Sort by expiry time and remove oldest 25% | |
| sorted_keys = sorted(self._cache.keys(), key=lambda k: self._cache[k][1]) | |
| evict_count = max(1, len(sorted_keys) // 4) | |
| for key in sorted_keys[:evict_count]: | |
| del self._cache[key] | |
| logger.debug(f"[Cache] Evicted {evict_count} old entries") | |
| def clear(self) -> None: | |
| """Clear all cache entries.""" | |
| self._cache.clear() | |
| self._hits = 0 | |
| self._misses = 0 | |
| def stats(self) -> Dict[str, Any]: | |
| """Get cache statistics.""" | |
| total = self._hits + self._misses | |
| hit_rate = (self._hits / total * 100) if total > 0 else 0 | |
| return { | |
| "size": len(self._cache), | |
| "max_size": self._max_size, | |
| "hits": self._hits, | |
| "misses": self._misses, | |
| "hit_rate_percent": round(hit_rate, 1), | |
| "total_requests": total, | |
| } | |
| # Global cache instance for AI responses (10 min default TTL) | |
| ai_response_cache = TTLCache(default_ttl=600, max_size=500) | |
| def cached_ai_call(tier: str, prompt_hash: str, system_instruction_hash: str = "", mime_type: str = "") -> Optional[Tuple[str, int]]: | |
| """Get a cached AI response if available. | |
| Args: | |
| tier: AI tier (HIGH, MEDIUM, LOW) | |
| prompt_hash: Hash of the prompt | |
| system_instruction_hash: Hash of system instruction | |
| mime_type: Response MIME type (e.g. "application/json") | |
| Returns: | |
| Tuple of (response_text, tokens_used) or None if cache miss | |
| """ | |
| cache_key = f"ai:{tier}:{prompt_hash}:{system_instruction_hash}:{mime_type}" | |
| return ai_response_cache.get(cache_key) | |
| def cache_ai_response(tier: str, prompt_hash: str, system_instruction_hash: str, | |
| response: str, tokens_used: int, ttl: Optional[int] = None, mime_type: str = "") -> None: | |
| """Cache an AI response for future calls. | |
| Args: | |
| tier: AI tier | |
| prompt_hash: Hash of the prompt | |
| system_instruction_hash: Hash of system instruction | |
| response: The AI response text | |
| tokens_used: Number of tokens consumed | |
| ttl: Optional TTL override in seconds | |
| mime_type: Response MIME type (e.g. "application/json") | |
| """ | |
| cache_key = f"ai:{tier}:{prompt_hash}:{system_instruction_hash}:{mime_type}" | |
| ai_response_cache.set(cache_key, (response, tokens_used), ttl) | |
| def get_ai_cache_stats() -> Dict[str, Any]: | |
| """Get AI cache statistics for health monitoring.""" | |
| return ai_response_cache.stats() | |
| def hash_prompt(prompt: str, system_instruction: Optional[str] = None, mime_type: str = "") -> str: | |
| """Create a deterministic hash of prompt + system instruction for caching.""" | |
| combined = f"{prompt}:{system_instruction or ''}:{mime_type}" | |
| return hashlib.md5(combined.encode()).hexdigest()[:16] | |