Spaces:
Build error
Build error
Download services/query_layer/app/config/multi_tier_cache.py from LuckyMod/intentforge: direct link, hf CLI and curl.
- Browser
- Download file 9.61 kB
-
https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/services/query_layer/app/config/multi_tier_cache.py
- Command line
-
hf download hf://spaces/LuckyMod/intentforge/services/query_layer/app/config/multi_tier_cache.py
-
curl -L -o multi_tier_cache.py https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/services/query_layer/app/config/multi_tier_cache.py
9.61 kB
| """ | |
| Intent Engine - Multi-Tier Cache for Search Results | |
| Implements 3-tier caching strategy for optimal performance: | |
| - L1: In-memory LRU cache (10ms access) - Top 1000 queries | |
| - L2: Redis cache (50ms access) - Recent queries (24h) | |
| - L3: Qdrant semantic cache (100ms access) - Similar queries | |
| Usage: | |
| cache = MultiTierCache() | |
| result = await cache.get(query) | |
| if not result: | |
| result = await search(query) | |
| await cache.set(query, result) | |
| """ | |
| import hashlib | |
| import logging | |
| from collections import OrderedDict | |
| from datetime import datetime, timedelta | |
| from typing import Any | |
| logger = logging.getLogger(__name__) | |
| class LRUCache: | |
| """L1: In-memory LRU cache for hot queries""" | |
| def __init__(self, capacity: int = 1000, ttl_seconds: int = 300): | |
| self.capacity = capacity | |
| self.ttl_seconds = ttl_seconds | |
| self.cache: OrderedDict[str, tuple[Any, datetime]] = OrderedDict() | |
| self.hits = 0 | |
| self.misses = 0 | |
| def get(self, key: str) -> Any | None: | |
| """Get item from cache""" | |
| if key not in self.cache: | |
| self.misses += 1 | |
| return None | |
| value, expiry = self.cache[key] | |
| # Check if expired | |
| if datetime.now() > expiry: | |
| del self.cache[key] | |
| self.misses += 1 | |
| return None | |
| # Move to end (most recently used) | |
| self.cache.move_to_end(key) | |
| self.hits += 1 | |
| return value | |
| def set(self, key: str, value: Any) -> None: | |
| """Set item in cache""" | |
| expiry = datetime.now() + timedelta(seconds=self.ttl_seconds) | |
| if key in self.cache: | |
| self.cache.move_to_end(key) | |
| self.cache[key] = (value, expiry) | |
| # Evict oldest if over capacity | |
| while len(self.cache) > self.capacity: | |
| self.cache.popitem(last=False) | |
| 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 { | |
| "hits": self.hits, | |
| "misses": self.misses, | |
| "hit_rate": f"{hit_rate:.1f}%", | |
| "size": len(self.cache), | |
| "capacity": self.capacity, | |
| } | |
| class MultiTierCache: | |
| """ | |
| Multi-tier caching for search results. | |
| Tiers: | |
| - L1: In-memory LRU (10ms) - Most popular queries | |
| - L2: Redis (50ms) - Recent queries | |
| - L3: Qdrant semantic (100ms) - Similar queries | |
| """ | |
| def __init__(self, redis_client=None): | |
| # L1: In-memory cache (1000 queries, 5 min TTL) | |
| self.l1_cache = LRUCache(capacity=1000, ttl_seconds=300) | |
| # L2: Redis cache (will be set from external) | |
| self.l2_redis = redis_client | |
| # L2 Redis keys | |
| self.redis_prefix = "search:cache:" | |
| self.redis_ttl = 3600 # 1 hour | |
| # L3: Qdrant semantic cache | |
| self.l3_qdrant = None | |
| self.l3_threshold = 0.95 # Similarity threshold | |
| logger.info("MultiTierCache initialized (L1: LRU, L2: Redis, L3: Qdrant)") | |
| def set_redis_client(self, redis_client) -> None: | |
| """Set Redis client for L2 cache""" | |
| self.l2_redis = redis_client | |
| logger.info("L2 Redis cache connected") | |
| def set_qdrant_client(self, qdrant_client) -> None: | |
| """Set Qdrant client for L3 semantic cache""" | |
| self.l3_qdrant = qdrant_client | |
| logger.info("L3 Qdrant semantic cache connected") | |
| def _generate_cache_key(self, query: str) -> str: | |
| """Generate consistent cache key from query""" | |
| # Normalize query | |
| normalized = query.lower().strip() | |
| # Generate hash | |
| key_hash = hashlib.md5(normalized.encode()).hexdigest()[:16] | |
| return f"{self.redis_prefix}{key_hash}" | |
| async def get(self, query: str) -> Any | None: | |
| """ | |
| Get search results from cache (multi-tier). | |
| Tries L1 → L2 → L3 in order, returns first match. | |
| Promotes results to higher tiers on hit. | |
| """ | |
| cache_key = self._generate_cache_key(query) | |
| # L1: Check in-memory cache (fastest) | |
| if (result := self.l1_cache.get(cache_key)) is not None: | |
| logger.debug(f"L1 cache HIT: {query[:50]}") | |
| return result | |
| # L2: Check Redis cache | |
| if self.l2_redis: | |
| try: | |
| cached = await self.l2_redis.get(cache_key) | |
| if cached: | |
| import json | |
| result = json.loads(cached) | |
| # Promote to L1 | |
| self.l1_cache.set(cache_key, result) | |
| logger.debug(f"L2 cache HIT: {query[:50]}") | |
| return result | |
| except Exception as e: | |
| logger.warning(f"L2 Redis cache error: {e}") | |
| # L3: Check Qdrant semantic cache (similar queries) | |
| if self.l3_qdrant: | |
| try: | |
| similar_result = await self._find_similar_query(query) | |
| if similar_result: | |
| # Promote to L1 and L2 | |
| self.l1_cache.set(cache_key, similar_result) | |
| await self._set_l2(cache_key, similar_result) | |
| logger.debug(f"L3 semantic cache HIT: {query[:50]}") | |
| return similar_result | |
| except Exception as e: | |
| logger.warning(f"L3 Qdrant cache error: {e}") | |
| # Cache miss | |
| logger.debug(f"Cache MISS: {query[:50]}") | |
| return None | |
| async def set(self, query: str, result: Any, ttl: int = 3600) -> None: | |
| """ | |
| Set search results in all cache tiers. | |
| Args: | |
| query: Search query | |
| result: Search results to cache | |
| ttl: Time to live in seconds | |
| """ | |
| cache_key = self._generate_cache_key(query) | |
| # L1: Always cache in memory | |
| self.l1_cache.set(cache_key, result) | |
| # L2: Cache in Redis | |
| await self._set_l2(cache_key, result, ttl) | |
| # L3: Index query in Qdrant for semantic lookup | |
| await self._index_query_semantic(query, result) | |
| logger.debug(f"Cached query: {query[:50]} (L1+L2+L3)") | |
| async def _set_l2(self, cache_key: str, result: Any, ttl: int = 3600) -> None: | |
| """Set result in L2 Redis cache""" | |
| if not self.l2_redis: | |
| return | |
| try: | |
| import json | |
| # Use RedisCache.set() method instead of raw Redis setex | |
| await self.l2_redis.set(cache_key, json.dumps(result), ttl=ttl) | |
| except Exception as e: | |
| logger.warning(f"Failed to set L2 cache: {e}") | |
| async def _find_similar_query(self, query: str) -> Any | None: | |
| """Find similar cached query in Qdrant (L3 semantic cache)""" | |
| if not self.l3_qdrant: | |
| return None | |
| try: | |
| from app.core.embedding_service import get_embedding_service | |
| embedding_service = get_embedding_service() | |
| query_embedding = embedding_service.encode_text(query) | |
| if query_embedding is None: | |
| return None | |
| # Search for similar queries | |
| similar = self.l3_qdrant.search_similar( | |
| query_embedding=query_embedding.tolist(), | |
| limit=1, | |
| score_threshold=self.l3_threshold, | |
| ) | |
| if similar and len(similar) > 0: | |
| result = similar[0] | |
| if result.get("payload", {}).get("cached_result"): | |
| return result["payload"]["cached_result"] | |
| except Exception as e: | |
| logger.debug(f"L3 semantic search failed: {e}") | |
| return None | |
| async def _index_query_semantic(self, query: str, result: Any) -> None: | |
| """Index query in Qdrant for future semantic lookup (L3)""" | |
| if not self.l3_qdrant: | |
| return | |
| try: | |
| from app.core.embedding_service import get_embedding_service | |
| embedding_service = get_embedding_service() | |
| query_embedding = embedding_service.encode_text(query) | |
| if query_embedding is None: | |
| return | |
| # Store in Qdrant with cached result using internal client | |
| # Note: QdrantVectorStore doesn't have upsert method, use internal client directly | |
| client = self.l3_qdrant._get_client() | |
| if client: | |
| from qdrant_client.http.models import PointStruct | |
| point = PointStruct( | |
| id=hashlib.md5(query.encode()).hexdigest(), | |
| vector=query_embedding.tolist(), | |
| payload={ | |
| "query": query, | |
| "cached_result": result, | |
| "timestamp": datetime.now().isoformat(), | |
| }, | |
| ) | |
| client.upsert( | |
| collection_name=self.l3_qdrant.collection_name, | |
| points=[point], | |
| ) | |
| except Exception as e: | |
| logger.debug(f"Failed to index query in L3: {e}") | |
| def get_stats(self) -> dict[str, Any]: | |
| """Get cache statistics""" | |
| return { | |
| "l1": self.l1_cache.stats(), | |
| "l2": "connected" if self.l2_redis else "disconnected", | |
| "l3": "connected" if self.l3_qdrant else "disconnected", | |
| } | |
| # Singleton instance | |
| _cache_instance: MultiTierCache | None = None | |
| def get_multi_tier_cache() -> MultiTierCache: | |
| """Get or create multi-tier cache singleton""" | |
| global _cache_instance | |
| if _cache_instance is None: | |
| _cache_instance = MultiTierCache() | |
| return _cache_instance | |