From 6d43bbb62704d28cab1e98d548dd1a70c33af6cb Mon Sep 17 00:00:00 2001 From: tt-P607 <68868379+tt-P607@users.noreply.github.com> Date: Fri, 10 Oct 2025 19:17:07 +0800 Subject: [PATCH] =?UTF-8?q?feat(cross=5Fcontext):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E8=B7=A8=E4=B8=8A=E4=B8=8B=E6=96=87=E6=A3=80=E7=B4=A2=EF=BC=8C?= =?UTF-8?q?=E5=8C=BA=E5=88=86=E7=BE=A4=E8=81=8A=E4=B8=8E=E7=A7=81=E8=81=8A?= =?UTF-8?q?=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 先前的实现中,在获取以用户为中心的上下文时,对所有聊天类型都只提取该用户的发言记录。 这在私聊场景下会导致上下文不完整,因为缺少了另一方(机器人)的消息。 本次更新通过判断聊天类型,实现了差异化的上下文获取: - **群聊**: 保持原有逻辑,只获取目标用户的近期发言。 - **私聊**: 获取完整的近期双向聊天记录,以提供更全面的对话背景。 --- src/plugin_system/apis/cross_context_api.py | 25 +++++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/plugin_system/apis/cross_context_api.py b/src/plugin_system/apis/cross_context_api.py index 8d534aab2..702bb9675 100644 --- a/src/plugin_system/apis/cross_context_api.py +++ b/src/plugin_system/apis/cross_context_api.py @@ -182,13 +182,22 @@ async def get_user_centric_context( timestamp=time.time(), limit=limit * 5, # 获取更多消息以供筛选 ) - user_messages = [msg for msg in messages if msg.get("user_id") == user_id][-limit:] + chat_name = await chat_manager.get_stream_name(stream.stream_id) or stream.stream_id + is_group = stream.group_info is not None - if user_messages: - chat_name = await chat_manager.get_stream_name(stream.stream_id) or stream.stream_id + if is_group: + # 对于群聊,只获取该用户的发言 + relevant_messages = [msg for msg in messages if msg.get("user_id") == user_id][-limit:] + title = f'[以下是该用户在"{chat_name}"的近期发言]\n' + else: + # 对于私聊,获取双方的聊天记录 + relevant_messages = messages[-limit:] + title = f'[以下是与该用户的近期私聊"{chat_name}"的记录]\n' + + if relevant_messages: if chat_name not in user_messages_map: - user_messages_map[chat_name] = [] - user_messages_map[chat_name].extend(user_messages) + user_messages_map[chat_name] = {"messages": [], "title": title} + user_messages_map[chat_name]["messages"].extend(relevant_messages) except Exception as e: logger.error(f"获取用户 {user_id} 在聊天 {stream.stream_id} 的消息失败: {e}") continue @@ -198,11 +207,13 @@ async def get_user_centric_context( # 构建最终的上下文字符串 cross_context_parts = [] - for chat_name, messages in user_messages_map.items(): + for chat_name, data in user_messages_map.items(): + messages = data["messages"] + title = data["title"] # 按时间戳对消息进行排序 messages.sort(key=lambda x: x.get("time", 0)) formatted_messages, _ = await build_readable_messages_with_id(messages, timestamp_mode="relative") - cross_context_parts.append(f'[以下是该用户在"{chat_name}"的近期发言]\n{formatted_messages}') + cross_context_parts.append(f"{title}{formatted_messages}") if not cross_context_parts: return None