From 16375e2a3a35b7923d3d510c94ea0083b132d8ad Mon Sep 17 00:00:00 2001 From: chan Date: Tue, 17 Jun 2025 17:05:00 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9C=AC=E5=9C=B0mem0=E8=AE=B0=E5=BF=86?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=8C=E9=80=9A=E8=BF=87mem0+milvus?= =?UTF-8?q?=E5=90=91=E9=87=8F=E6=95=B0=E6=8D=AE=E5=BA=93=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main/xiaozhi-server/config.yaml | 28 ++++++- .../memory/mem0_milvus/mem0_milvus.py | 78 +++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 main/xiaozhi-server/core/providers/memory/mem0_milvus/mem0_milvus.py diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 6dc0b25d4..cf566aaae 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -235,7 +235,33 @@ Memory: # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型 # 如果你的不想使用selected_module.LLM记忆存储,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM llm: ChatGLMLLM - + mem0_milvus: + # 本地 mem0+milvus 记忆功能 + type: mem0_milvus + llm: + provider: openai + config: + model: qwen-plus + openai_base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 + # https://bailian.console.aliyun.com/?tab=model#/api-key + api_key: 阿里云百炼平台api_key + temperature: 0.2 + max_tokens: 2000 + top_p: 1.0 + embedder: + provider: openai + config: + model: text-embedding-v4 + api_key: 阿里云百炼平台api_key + openai_base_url: https://dashscope.aliyuncs.com/compatible-mode/v1/ + vector_store: + #可以使用容器本地部署 milvus 向量数据库 + provider: milvus + config: + # 使用你的 milvus 向量数据库地址 + url: http://127.0.0.1:19530 + collection_name: mem0_collection + embedding_model_dims: 1024 ASR: FunASR: type: fun_local diff --git a/main/xiaozhi-server/core/providers/memory/mem0_milvus/mem0_milvus.py b/main/xiaozhi-server/core/providers/memory/mem0_milvus/mem0_milvus.py new file mode 100644 index 000000000..b3cdf7768 --- /dev/null +++ b/main/xiaozhi-server/core/providers/memory/mem0_milvus/mem0_milvus.py @@ -0,0 +1,78 @@ +from ..base import MemoryProviderBase, logger +from mem0 import Memory + +TAG = __name__ + + +class MemoryProvider(MemoryProviderBase): + def __init__(self, config, summary_memory=None): + super().__init__(config) + + try: + self.client = Memory.from_config(self.config) + self.use_mem0local = True + logger.bind(tag=TAG).info("成功使用Mem0_milvus服务") + except Exception as e: + logger.bind(tag=TAG).error(f"Mem0配置错误: {str(e)}") + self.use_mem0local = False + + async def save_memory(self, msgs): + if not self.use_mem0local: + return None + if len(msgs) < 2: + return None + + try: + # Format the content as a message list for mem0 + messages = [ + {"role": message.role, "content": message.content} + for message in msgs if message.role != "system" + ] + result = self.client.add(messages, user_id=self.role_id) + logger.bind(tag=TAG).info(f"Save memory result: {result}") + except Exception as e: + print(e) + logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}") + return None + + async def query_memory(self, query: str) -> str: + if not self.use_mem0local: + return "" + try: + results = self.client.search( + query, + user_id=self.role_id + ) + logger.bind(tag=TAG).info(f"get memory result: {results}") + if not results or 'results' not in results: + return "" + + # Format each memory entry with its update time up to minutes + memories = [] + for entry in results['results']: + timestamp = entry.get('updated_at', '') or entry.get('created_at', '') + if timestamp: + try: + # Parse and reformat the timestamp + dt = timestamp.split('.')[0] # Remove milliseconds + formatted_time = dt.replace('T', ' ') + except: + formatted_time = timestamp + memory = entry.get('memory', '') + if timestamp and memory: + # Store tuple of (timestamp, formatted_string) for sorting + memories.append((timestamp, f"[{formatted_time}] {memory}")) + + # Sort by timestamp in descending order (newest first) + memories.sort(key=lambda x: x[0], reverse=True) + + # Extract only the formatted strings + memories_str = "\n".join(f"- {memory[1]}" for memory in memories) + logger.bind(tag=TAG).debug(f"Query results: {memories_str}") + return memories_str + except Exception as e: + if "collection not found" in e: + return "" + else: + logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}") + return ""