feat:动作现在区分focus和normal,并且可选不同的激活策略

This commit is contained in:
SengokuCola
2025-06-09 15:10:38 +08:00
parent 2ce5114b8c
commit 97ffbe5145
25 changed files with 1180 additions and 855 deletions

View File

@@ -280,28 +280,26 @@ class NormalChat:
info_catcher = info_catcher_manager.get_info_catcher(thinking_id)
info_catcher.catch_decide_to_response(message)
# 如果启用planner预先修改可用actions避免在并行任务中重复调用
available_actions = None
if self.enable_planner:
try:
await self.action_modifier.modify_actions_for_normal_chat(
self.chat_stream, self.recent_replies, message.processed_plain_text
)
available_actions = self.action_manager.get_using_actions()
except Exception as e:
logger.warning(f"[{self.stream_name}] 获取available_actions失败: {e}")
available_actions = None
# 定义并行执行的任务
async def generate_normal_response():
"""生成普通回复"""
try:
# 如果启用planner获取可用actions
enable_planner = self.enable_planner
available_actions = None
if enable_planner:
try:
await self.action_modifier.modify_actions_for_normal_chat(
self.chat_stream, self.recent_replies
)
available_actions = self.action_manager.get_using_actions()
except Exception as e:
logger.warning(f"[{self.stream_name}] 获取available_actions失败: {e}")
available_actions = None
return await self.gpt.generate_response(
message=message,
thinking_id=thinking_id,
enable_planner=enable_planner,
enable_planner=self.enable_planner,
available_actions=available_actions,
)
except Exception as e:
@@ -315,38 +313,37 @@ class NormalChat:
return None
try:
# 并行执行动作修改和规划准备
async def modify_actions():
"""修改可用动作集合"""
return await self.action_modifier.modify_actions_for_normal_chat(
self.chat_stream, self.recent_replies
)
async def prepare_planning():
"""准备规划所需的信息"""
return self._get_sender_name(message)
# 并行执行动作修改和准备工作
_, sender_name = await asyncio.gather(modify_actions(), prepare_planning())
# 获取发送者名称(动作修改已在并行执行前完成)
sender_name = self._get_sender_name(message)
no_action = {
"action_result": {"action_type": "no_action", "action_data": {}, "reasoning": "规划器初始化默认", "is_parallel": True},
"chat_context": "",
"action_prompt": "",
}
# 检查是否应该跳过规划
if self.action_modifier.should_skip_planning():
logger.debug(f"[{self.stream_name}] 没有可用动作,跳过规划")
return None
self.action_type = "no_action"
return no_action
# 执行规划
plan_result = await self.planner.plan(message, sender_name)
action_type = plan_result["action_result"]["action_type"]
action_data = plan_result["action_result"]["action_data"]
reasoning = plan_result["action_result"]["reasoning"]
is_parallel = plan_result["action_result"].get("is_parallel", False)
logger.info(f"[{self.stream_name}] Planner决策: {action_type}, 理由: {reasoning}")
logger.info(f"[{self.stream_name}] Planner决策: {action_type}, 理由: {reasoning}, 并行执行: {is_parallel}")
self.action_type = action_type # 更新实例属性
self.is_parallel_action = is_parallel # 新增:保存并行执行标志
# 如果规划器决定不执行任何动作
if action_type == "no_action":
logger.debug(f"[{self.stream_name}] Planner决定不执行任何额外动作")
return None
return no_action
elif action_type == "change_to_focus_chat":
logger.info(f"[{self.stream_name}] Planner决定切换到focus聊天模式")
return None
@@ -358,14 +355,15 @@ class NormalChat:
else:
logger.warning(f"[{self.stream_name}] 额外动作 {action_type} 执行失败")
return {"action_type": action_type, "action_data": action_data, "reasoning": reasoning}
return {"action_type": action_type, "action_data": action_data, "reasoning": reasoning, "is_parallel": is_parallel}
except Exception as e:
logger.error(f"[{self.stream_name}] Planner执行失败: {e}")
return None
return no_action
# 并行执行回复生成和动作规划
self.action_type = None # 初始化动作类型
self.is_parallel_action = False # 初始化并行动作标志
with Timer("并行生成回复和规划", timing_results):
response_set, plan_result = await asyncio.gather(
generate_normal_response(), plan_and_execute_actions(), return_exceptions=True
@@ -382,15 +380,15 @@ class NormalChat:
if isinstance(plan_result, Exception):
logger.error(f"[{self.stream_name}] 动作规划异常: {plan_result}")
elif plan_result:
logger.debug(f"[{self.stream_name}] 额外动作处理完成: {plan_result['action_type']}")
logger.debug(f"[{self.stream_name}] 额外动作处理完成: {self.action_type}")
if not response_set or (
self.enable_planner and self.action_type not in ["no_action", "change_to_focus_chat"]
self.enable_planner and self.action_type not in ["no_action", "change_to_focus_chat"] and not self.is_parallel_action
):
if not response_set:
logger.info(f"[{self.stream_name}] 模型未生成回复内容")
elif self.enable_planner and self.action_type not in ["no_action", "change_to_focus_chat"]:
logger.info(f"[{self.stream_name}] 模型选择其他动作")
elif self.enable_planner and self.action_type not in ["no_action", "change_to_focus_chat"] and not self.is_parallel_action:
logger.info(f"[{self.stream_name}] 模型选择其他动作(非并行动作)")
# 如果模型未生成回复,移除思考消息
container = await message_manager.get_container(self.stream_id) # 使用 self.stream_id
for msg in container.messages[:]:
@@ -446,7 +444,7 @@ class NormalChat:
logger.warning(f"[{self.stream_name}] 没有设置切换到focus聊天模式的回调函数无法执行切换")
return
else:
await self._check_switch_to_focus()
# await self._check_switch_to_focus()
pass
info_catcher.done_catch()

View File

@@ -1,6 +1,11 @@
from typing import List, Any
from typing import List, Any, Dict
from src.common.logger_manager import get_logger
from src.chat.focus_chat.planners.action_manager import ActionManager
from src.chat.focus_chat.planners.actions.base_action import ActionActivationType, ChatMode
from src.chat.utils.chat_message_builder import build_readable_messages, get_raw_msg_before_timestamp_with_chat
from src.config.config import global_config
import random
import time
logger = get_logger("normal_chat_action_modifier")
@@ -9,6 +14,7 @@ class NormalChatActionModifier:
"""Normal Chat动作修改器
负责根据Normal Chat的上下文和状态动态调整可用的动作集合
实现与Focus Chat类似的动作激活策略但将LLM_JUDGE转换为概率激活以提升性能
"""
def __init__(self, action_manager: ActionManager, stream_id: str, stream_name: str):
@@ -25,9 +31,14 @@ class NormalChatActionModifier:
self,
chat_stream,
recent_replies: List[dict],
message_content: str,
**kwargs: Any,
):
"""为Normal Chat修改可用动作集合
实现动作激活策略:
1. 基于关联类型的动态过滤
2. 基于激活类型的智能判定LLM_JUDGE转为概率激活
Args:
chat_stream: 聊天流对象
@@ -35,24 +46,19 @@ class NormalChatActionModifier:
**kwargs: 其他参数
"""
# 合并所有动作变更
merged_action_changes = {"add": [], "remove": []}
reasons = []
merged_action_changes = {"add": [], "remove": []}
type_mismatched_actions = [] # 在外层定义避免作用域问题
self.action_manager.restore_default_actions()
# 1. 移除Normal Chat不适用的动作
excluded_actions = ["exit_focus_chat_action", "no_reply", "reply"]
for action_name in excluded_actions:
if action_name in self.action_manager.get_using_actions():
merged_action_changes["remove"].append(action_name)
reasons.append(f"移除{action_name}(Normal Chat不适用)")
# 2. 检查动作的关联类型
# 第一阶段:基于关联类型的动态过滤
if chat_stream:
chat_context = chat_stream.context if hasattr(chat_stream, "context") else None
if chat_context:
type_mismatched_actions = []
current_using_actions = self.action_manager.get_using_actions()
# 获取Normal模式下的可用动作已经过滤了mode_enable
current_using_actions = self.action_manager.get_using_actions_for_mode(ChatMode.NORMAL)
# print(f"current_using_actions: {current_using_actions}")
for action_name in current_using_actions.keys():
if action_name in self.all_actions:
data = self.all_actions[action_name]
@@ -65,26 +71,218 @@ class NormalChatActionModifier:
merged_action_changes["remove"].extend(type_mismatched_actions)
reasons.append(f"移除{type_mismatched_actions}(关联类型不匹配)")
# 应用动作变更
# 第二阶段:应用激活类型判定
# 构建聊天内容 - 使用与planner一致的方式
chat_content = ""
if chat_stream and hasattr(chat_stream, 'stream_id'):
try:
# 获取消息历史使用与normal_chat_planner相同的方法
message_list_before_now = get_raw_msg_before_timestamp_with_chat(
chat_id=chat_stream.stream_id,
timestamp=time.time(),
limit=global_config.focus_chat.observation_context_size, # 使用相同的配置
)
# 构建可读的聊天上下文
chat_content = build_readable_messages(
message_list_before_now,
replace_bot_name=True,
merge_messages=False,
timestamp_mode="relative",
read_mark=0.0,
show_actions=True,
)
logger.debug(f"{self.log_prefix} 成功构建聊天内容,长度: {len(chat_content)}")
except Exception as e:
logger.warning(f"{self.log_prefix} 构建聊天内容失败: {e}")
chat_content = ""
# 获取当前Normal模式下的动作集进行激活判定
current_actions = self.action_manager.get_using_actions_for_mode(ChatMode.NORMAL)
# print(f"current_actions: {current_actions}")
# print(f"chat_content: {chat_content}")
final_activated_actions = await self._apply_normal_activation_filtering(
current_actions,
chat_content,
message_content
)
# print(f"final_activated_actions: {final_activated_actions}")
# 统一处理所有需要移除的动作,避免重复移除
all_actions_to_remove = set() # 使用set避免重复
# 添加关联类型不匹配的动作
if type_mismatched_actions:
all_actions_to_remove.update(type_mismatched_actions)
# 添加激活类型判定未通过的动作
for action_name in current_actions.keys():
if action_name not in final_activated_actions:
all_actions_to_remove.add(action_name)
# 统计移除原因(避免重复)
activation_failed_actions = [name for name in current_actions.keys() if name not in final_activated_actions and name not in type_mismatched_actions]
if activation_failed_actions:
reasons.append(f"移除{activation_failed_actions}(激活类型判定未通过)")
# 统一执行移除操作
for action_name in all_actions_to_remove:
success = self.action_manager.remove_action_from_using(action_name)
if success:
logger.debug(f"{self.log_prefix} 移除动作: {action_name}")
else:
logger.debug(f"{self.log_prefix} 动作 {action_name} 已经不在使用集中,跳过移除")
# 应用动作添加(如果有的话)
for action_name in merged_action_changes["add"]:
if action_name in self.all_actions and action_name not in excluded_actions:
if action_name in self.all_actions:
success = self.action_manager.add_action_to_using(action_name)
if success:
logger.debug(f"{self.log_prefix} 添加动作: {action_name}")
for action_name in merged_action_changes["remove"]:
success = self.action_manager.remove_action_from_using(action_name)
if success:
logger.debug(f"{self.log_prefix} 移除动作: {action_name}")
# 记录变更原因
if merged_action_changes["add"] or merged_action_changes["remove"]:
if reasons:
logger.info(f"{self.log_prefix} 动作调整完成: {' | '.join(reasons)}")
logger.debug(f"{self.log_prefix} 当前可用动作: {list(self.action_manager.get_using_actions().keys())}")
# 获取最终的Normal模式可用动作并记录
final_actions = self.action_manager.get_using_actions_for_mode(ChatMode.NORMAL)
logger.debug(f"{self.log_prefix} 当前Normal模式可用动作: {list(final_actions.keys())}")
async def _apply_normal_activation_filtering(
self,
actions_with_info: Dict[str, Any],
chat_content: str = "",
message_content: str = "",
) -> Dict[str, Any]:
"""
应用Normal模式的激活类型过滤逻辑
与Focus模式的区别
1. LLM_JUDGE类型转换为概率激活避免LLM调用
2. RANDOM类型保持概率激活
3. KEYWORD类型保持关键词匹配
4. ALWAYS类型直接激活
Args:
actions_with_info: 带完整信息的动作字典
chat_content: 聊天内容
Returns:
Dict[str, Any]: 过滤后激活的actions字典
"""
activated_actions = {}
# 分类处理不同激活类型的actions
always_actions = {}
random_actions = {}
keyword_actions = {}
for action_name, action_info in actions_with_info.items():
# 使用normal_activation_type
activation_type = action_info.get("normal_activation_type", ActionActivationType.ALWAYS)
if activation_type == ActionActivationType.ALWAYS:
always_actions[action_name] = action_info
elif activation_type == ActionActivationType.RANDOM or activation_type == ActionActivationType.LLM_JUDGE:
random_actions[action_name] = action_info
elif activation_type == ActionActivationType.KEYWORD:
keyword_actions[action_name] = action_info
else:
logger.warning(f"{self.log_prefix}未知的激活类型: {activation_type},跳过处理")
# 1. 处理ALWAYS类型直接激活
for action_name, action_info in always_actions.items():
activated_actions[action_name] = action_info
logger.debug(f"{self.log_prefix}激活动作: {action_name},原因: ALWAYS类型直接激活")
# 2. 处理RANDOM类型概率激活
for action_name, action_info in random_actions.items():
probability = action_info.get("random_probability", 0.3)
should_activate = random.random() < probability
if should_activate:
activated_actions[action_name] = action_info
logger.info(f"{self.log_prefix}激活动作: {action_name},原因: RANDOM类型触发概率{probability}")
else:
logger.debug(f"{self.log_prefix}未激活动作: {action_name},原因: RANDOM类型未触发概率{probability}")
# 3. 处理KEYWORD类型关键词匹配
for action_name, action_info in keyword_actions.items():
should_activate = self._check_keyword_activation(
action_name,
action_info,
chat_content,
message_content
)
if should_activate:
activated_actions[action_name] = action_info
keywords = action_info.get("activation_keywords", [])
logger.info(f"{self.log_prefix}激活动作: {action_name},原因: KEYWORD类型匹配关键词{keywords}")
else:
keywords = action_info.get("activation_keywords", [])
logger.info(f"{self.log_prefix}未激活动作: {action_name},原因: KEYWORD类型未匹配关键词{keywords}")
# print(f"keywords: {keywords}")
# print(f"chat_content: {chat_content}")
logger.debug(f"{self.log_prefix}Normal模式激活类型过滤完成: {list(activated_actions.keys())}")
return activated_actions
def _check_keyword_activation(
self,
action_name: str,
action_info: Dict[str, Any],
chat_content: str = "",
message_content: str = "",
) -> bool:
"""
检查是否匹配关键词触发条件
Args:
action_name: 动作名称
action_info: 动作信息
chat_content: 聊天内容(已经是格式化后的可读消息)
Returns:
bool: 是否应该激活此action
"""
activation_keywords = action_info.get("activation_keywords", [])
case_sensitive = action_info.get("keyword_case_sensitive", False)
if not activation_keywords:
logger.warning(f"{self.log_prefix}动作 {action_name} 设置为关键词触发但未配置关键词")
return False
# 使用构建好的聊天内容作为检索文本
search_text = chat_content +message_content
# 如果不区分大小写,转换为小写
if not case_sensitive:
search_text = search_text.lower()
# 检查每个关键词
matched_keywords = []
for keyword in activation_keywords:
check_keyword = keyword if case_sensitive else keyword.lower()
if check_keyword in search_text:
matched_keywords.append(keyword)
# print(f"search_text: {search_text}")
# print(f"activation_keywords: {activation_keywords}")
if matched_keywords:
logger.info(f"{self.log_prefix}动作 {action_name} 匹配到关键词: {matched_keywords}")
return True
else:
logger.info(f"{self.log_prefix}动作 {action_name} 未匹配到任何关键词: {activation_keywords}")
return False
def get_available_actions_count(self) -> int:
"""获取当前可用动作数量排除默认的no_action"""
current_actions = self.action_manager.get_using_actions()
current_actions = self.action_manager.get_using_actions_for_mode(ChatMode.NORMAL)
# 排除no_action如果存在
filtered_actions = {k: v for k, v in current_actions.items() if k != "no_action"}
return len(filtered_actions)

