"""Redis Cache Layer for Working Memory""" import json import time import logging from typing import List, Optional, Dict import redis logger = logging.getLogger(__name__) class RedisCache: """Redis-backed working memory cache with TTL.""" def __init__(self, host: str = "127.0.0.1", port: int = 6379, password: str = "", db: int = 0): self.client = redis.Redis( host=host, port=port, password=password, db=db, decode_responses=True, socket_timeout=5, ) def _key(self, agent_id: str) -> str: return f"wm:{agent_id}" def add_working_memory(self, agent_id: str, content: str, metadata: dict = None, ttl: int = 259200) -> dict: """Add an item to agent's working memory (Redis List).""" item = { "content": content, "metadata": metadata or {}, "timestamp": time.time(), } key = self._key(agent_id) self.client.lpush(key, json.dumps(item)) self.client.expire(key, ttl) return item def get_working_memories(self, agent_id: str, limit: int = 20) -> List[dict]: """Get recent working memory items for an agent.""" key = self._key(agent_id) items = self.client.lrange(key, 0, limit - 1) result = [] for item_str in items: try: parsed = json.loads(item_str) if isinstance(parsed, dict): result.append(parsed) except json.JSONDecodeError: continue return result def clear_working_memory(self, agent_id: str) -> bool: """Clear all working memory for an agent.""" key = self._key(agent_id) self.client.delete(key) return True def get_working_memory_count(self, agent_id: str) -> int: """Get count of working memory items.""" key = self._key(agent_id) return self.client.llen(key) def health_check(self) -> bool: """Check Redis connectivity.""" try: return self.client.ping() except Exception: return False