""" Memory Service - Robust memory management """ from datetime import datetime, timezone from typing import Dict, List from database import long_term_memory_col, chat_history_col class MemoryService: @staticmethod def load_long_memory(user_id: str) -> Dict: try: return long_term_memory_col.find_one({"user_id": user_id}) or {} except Exception as e: logging.error(f"[Memory] Load failed: {e}") return {} @staticmethod def save_fact(user_id: str, key: str, value: str): try: long_term_memory_col.update_one( {"user_id": user_id}, {"$set": {key: value, "last_updated": datetime.now(timezone.utc)}}, upsert=True ) except Exception as e: logging.error(f"[Memory] Save failed: {e}") @staticmethod def load_recent_memory(user_id: str, limit: int = 8) -> List[Dict]: try: cursor = chat_history_col.find({"user_id": user_id}).sort("timestamp", -1).limit(limit * 2) msgs = list(cursor) msgs.reverse() pairs = [] for msg in msgs: if msg["role"] == "user": pairs.append({"user": msg["content"], "ai": ""}) elif msg["role"] == "assistant" and pairs: pairs[-1]["ai"] = msg["content"] return [p for p in pairs if p["ai"]] except Exception as e: logging.error(f"[Memory] Load recent failed: {e}") return []