View File

@@ -7,6 +7,7 @@ from src.common.logger_manager import get_logger
from src.chat.utils.prompt_builder import Prompt, global_prompt_manager
from src.individuality.individuality import individuality
from src.chat.focus_chat.planners.action_manager import ActionManager
from src.chat.focus_chat.planners.actions.base_action import ChatMode
from src.chat.message_receive.message import MessageThinking
from json_repair import repair_json
from src.chat.utils.chat_message_builder import build_readable_messages, get_raw_msg_before_timestamp_with_chat
@@ -98,16 +99,18 @@ class NormalChatPlanner:
self_info = name_block + personality_block + identity_block
# 获取当前可用的动作
current_available_actions = self.action_manager.get_using_actions()
# 获取当前可用的动作使用Normal模式过滤
current_available_actions = self.action_manager.get_using_actions_for_mode(ChatMode.NORMAL)
# 注意:动作的激活判定现在在 normal_chat_action_modifier 中完成
# 这里直接使用经过 action_modifier 处理后的最终动作集
# 符合职责分离原则ActionModifier负责动作管理Planner专注于决策
# 如果没有可用动作或只有no_action动作直接返回no_action
if not current_available_actions or (
len(current_available_actions) == 1 and "no_action" in current_available_actions
):
logger.debug(f"{self.log_prefix}规划器: 没有可用动作或只有no_action动作返回no_action")
# 如果没有可用动作直接返回no_action
if not current_available_actions:
logger.debug(f"{self.log_prefix}规划器: 没有可用动作返回no_action")
return {
"action_result": {"action_type": action, "action_data": action_data, "reasoning": reasoning},
"action_result": {"action_type": action, "action_data": action_data, "reasoning": reasoning, "is_parallel": True},
"chat_context": "",
"action_prompt": "",
}
@@ -138,7 +141,7 @@ class NormalChatPlanner:
if not prompt:
logger.warning(f"{self.log_prefix}规划器: 构建提示词失败")
return {
"action_result": {"action_type": action, "action_data": action_data, "reasoning": reasoning},
"action_result": {"action_type": action, "action_data": action_data, "reasoning": reasoning, "is_parallel": False},
"chat_context": chat_context,
"action_prompt": "",
}
@@ -185,13 +188,21 @@ class NormalChatPlanner:
except Exception as outer_e:
logger.error(f"{self.log_prefix}规划器异常: {outer_e}")
chat_context = "无法获取聊天上下文" # 设置默认值
prompt = "" # 设置默认值
# 设置异常时的默认值
current_available_actions = {}
chat_context = "无法获取聊天上下文"
prompt = ""
action = "no_action"
reasoning = "规划器出现异常,使用默认动作"
action_data = {}
logger.debug(f"{self.log_prefix}规划器决策动作:{action}, 动作信息: '{action_data}', 理由: {reasoning}")
# 检查动作是否支持并行执行
is_parallel = False
if action in current_available_actions:
action_info = current_available_actions[action]
is_parallel = action_info.get("parallel_action", False)
logger.debug(f"{self.log_prefix}规划器决策动作:{action}, 动作信息: '{action_data}', 理由: {reasoning}, 并行执行: {is_parallel}")
# 恢复到默认动作集
self.action_manager.restore_actions()
@@ -212,6 +223,7 @@ class NormalChatPlanner:
"action_type": action,
"action_data": action_data,
"reasoning": reasoning,
"is_parallel": is_parallel,
"action_record": json.dumps(action_record, ensure_ascii=False)
}
@@ -304,4 +316,6 @@ class NormalChatPlanner:
return ""
init_prompt()