modified: backend/open_webui/memory/mem0.py

modified:   backend/open_webui/utils/middleware.py
This commit is contained in:
xinyan 2025-11-30 22:18:55 +08:00
parent c4d1fa5048
commit d70647629a
2 changed files with 28 additions and 4 deletions

View file

@ -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}")

View file

@ -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": "<string>",
"user_id": "<string>",
"metadata": {},
"categories": [
"<string>"
],
"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"