+ # --- THE SLIDING WINDOW FIX ---
+ # If the memory gets longer than 11 messages (1 system prompt + 10 chat messages)
+ if len(chat_memory[session_id]) > 11:
+ # Keep the system prompt at index [0], and grab the 10 most recent messages
+ chat_memory[session_id] = [chat_memory[session_id][0]] + chat_memory[session_id][-10:]
+