Spaces:
Sleeping
Sleeping
File size: 5,094 Bytes
b613c13 | 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 | """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]
|