import os import json import logging logger = logging.getLogger("Memory") MEMORY_DIR = "conversation_memory" # Ensure the memory directory exists if not os.path.exists(MEMORY_DIR): os.makedirs(MEMORY_DIR) class FileMemory: def __init__(self): self.memory_dir = MEMORY_DIR def _get_filepath(self, user_id): return os.path.join(self.memory_dir, f"{user_id}.json") def store_user_message(self, user_id, message): self._store_message(user_id, "user", message) def store_agent_message(self, user_id, message): self._store_message(user_id, "assistant", message) def _store_message(self, user_id, role, message): conversation = self.get_memory(user_id) conversation.append({"role": role, "content": message}) self._save_conversation(user_id, conversation) def get_memory(self, user_id): filepath = self._get_filepath(user_id) if os.path.exists(filepath): with open(filepath, "r") as f: return json.load(f) return [] def clear_memory(self, user_id): filepath = self._get_filepath(user_id) if os.path.exists(filepath): os.remove(filepath) logger.info(f"Cleared memory for {user_id}") def _save_conversation(self, user_id, conversation): filepath = self._get_filepath(user_id) with open(filepath, "w") as f: json.dump(conversation, f, indent=2) def get_context(self, user_id): # Combine last 5 messages as a basic context conversation = self.get_memory(user_id) last_messages = conversation[-5:] context = "\n".join( [f"{msg['role'].capitalize()}: {msg['content']}" for msg in last_messages] ) return context def store_user_profile(self, user_id, email=None): # Placeholder: can extend if needed pass def update_user_preference(self, user_id, key, value): # Placeholder: can extend if needed pass def get_user_profile(self, user_id): # Placeholder: return empty dict return {} # Instantiate a global memory object memory = FileMemory()