refactor(chat): 优化跨群聊上下文构建与代码格式

对 `default_generator.py` 进行了多项重构和优化:
- 将跨群聊上下文的构建逻辑移入独立的 `_build_cross_context_block` 方法,并在主流程中异步并行执行,提高了代码的模块化和执行效率。
- 全面清理了代码中的多余空行和不一致的间距,提升了代码的可读性和一致性。
- 调整了 `NoReplyAction` 和 `ReplyAction` 的 `mode_enable` 配置,使其行为更符合预期。
This commit is contained in:
minecraft1024a
2025-08-22 13:37:59 +08:00
committed by Windpicker-owo
parent 268bbc3e2d
commit 1a5cb9e851
3 changed files with 74 additions and 62 deletions

View File

@@ -196,10 +196,7 @@ class DefaultReplyer:
self.heart_fc_sender = HeartFCSender() self.heart_fc_sender = HeartFCSender()
self.memory_activator = MemoryActivator() self.memory_activator = MemoryActivator()
# 使用纯向量瞬时记忆系统V2支持自定义保留时间 # 使用纯向量瞬时记忆系统V2支持自定义保留时间
self.instant_memory = VectorInstantMemoryV2( self.instant_memory = VectorInstantMemoryV2(chat_id=self.chat_stream.stream_id, retention_hours=1)
chat_id=self.chat_stream.stream_id,
retention_hours=1
)
from src.plugin_system.core.tool_use import ToolExecutor # 延迟导入ToolExecutor不然会循环依赖 from src.plugin_system.core.tool_use import ToolExecutor # 延迟导入ToolExecutor不然会循环依赖
@@ -221,26 +218,27 @@ class DefaultReplyer:
if str(current_chat_raw_id) in group.chat_ids: if str(current_chat_raw_id) in group.chat_ids:
target_group = group target_group = group
break break
if not target_group: if not target_group:
return "" return ""
# 根据prompt_mode选择策略 # 根据prompt_mode选择策略
prompt_mode = global_config.personality.prompt_mode prompt_mode = global_config.personality.prompt_mode
other_chat_raw_ids = [chat_id for chat_id in target_group.chat_ids if chat_id != str(current_chat_raw_id)] other_chat_raw_ids = [chat_id for chat_id in target_group.chat_ids if chat_id != str(current_chat_raw_id)]
cross_context_messages = [] cross_context_messages = []
if prompt_mode == "normal": if prompt_mode == "normal":
# normal模式获取其他群聊的最近N条消息 # normal模式获取其他群聊的最近N条消息
for chat_raw_id in other_chat_raw_ids: for chat_raw_id in other_chat_raw_ids:
stream_id = get_chat_manager().get_stream_id(current_stream.platform, chat_raw_id, is_group=True) stream_id = get_chat_manager().get_stream_id(current_stream.platform, chat_raw_id, is_group=True)
if not stream_id: continue if not stream_id:
continue
messages = get_raw_msg_before_timestamp_with_chat( messages = get_raw_msg_before_timestamp_with_chat(
chat_id=stream_id, chat_id=stream_id,
timestamp=time.time(), timestamp=time.time(),
limit=5 # 可配置 limit=5, # 可配置
) )
if messages: if messages:
chat_name = get_chat_manager().get_stream_name(stream_id) or stream_id chat_name = get_chat_manager().get_stream_name(stream_id) or stream_id
@@ -254,21 +252,32 @@ class DefaultReplyer:
if user_id: if user_id:
for chat_raw_id in other_chat_raw_ids: for chat_raw_id in other_chat_raw_ids:
stream_id = get_chat_manager().get_stream_id(current_stream.platform, chat_raw_id, is_group=True) stream_id = get_chat_manager().get_stream_id(
if not stream_id: continue current_stream.platform, chat_raw_id, is_group=True
)
if not stream_id:
continue
messages = get_raw_msg_before_timestamp_with_chat( messages = get_raw_msg_before_timestamp_with_chat(
chat_id=stream_id, chat_id=stream_id,
timestamp=time.time(), timestamp=time.time(),
limit=20 # 获取更多消息以供筛选 limit=20, # 获取更多消息以供筛选
) )
user_messages = [msg for msg in messages if msg.get('user_id') == user_id][-5:] # 筛选并取最近5条 user_messages = [msg for msg in messages if msg.get("user_id") == user_id][
-5:
] # 筛选并取最近5条
if user_messages: if user_messages:
chat_name = get_chat_manager().get_stream_name(stream_id) or stream_id chat_name = get_chat_manager().get_stream_name(stream_id) or stream_id
user_name = target_user_info.get("person_name") or target_user_info.get("user_nickname") or user_id user_name = (
formatted_messages, _ = build_readable_messages_with_id(user_messages, timestamp_mode="relative") target_user_info.get("person_name") or target_user_info.get("user_nickname") or user_id
cross_context_messages.append(f"[以下是“{user_name}”在“{chat_name}”的近期发言]\n{formatted_messages}") )
formatted_messages, _ = build_readable_messages_with_id(
user_messages, timestamp_mode="relative"
)
cross_context_messages.append(
f"[以下是“{user_name}”在“{chat_name}”的近期发言]\n{formatted_messages}"
)
if not cross_context_messages: if not cross_context_messages:
return "" return ""
@@ -511,55 +520,50 @@ class DefaultReplyer:
# 使用异步记忆包装器(最优化的非阻塞模式) # 使用异步记忆包装器(最优化的非阻塞模式)
try: try:
from src.chat.memory_system.async_instant_memory_wrapper import get_async_instant_memory from src.chat.memory_system.async_instant_memory_wrapper import get_async_instant_memory
# 获取异步记忆包装器 # 获取异步记忆包装器
async_memory = get_async_instant_memory(self.chat_stream.stream_id) async_memory = get_async_instant_memory(self.chat_stream.stream_id)
# 后台存储聊天历史(完全非阻塞) # 后台存储聊天历史(完全非阻塞)
async_memory.store_memory_background(chat_history) async_memory.store_memory_background(chat_history)
# 快速检索记忆最大超时2秒 # 快速检索记忆最大超时2秒
instant_memory = await async_memory.get_memory_with_fallback(target, max_timeout=2.0) instant_memory = await async_memory.get_memory_with_fallback(target, max_timeout=2.0)
logger.info(f"异步瞬时记忆:{instant_memory}") logger.info(f"异步瞬时记忆:{instant_memory}")
except ImportError: except ImportError:
# 如果异步包装器不可用,尝试使用异步记忆管理器 # 如果异步包装器不可用,尝试使用异步记忆管理器
try: try:
from src.chat.memory_system.async_memory_optimizer import ( from src.chat.memory_system.async_memory_optimizer import (
retrieve_memory_nonblocking, retrieve_memory_nonblocking,
store_memory_nonblocking store_memory_nonblocking,
) )
# 异步存储聊天历史(非阻塞) # 异步存储聊天历史(非阻塞)
asyncio.create_task(store_memory_nonblocking( asyncio.create_task(
chat_id=self.chat_stream.stream_id, store_memory_nonblocking(chat_id=self.chat_stream.stream_id, content=chat_history)
content=chat_history
))
# 尝试从缓存获取瞬时记忆
instant_memory = await retrieve_memory_nonblocking(
chat_id=self.chat_stream.stream_id,
query=target
) )
# 尝试从缓存获取瞬时记忆
instant_memory = await retrieve_memory_nonblocking(chat_id=self.chat_stream.stream_id, query=target)
# 如果没有缓存结果,快速检索一次 # 如果没有缓存结果,快速检索一次
if instant_memory is None: if instant_memory is None:
try: try:
instant_memory = await asyncio.wait_for( instant_memory = await asyncio.wait_for(
self.instant_memory.get_memory_for_context(target), self.instant_memory.get_memory_for_context(target), timeout=1.5
timeout=1.5
) )
except asyncio.TimeoutError: except asyncio.TimeoutError:
logger.warning("瞬时记忆检索超时,使用空结果") logger.warning("瞬时记忆检索超时,使用空结果")
instant_memory = "" instant_memory = ""
logger.info(f"向量瞬时记忆:{instant_memory}") logger.info(f"向量瞬时记忆:{instant_memory}")
except ImportError: except ImportError:
# 最后的fallback使用原有逻辑但加上超时控制 # 最后的fallback使用原有逻辑但加上超时控制
logger.warning("异步记忆系统不可用,使用带超时的同步方式") logger.warning("异步记忆系统不可用,使用带超时的同步方式")
# 异步存储聊天历史 # 异步存储聊天历史
asyncio.create_task(self.instant_memory.store_message(chat_history)) asyncio.create_task(self.instant_memory.store_message(chat_history))
@@ -567,7 +571,7 @@ class DefaultReplyer:
try: try:
instant_memory = await asyncio.wait_for( instant_memory = await asyncio.wait_for(
self.instant_memory.get_memory_for_context(target), self.instant_memory.get_memory_for_context(target),
timeout=1.0 # 最保守的1秒超时 timeout=1.0, # 最保守的1秒超时
) )
except asyncio.TimeoutError: except asyncio.TimeoutError:
logger.warning("瞬时记忆检索超时,跳过记忆获取") logger.warning("瞬时记忆检索超时,跳过记忆获取")
@@ -575,9 +579,9 @@ class DefaultReplyer:
except Exception as e: except Exception as e:
logger.error(f"瞬时记忆检索失败: {e}") logger.error(f"瞬时记忆检索失败: {e}")
instant_memory = "" instant_memory = ""
logger.info(f"同步瞬时记忆:{instant_memory}") logger.info(f"同步瞬时记忆:{instant_memory}")
except Exception as e: except Exception as e:
logger.error(f"瞬时记忆系统异常: {e}") logger.error(f"瞬时记忆系统异常: {e}")
instant_memory = "" instant_memory = ""
@@ -906,7 +910,7 @@ class DefaultReplyer:
if global_config.mood.enable_mood: if global_config.mood.enable_mood:
chat_mood = mood_manager.get_mood_by_chat_id(chat_id) chat_mood = mood_manager.get_mood_by_chat_id(chat_id)
mood_prompt = chat_mood.mood_state mood_prompt = chat_mood.mood_state
# 检查是否有愤怒状态的补充提示词 # 检查是否有愤怒状态的补充提示词
angry_prompt_addition = mood_manager.get_angry_prompt_addition(chat_id) angry_prompt_addition = mood_manager.get_angry_prompt_addition(chat_id)
if angry_prompt_addition: if angry_prompt_addition:
@@ -937,7 +941,12 @@ class DefaultReplyer:
show_actions=True, show_actions=True,
) )
# 并行执行五个构建任务 # 获取目标用户信息用于s4u模式
target_user_info = None
if sender:
target_user_info = await person_info_manager.get_person_info_by_name(sender)
# 并行执行六个构建任务
task_results = await asyncio.gather( task_results = await asyncio.gather(
self._time_and_run_task( self._time_and_run_task(
self.build_expression_habits(chat_talking_prompt_short, target), "expression_habits" self.build_expression_habits(chat_talking_prompt_short, target), "expression_habits"
@@ -947,8 +956,8 @@ class DefaultReplyer:
self._time_and_run_task( self._time_and_run_task(
self.build_tool_info(chat_talking_prompt_short, sender, target, enable_tool=enable_tool), "tool_info" self.build_tool_info(chat_talking_prompt_short, sender, target, enable_tool=enable_tool), "tool_info"
), ),
self._time_and_run_task(self.get_prompt_info(chat_talking_prompt_short, sender, target), "prompt_info"), self._time_and_run_task(self.get_prompt_info(chat_talking_prompt_short, reply_to), "prompt_info"),
self._time_and_run_task(self.build_actions_prompt(available_actions,choosen_actions), "actions_info"), self._time_and_run_task(self._build_cross_context_block(chat_id, target_user_info), "cross_context"),
) )
# 任务名称中英文映射 # 任务名称中英文映射
@@ -976,8 +985,9 @@ class DefaultReplyer:
relation_info = results_dict["relation_info"] relation_info = results_dict["relation_info"]
memory_block = results_dict["memory_block"] memory_block = results_dict["memory_block"]
tool_info = results_dict["tool_info"] tool_info = results_dict["tool_info"]
prompt_info = results_dict["prompt_info"] # 直接使用格式化后的结果 prompt_info = results_dict["prompt_info"]
actions_info = results_dict["actions_info"] cross_context_block = results_dict["cross_context"]
keywords_reaction_prompt = await self.build_keywords_reaction_prompt(target) keywords_reaction_prompt = await self.build_keywords_reaction_prompt(target)
if extra_info: if extra_info:
@@ -1034,13 +1044,13 @@ class DefaultReplyer:
# 根据配置选择模板 # 根据配置选择模板
current_prompt_mode = global_config.personality.prompt_mode current_prompt_mode = global_config.personality.prompt_mode
logger.debug(f"[Prompt模式调试] 当前配置的prompt_mode: {current_prompt_mode}") logger.debug(f"[Prompt模式调试] 当前配置的prompt_mode: {current_prompt_mode}")
if current_prompt_mode == "normal": if current_prompt_mode == "normal":
template_name = "normal_style_prompt" template_name = "normal_style_prompt"
logger.debug(f"[Prompt模式调试] 选择使用normal模式模板: {template_name}") logger.debug(f"[Prompt模式调试] 选择使用normal模式模板: {template_name}")
# normal模式使用统一的聊天历史不分离核心对话和背景对话 # normal模式使用统一的聊天历史不分离核心对话和背景对话
config_expression_style = global_config.personality.reply_style config_expression_style = global_config.personality.reply_style
# 获取统一的聊天历史(不分离) # 获取统一的聊天历史(不分离)
unified_message_list = get_raw_msg_before_timestamp_with_chat( unified_message_list = get_raw_msg_before_timestamp_with_chat(
chat_id=self.chat_stream.stream_id, chat_id=self.chat_stream.stream_id,
@@ -1056,23 +1066,23 @@ class DefaultReplyer:
truncate=True, truncate=True,
show_actions=True, show_actions=True,
) )
# 为normal模式构建简化的chat_info不包含时间因为time_block单独传递 # 为normal模式构建简化的chat_info不包含时间因为time_block单独传递
chat_info = f"""群里的聊天内容: chat_info = f"""群里的聊天内容:
{unified_chat_history}""" {unified_chat_history}"""
logger.debug("[Prompt模式调试] normal模式使用统一聊天历史不分离对话") logger.debug("[Prompt模式调试] normal模式使用统一聊天历史不分离对话")
logger.debug("[Prompt模式调试] normal模式参数准备完成开始调用format_prompt") logger.debug("[Prompt模式调试] normal模式参数准备完成开始调用format_prompt")
logger.debug(f"[Prompt模式调试] normal模式传递的参数: template_name={template_name}") logger.debug(f"[Prompt模式调试] normal模式传递的参数: template_name={template_name}")
logger.debug("[Prompt模式调试] 检查global_prompt_manager是否有该模板...") logger.debug("[Prompt模式调试] 检查global_prompt_manager是否有该模板...")
# 检查模板是否存在 # 检查模板是否存在
try: try:
test_prompt = await global_prompt_manager.get_prompt_async(template_name) test_prompt = await global_prompt_manager.get_prompt_async(template_name)
logger.debug(f"[Prompt模式调试] 找到模板 {template_name}, 内容预览: {test_prompt[:100]}...") logger.debug(f"[Prompt模式调试] 找到模板 {template_name}, 内容预览: {test_prompt[:100]}...")
except Exception as e: except Exception as e:
logger.error(f"[Prompt模式调试] 模板 {template_name} 不存在或获取失败: {e}") logger.error(f"[Prompt模式调试] 模板 {template_name} 不存在或获取失败: {e}")
result = await global_prompt_manager.format_prompt( result = await global_prompt_manager.format_prompt(
template_name, template_name,
expression_habits_block=expression_habits_block, expression_habits_block=expression_habits_block,
@@ -1084,30 +1094,31 @@ class DefaultReplyer:
identity=identity_block, identity=identity_block,
schedule_block=schedule_block, schedule_block=schedule_block,
action_descriptions=action_descriptions, action_descriptions=action_descriptions,
time_block=time_block, # 保留time_block参数 time_block=time_block,
chat_info=chat_info, chat_info=chat_info,
reply_target_block=reply_target_block, reply_target_block=reply_target_block,
mood_state=mood_prompt, mood_state=mood_prompt,
config_expression_style=config_expression_style, config_expression_style=config_expression_style,
keywords_reaction_prompt=keywords_reaction_prompt, keywords_reaction_prompt=keywords_reaction_prompt,
moderation_prompt=moderation_prompt_block, moderation_prompt=moderation_prompt_block,
cross_context_block=cross_context_block,
) )
return result return result
else: else:
# 使用 s4u 风格的模板 # 使用 s4u 风格的模板
template_name = "s4u_style_prompt" template_name = "s4u_style_prompt"
logger.debug(f"[Prompt模式调试] 选择使用s4u模式模板: {template_name} (prompt_mode={current_prompt_mode})") logger.debug(f"[Prompt模式调试] 选择使用s4u模式模板: {template_name} (prompt_mode={current_prompt_mode})")
logger.debug("[Prompt模式调试] s4u模式参数准备完成开始调用format_prompt") logger.debug("[Prompt模式调试] s4u模式参数准备完成开始调用format_prompt")
# 检查s4u模板是否存在 # 检查s4u模板是否存在
try: try:
test_prompt = await global_prompt_manager.get_prompt_async(template_name) test_prompt = await global_prompt_manager.get_prompt_async(template_name)
logger.debug(f"[Prompt模式调试] 找到s4u模板 {template_name}, 内容预览: {test_prompt[:100]}...") logger.debug(f"[Prompt模式调试] 找到s4u模板 {template_name}, 内容预览: {test_prompt[:100]}...")
except Exception as e: except Exception as e:
#理论上我觉得这玩意没多大可能炸就是了 # 理论上我觉得这玩意没多大可能炸就是了
logger.error(f"[Prompt模式调试] s4u模板 {template_name} 不存在或获取失败: {e}") logger.error(f"[Prompt模式调试] s4u模板 {template_name} 不存在或获取失败: {e}")
result = await global_prompt_manager.format_prompt( result = await global_prompt_manager.format_prompt(
template_name, template_name,
expression_habits_block=expression_habits_block, expression_habits_block=expression_habits_block,
@@ -1129,6 +1140,7 @@ class DefaultReplyer:
reply_style=global_config.personality.reply_style, reply_style=global_config.personality.reply_style,
keywords_reaction_prompt=keywords_reaction_prompt, keywords_reaction_prompt=keywords_reaction_prompt,
moderation_prompt=moderation_prompt_block, moderation_prompt=moderation_prompt_block,
cross_context_block=cross_context_block,
) )
logger.debug(f"[Prompt模式调试] s4u format_prompt调用完成结果预览: {result[:200]}...") logger.debug(f"[Prompt模式调试] s4u format_prompt调用完成结果预览: {result[:200]}...")
return result return result
@@ -1154,7 +1166,7 @@ class DefaultReplyer:
if global_config.mood.enable_mood: if global_config.mood.enable_mood:
chat_mood = mood_manager.get_mood_by_chat_id(chat_id) chat_mood = mood_manager.get_mood_by_chat_id(chat_id)
mood_prompt = chat_mood.mood_state mood_prompt = chat_mood.mood_state
# 检查是否有愤怒状态的补充提示词 # 检查是否有愤怒状态的补充提示词
angry_prompt_addition = mood_manager.get_angry_prompt_addition(chat_id) angry_prompt_addition = mood_manager.get_angry_prompt_addition(chat_id)
if angry_prompt_addition: if angry_prompt_addition:

View File

@@ -16,7 +16,7 @@ class NoReplyAction(BaseAction):
focus_activation_type = ActionActivationType.ALWAYS # 修复在focus模式下应该始终可用 focus_activation_type = ActionActivationType.ALWAYS # 修复在focus模式下应该始终可用
normal_activation_type = ActionActivationType.ALWAYS # 修复在normal模式下应该始终可用 normal_activation_type = ActionActivationType.ALWAYS # 修复在normal模式下应该始终可用
mode_enable = ChatMode.FOCUS mode_enable = ChatMode.FOCUS # 修复:在所有模式下都可用 # 二次修复:这玩意只有专注下才有用的好吗
parallel_action = False parallel_action = False
# 动作基本信息 # 动作基本信息

View File

@@ -16,7 +16,7 @@ class ReplyAction(BaseAction):
focus_activation_type = ActionActivationType.ALWAYS focus_activation_type = ActionActivationType.ALWAYS
normal_activation_type = ActionActivationType.ALWAYS normal_activation_type = ActionActivationType.ALWAYS
mode_enable = ChatMode.FOCUS | ChatMode.NORMAL mode_enable = ChatMode.ALL
parallel_action = False parallel_action = False
# 动作基本信息 # 动作基本信息