from langchain.memory import ConversationBufferMemory from langchain.memory.chat_message_histories import SQLChatMessageHistory from database import DB_URI def get_user_memory(user_id): # Check if the user exists in the database, if not, create new memory return ConversationBufferMemory( chat_memory=SQLChatMessageHistory( connection_string=DB_URI, session_id=user_id, ),memory_key="chat_history", return_messages=True # FIX: Prevent duplicate storage )