diff --git a/backend/open_webui/memory/mem0.py b/backend/open_webui/memory/mem0.py index 23dd9c032a..fa0d31ab1d 100644 --- a/backend/open_webui/memory/mem0.py +++ b/backend/open_webui/memory/mem0.py @@ -28,7 +28,7 @@ async def mem0_search(user_id: str, chat_id: str, last_message: str) -> list[str log.debug(f"Mem0 search failed: {e}") return [] -async def mem0_search_and_add(user_id: str, chat_id: str, last_message: str) -> list[str]: +async def mem0_search_and_add(user_id: str, chat_id: str, last_message: str) -> list[Dict]: """ 检索并添加记忆,添加记忆使用mem0 的add功能,返回若干相关记忆条目(字符串)。 增加 chat_id 便于按会话窗口区分/隔离记忆。 @@ -45,7 +45,7 @@ async def mem0_search_and_add(user_id: str, chat_id: str, last_message: str) -> memories=[] else: log.info(f"mem0_search_and_add found {len(serach_rst['results'])} results") - memories=[item.get("memory", item.get("text", "")) for item in serach_rst["results"]] + memories=serach_rst["results"] added_messages= [{"role": "user", "content": last_message}] memory_client.add(added_messages, user_id=user_id,enable_graph=True,async_mode=False, metadata={"session_id": chat_id}) log.info(f"mem0_add added message for user_id: {user_id}") diff --git a/backend/open_webui/utils/middleware.py b/backend/open_webui/utils/middleware.py index f32bb5a5e3..29f7dbd0c2 100644 --- a/backend/open_webui/utils/middleware.py +++ b/backend/open_webui/utils/middleware.py @@ -545,13 +545,37 @@ async def chat_memory_handler( entries.append(f"[{created_at_date}] {mem.content}") # 3.2 Mem0 检索结果 + ''' + { + "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "memory": "", + "user_id": "", + "metadata": {}, + "categories": [ + "" + ], + "immutable": false, + "expiration_date": null, + "created_at": "2023-11-07T05:31:56Z", + "updated_at": "2023-11-07T05:31:56Z" + } + ''' for item in mem0_results: - entries.append(f"[Mem0] {item}") + memory_content = item["memory"] if isinstance(item, dict) else item + created_at_date = time.strftime("%Y-%m-%d", time.localtime(item.get("created_at", 0))) if isinstance(item, dict) else "Unknown Date" + categories = item.get("categories", []) if isinstance(item, dict) else [] + if categories: + entries.append(f"[{created_at_date}] {memory_content} (Categories: {', '.join(categories)})") + else: + entries.append(f"[{created_at_date}] {memory_content}") + if not entries: return form_data - user_context = "" + #排序 + entries.sort(key=lambda x: x.split("]")[0], reverse=True) + user_context = "以下为检索到的相关记忆条目(按时间顺序):\n\n" for idx, entry in enumerate(entries): user_context += f"{idx + 1}. {entry}\n"