diff --git a/dsLightRag/Volcengine/Kit/VikingDBMemoryService.py b/dsLightRag/Volcengine/Kit/VikingDBMemoryService.py index facbac66..f5e822d9 100644 --- a/dsLightRag/Volcengine/Kit/VikingDBMemoryService.py +++ b/dsLightRag/Volcengine/Kit/VikingDBMemoryService.py @@ -212,70 +212,6 @@ class VikingDBMemoryService(Service): res = self.json("AddSession", {}, json.dumps(params)) return json.loads(res) - def handle_conversation_turn(self, llm_client, user_id, user_message, conversation_history): - """处理一轮对话,包括记忆搜索和LLM响应。""" - logger.info("\n" + "=" * 60) - logger.info(f"用户: {user_message}") - - # 修复:调用正确的search_relevant_memories方法 - relevant_memories = self.search_relevant_memories(MEMORY_COLLECTION_NAME, user_id, user_message) - - system_prompt = "你是一个富有同情心、善于倾听的AI伙伴,拥有长期记忆能力。你的目标是为用户提供情感支持和温暖的陪伴。" - if relevant_memories: - memory_context = "\n".join( - [f"- {json.dumps(mem['memory_info'], ensure_ascii=False)}" for mem in relevant_memories]) - system_prompt += f"\n\n这是我们过去的一些对话记忆,请参考:\n{memory_context}\n\n请利用这些信息来更好地理解和回应用户。" - - logger.info("AI正在思考...") - - try: - messages = [{"role": "system", "content": system_prompt}] + conversation_history + [ - {"role": "user", "content": user_message}] - completion = llm_client.chat.completions.create( - model="doubao-seed-1-6-flash-250715", - messages=messages - ) - assistant_reply = completion.choices[0].message.content - except Exception as e: - logger.info(f"LLM调用失败: {e}") - assistant_reply = "抱歉,我现在有点混乱,无法回应。我们可以稍后再聊吗?" - - logger.info(f"伙伴: {assistant_reply}") - - conversation_history.extend([ - {"role": "user", "content": user_message}, - {"role": "assistant", "content": assistant_reply} - ]) - return assistant_reply - - def archive_conversation(self, user_id, assistant_id, conversation_history, topic_name): - """将对话历史归档到记忆数据库。""" - if not conversation_history: - logger.info("没有对话可以归档。") - return False - - logger.info(f"\n正在归档关于 '{topic_name}' 的对话...") - session_id = f"{topic_name}_{int(time.time())}" - metadata = { - "default_user_id": user_id, - "default_assistant_id": assistant_id, - "time": int(time.time() * 1000) - } - - try: - self.add_session( - collection_name=MEMORY_COLLECTION_NAME, - session_id=session_id, - messages=conversation_history, - metadata=metadata - ) - logger.info(f"对话已成功归档,会话ID: {session_id}") - logger.info("正在等待记忆索引更新...") - return True - except Exception as e: - logger.info(f"归档对话失败: {e}") - return False - def wait_for_collection_ready(self, timeout=300, interval=10): """ 等待集合准备就绪 @@ -352,52 +288,6 @@ class VikingDBMemoryService(Service): logger.info(f"检查集合时出错: {e}") raise - def search_relevant_memories(self, collection_name, user_id, query, limit=3): - """搜索与用户查询相关的记忆,并在索引构建中时重试。""" - logger.info(f"正在搜索与 '{query}' 相关的记忆...") - retry_attempt = 0 - while True: - try: - filter_params = { - "user_id": user_id, # 修正为字符串类型 - "memory_type": ["sys_event_v1", "sys_profile_v1"] - } - response = self.search_memory( - collection_name=collection_name, - query=query, - filter=filter_params, - limit=limit - ) - - memories = [] - if response.get('data', {}).get('count', 0) > 0: - for result in response['data']['result_list']: - if 'memory_info' in result and result['memory_info']: - memories.append({ - 'memory_info': result['memory_info'], - 'score': result['score'] - }) - - if memories: - if retry_attempt > 0: - logger.info("重试后搜索成功。") - logger.info(f"找到 {len(memories)} 条相关记忆:") - for i, memory in enumerate(memories, 1): - logger.info( - f" {i}. (相关度: {memory['score']:.3f}): {json.dumps(memory['memory_info'], ensure_ascii=False, indent=2)}") - else: - logger.info("未找到相关记忆。") - return memories - - except Exception as e: - error_message = str(e) - if "1000023" in error_message: - retry_attempt += 1 - logger.info(f"记忆索引正在构建中。将在60秒后重试... (尝试次数 {retry_attempt})") - time.sleep(60) - else: - logger.info(f"搜索记忆时出错 (不可重试): {e}") - return [] def setup_memory_collection(self): """独立封装记忆体创建逻辑,返回memory_service供测试使用""" @@ -441,7 +331,7 @@ def initialize_services(): return memory_service, llm_client -def search_relevant_memories(memory_service, collection_name, user_id, query): +def search_relevant_memories(memory_service, collection_name, user_id, assistant_id, query): """搜索与用户查询相关的记忆,并在索引构建中时重试。""" logger.info(f"正在搜索与 '{query}' 相关的记忆...") retry_attempt = 0 @@ -449,6 +339,7 @@ def search_relevant_memories(memory_service, collection_name, user_id, query): try: filter_params = { "user_id": [user_id], + "assistant_id": assistant_id, # 添加assistant_id过滤条件 "memory_type": ["sys_event_v1", "sys_profile_v1"] } response = memory_service.search_memory( @@ -489,12 +380,12 @@ def search_relevant_memories(memory_service, collection_name, user_id, query): return [] -def handle_conversation_turn(memory_service, llm_client, collection_name, user_id, user_message, conversation_history): +def handle_conversation_turn(memory_service, llm_client, collection_name, user_id, assistant_id, user_message, conversation_history): """处理一轮对话,包括记忆搜索和LLM响应。""" logger.info("\n" + "=" * 60) logger.info(f"用户: {user_message}") - relevant_memories = search_relevant_memories(memory_service, collection_name, user_id, user_message) + relevant_memories = search_relevant_memories(memory_service, collection_name, user_id, assistant_id, user_message) system_prompt = "你是一个富有同情心、善于倾听的AI伙伴,拥有长期记忆能力。你的目标是为用户提供情感支持和温暖的陪伴。" if relevant_memories: diff --git a/dsLightRag/Volcengine/Kit/__pycache__/VikingDBMemoryService.cpython-310.pyc b/dsLightRag/Volcengine/Kit/__pycache__/VikingDBMemoryService.cpython-310.pyc index 2f61a84a..a4727782 100644 Binary files a/dsLightRag/Volcengine/Kit/__pycache__/VikingDBMemoryService.cpython-310.pyc and b/dsLightRag/Volcengine/Kit/__pycache__/VikingDBMemoryService.cpython-310.pyc differ diff --git a/dsLightRag/Volcengine/T3_ChatWithMemory.py b/dsLightRag/Volcengine/T3_ChatWithMemory.py index 7538b99e..5f5e51d3 100644 --- a/dsLightRag/Volcengine/T3_ChatWithMemory.py +++ b/dsLightRag/Volcengine/T3_ChatWithMemory.py @@ -22,10 +22,13 @@ def main(): try: # 使用initialize_services函数初始化服务和LLM客户端 memory_service, llm_client = initialize_services() - + # 集合名称【数据库名】 collection_name = MEMORY_COLLECTION_NAME - user_id = "liming" # 用户李明 - assistant_id = "assistant" # 助手ID:助手 + + # 用户李明 + user_id = "liming" + # 助手ID:助手 + assistant_id = "assistant" # 告知大模型用户信息 logger.info("告知大模型用户信息...") @@ -39,12 +42,13 @@ def main(): # 使用正确的handle_conversation_turn方法参数 response = handle_conversation_turn( - memory_service=memory_service, - llm_client=llm_client, - collection_name=collection_name, - user_id=user_id, - user_message=f"请记住以下用户信息:{user_info}", - conversation_history=conversation_history + memory_service=memory_service,# 内存记忆服务 + llm_client=llm_client,# 大模型客户端 + collection_name=collection_name,# 集合名称 + user_id=user_id,# 用户ID + assistant_id=assistant_id,# 助手ID + user_message=f"请记住以下用户信息:{user_info}",# 要记忆的信息 + conversation_history=conversation_history # 对话历史 ) logger.info(f"模型回复: {response}") @@ -72,6 +76,7 @@ def main(): llm_client=llm_client, collection_name=collection_name, user_id=user_id, + assistant_id=assistant_id, # 添加这一行 user_message="请告诉我李明的个人信息", conversation_history=test_conversation_history )