diff --git a/src/chat/heart_flow/heartFC_chat - 副本.py b/src/chat/heart_flow/heartFC_chat - 副本.py new file mode 100644 index 00000000..c805597d --- /dev/null +++ b/src/chat/heart_flow/heartFC_chat - 副本.py @@ -0,0 +1,734 @@ +import asyncio +import time +import traceback +import random +from typing import List, Optional, Dict, Any, Tuple, TYPE_CHECKING +from rich.traceback import install + +from src.config.config import global_config +from src.common.logger import get_logger +from src.common.data_models.info_data_model import ActionPlannerInfo +from src.common.data_models.message_data_model import ReplyContentType +from src.chat.message_receive.chat_stream import ChatStream, get_chat_manager +from src.chat.utils.prompt_builder import global_prompt_manager +from src.chat.utils.timer_calculator import Timer +from src.chat.planner_actions.planner import ActionPlanner +from src.chat.planner_actions.action_modifier import ActionModifier +from src.chat.planner_actions.action_manager import ActionManager +from src.chat.heart_flow.hfc_utils import CycleDetail +from src.bw_learner.expression_learner import expression_learner_manager +from src.chat.heart_flow.frequency_control import frequency_control_manager +from src.bw_learner.message_recorder import extract_and_distribute_messages +from src.person_info.person_info import Person +from src.plugin_system.base.component_types import EventType, ActionInfo +from src.plugin_system.core import events_manager +from src.plugin_system.apis import generator_api, send_api, message_api, database_api +from src.chat.utils.chat_message_builder import ( + build_readable_messages_with_id, + get_raw_msg_before_timestamp_with_chat, +) +from src.chat.utils.utils import record_replyer_action_temp +from src.memory_system.chat_history_summarizer import ChatHistorySummarizer + +if TYPE_CHECKING: + from src.common.data_models.database_data_model import DatabaseMessages + from src.common.data_models.message_data_model import ReplySetModel + + +ERROR_LOOP_INFO = { + "loop_plan_info": { + "action_result": { + "action_type": "error", + "action_data": {}, + "reasoning": "循环处理失败", + }, + }, + "loop_action_info": { + "action_taken": False, + "reply_text": "", + "command": "", + "taken_time": time.time(), + }, +} + + +install(extra_lines=3) + +# 注释:原来的动作修改超时常量已移除,因为改为顺序执行 + +logger = get_logger("hfc") # Logger Name Changed + + +class HeartFChatting: + """ + 管理一个连续的Focus Chat循环 + 用于在特定聊天流中生成回复。 + 其生命周期现在由其关联的 SubHeartflow 的 FOCUSED 状态控制。 + """ + + def __init__(self, chat_id: str): + """ + HeartFChatting 初始化函数 + + 参数: + chat_id: 聊天流唯一标识符(如stream_id) + on_stop_focus_chat: 当收到stop_focus_chat命令时调用的回调函数 + performance_version: 性能记录版本号,用于区分不同启动版本 + """ + # 基础属性 + self.stream_id: str = chat_id # 聊天流ID + self.chat_stream: ChatStream = get_chat_manager().get_stream(self.stream_id) # type: ignore + if not self.chat_stream: + raise ValueError(f"无法找到聊天流: {self.stream_id}") + self.log_prefix = f"[{get_chat_manager().get_stream_name(self.stream_id) or self.stream_id}]" + + self.expression_learner = expression_learner_manager.get_expression_learner(self.stream_id) + + self.action_manager = ActionManager() + self.action_planner = ActionPlanner(chat_id=self.stream_id, action_manager=self.action_manager) + self.action_modifier = ActionModifier(action_manager=self.action_manager, chat_id=self.stream_id) + + # 循环控制内部状态 + self.running: bool = False + self._loop_task: Optional[asyncio.Task] = None # 主循环任务 + + # 添加循环信息管理相关的属性 + self.history_loop: List[CycleDetail] = [] + self._cycle_counter = 0 + self._current_cycle_detail: CycleDetail = None # type: ignore + + self.last_read_time = time.time() - 2 + + self.is_mute = False + + self.last_active_time = time.time() # 记录上一次非noreply时间 + + self.question_probability_multiplier = 1 + self.questioned = False + + # 跟踪连续 no_reply 次数,用于动态调整阈值 + self.consecutive_no_reply_count = 0 + + # 聊天内容概括器 + self.chat_history_summarizer = ChatHistorySummarizer(chat_id=self.stream_id) + + async def start(self): + """检查是否需要启动主循环,如果未激活则启动。""" + + # 如果循环已经激活,直接返回 + if self.running: + logger.debug(f"{self.log_prefix} HeartFChatting 已激活,无需重复启动") + return + + try: + # 标记为活动状态,防止重复启动 + self.running = True + + self._loop_task = asyncio.create_task(self._main_chat_loop()) + self._loop_task.add_done_callback(self._handle_loop_completion) + + # 启动聊天内容概括器的后台定期检查循环 + await self.chat_history_summarizer.start() + + logger.info(f"{self.log_prefix} HeartFChatting 启动完成") + + except Exception as e: + # 启动失败时重置状态 + self.running = False + self._loop_task = None + logger.error(f"{self.log_prefix} HeartFChatting 启动失败: {e}") + raise + + def _handle_loop_completion(self, task: asyncio.Task): + """当 _hfc_loop 任务完成时执行的回调。""" + try: + if exception := task.exception(): + logger.error(f"{self.log_prefix} HeartFChatting: 脱离了聊天(异常): {exception}") + logger.error(traceback.format_exc()) # Log full traceback for exceptions + else: + logger.info(f"{self.log_prefix} HeartFChatting: 脱离了聊天 (外部停止)") + except asyncio.CancelledError: + logger.info(f"{self.log_prefix} HeartFChatting: 结束了聊天") + + def start_cycle(self) -> Tuple[Dict[str, float], str]: + self._cycle_counter += 1 + self._current_cycle_detail = CycleDetail(self._cycle_counter) + self._current_cycle_detail.thinking_id = f"tid{str(round(time.time(), 2))}" + cycle_timers = {} + return cycle_timers, self._current_cycle_detail.thinking_id + + def end_cycle(self, loop_info, cycle_timers): + self._current_cycle_detail.set_loop_info(loop_info) + self.history_loop.append(self._current_cycle_detail) + self._current_cycle_detail.timers = cycle_timers + self._current_cycle_detail.end_time = time.time() + + def print_cycle_info(self, cycle_timers): + # 记录循环信息和计时器结果 + timer_strings = [] + for name, elapsed in cycle_timers.items(): + if elapsed < 0.1: + # 不显示小于0.1秒的计时器 + continue + formatted_time = f"{elapsed:.2f}秒" + timer_strings.append(f"{name}: {formatted_time}") + + logger.info( + f"{self.log_prefix} 第{self._current_cycle_detail.cycle_id}次思考," + f"耗时: {self._current_cycle_detail.end_time - self._current_cycle_detail.start_time:.1f}秒;" # type: ignore + + (f"详情: {'; '.join(timer_strings)}" if timer_strings else "") + ) + + async def _loopbody(self): + recent_messages_list = message_api.get_messages_by_time_in_chat( + chat_id=self.stream_id, + start_time=self.last_read_time, + end_time=time.time(), + limit=20, + limit_mode="latest", + filter_mai=True, + filter_command=False, + filter_intercept_message_level=0, + ) + + # 根据连续 no_reply 次数动态调整阈值 + # 3次 no_reply 时,阈值调高到 1.5(50%概率为1,50%概率为2) + # 5次 no_reply 时,提高到 2(大于等于两条消息的阈值) + if self.consecutive_no_reply_count >= 5: + threshold = 2 + elif self.consecutive_no_reply_count >= 3: + # 1.5 的含义:50%概率为1,50%概率为2 + threshold = 2 if random.random() < 0.5 else 1 + else: + threshold = 1 + + if len(recent_messages_list) >= threshold: + # for message in recent_messages_list: + # print(message.processed_plain_text) + + self.last_read_time = time.time() + + # !此处使at或者提及必定回复 + mentioned_message = None + for message in recent_messages_list: + if (message.is_mentioned or message.is_at) and global_config.chat.mentioned_bot_reply: + mentioned_message = message + + # logger.info(f"{self.log_prefix} 当前talk_value: {global_config.chat.get_talk_value(self.stream_id)}") + + # *控制频率用 + if mentioned_message: + await self._observe(recent_messages_list=recent_messages_list, force_reply_message=mentioned_message) + elif ( + random.random() + < global_config.chat.get_talk_value(self.stream_id) + * frequency_control_manager.get_or_create_frequency_control(self.stream_id).get_talk_frequency_adjust() + ): + await self._observe(recent_messages_list=recent_messages_list) + else: + # 没有提到,继续保持沉默,等待5秒防止频繁触发 + await asyncio.sleep(10) + return True + else: + await asyncio.sleep(0.2) + return True + return True + + async def _send_and_store_reply( + self, + response_set: "ReplySetModel", + action_message: "DatabaseMessages", + cycle_timers: Dict[str, float], + thinking_id, + actions, + selected_expressions: Optional[List[int]] = None, + quote_message: Optional[bool] = None, + ) -> Tuple[Dict[str, Any], str, Dict[str, float]]: + with Timer("回复发送", cycle_timers): + reply_text = await self._send_response( + reply_set=response_set, + message_data=action_message, + selected_expressions=selected_expressions, + quote_message=quote_message, + ) + + # 获取 platform,如果不存在则从 chat_stream 获取,如果还是 None 则使用默认值 + platform = action_message.chat_info.platform + if platform is None: + platform = getattr(self.chat_stream, "platform", "unknown") + + person = Person(platform=platform, user_id=action_message.user_info.user_id) + person_name = person.person_name + action_prompt_display = f"你对{person_name}进行了回复:{reply_text}" + + await database_api.store_action_info( + chat_stream=self.chat_stream, + action_build_into_prompt=False, + action_prompt_display=action_prompt_display, + action_done=True, + thinking_id=thinking_id, + action_data={"reply_text": reply_text}, + action_name="reply", + ) + + # 构建循环信息 + loop_info: Dict[str, Any] = { + "loop_plan_info": { + "action_result": actions, + }, + "loop_action_info": { + "action_taken": True, + "reply_text": reply_text, + "command": "", + "taken_time": time.time(), + }, + } + + return loop_info, reply_text, cycle_timers + + async def _observe( + self, # interest_value: float = 0.0, + recent_messages_list: Optional[List["DatabaseMessages"]] = None, + force_reply_message: Optional["DatabaseMessages"] = None, + ) -> bool: # sourcery skip: merge-else-if-into-elif, remove-redundant-if + if recent_messages_list is None: + recent_messages_list = [] + _reply_text = "" # 初始化reply_text变量,避免UnboundLocalError + + start_time = time.time() + async with global_prompt_manager.async_message_scope(self.chat_stream.context.get_template_name()): + # 通过 MessageRecorder 统一提取消息并分发给 expression_learner 和 jargon_miner + # 在 replyer 执行时触发,统一管理时间窗口,避免重复获取消息 + asyncio.create_task(extract_and_distribute_messages(self.stream_id)) + + # 添加curious检测任务 - 检测聊天记录中的矛盾、冲突或需要提问的内容 + # asyncio.create_task(check_and_make_question(self.stream_id)) + # 添加聊天内容概括任务 - 累积、打包和压缩聊天记录 + # 注意:后台循环已在start()中启动,这里作为额外触发点,在有思考时立即处理 + # asyncio.create_task(self.chat_history_summarizer.process()) + + cycle_timers, thinking_id = self.start_cycle() + logger.info( + f"{self.log_prefix} 开始第{self._cycle_counter}次思考(频率: {global_config.chat.get_talk_value(self.stream_id)})" + ) + + # 第一步:动作检查 + available_actions: Dict[str, ActionInfo] = {} + try: + await self.action_modifier.modify_actions() + available_actions = self.action_manager.get_using_actions() + except Exception as e: + logger.error(f"{self.log_prefix} 动作修改失败: {e}") + + # 执行planner + is_group_chat, chat_target_info, _ = self.action_planner.get_necessary_info() + + message_list_before_now = get_raw_msg_before_timestamp_with_chat( + chat_id=self.stream_id, + timestamp=time.time(), + limit=int(global_config.chat.max_context_size * 0.6), + filter_intercept_message_level=1, + ) + chat_content_block, message_id_list = build_readable_messages_with_id( + messages=message_list_before_now, + timestamp_mode="normal_no_YMD", + read_mark=self.action_planner.last_obs_time_mark, + truncate=True, + show_actions=True, + ) + + prompt_info = await self.action_planner.build_planner_prompt( + is_group_chat=is_group_chat, + chat_target_info=chat_target_info, + current_available_actions=available_actions, + chat_content_block=chat_content_block, + message_id_list=message_id_list, + ) + continue_flag, modified_message = await events_manager.handle_mai_events( + EventType.ON_PLAN, None, prompt_info[0], None, self.chat_stream.stream_id + ) + if not continue_flag: + return False + if modified_message and modified_message._modify_flags.modify_llm_prompt: + prompt_info = (modified_message.llm_prompt, prompt_info[1]) + + with Timer("规划器", cycle_timers): + action_to_use_info = await self.action_planner.plan( + loop_start_time=self.last_read_time, + available_actions=available_actions, + force_reply_message=force_reply_message, + ) + + logger.info( + f"{self.log_prefix} 决定执行{len(action_to_use_info)}个动作: {' '.join([a.action_type for a in action_to_use_info])}" + ) + + # 3. 并行执行所有动作 + action_tasks = [ + asyncio.create_task( + self._execute_action(action, action_to_use_info, thinking_id, available_actions, cycle_timers) + ) + for action in action_to_use_info + ] + + # 并行执行所有任务 + results = await asyncio.gather(*action_tasks, return_exceptions=True) + + # 处理执行结果 + reply_loop_info = None + reply_text_from_reply = "" + action_success = False + action_reply_text = "" + + excute_result_str = "" + for result in results: + excute_result_str += f"{result['action_type']} 执行结果:{result['result']}\n" + + if isinstance(result, BaseException): + logger.error(f"{self.log_prefix} 动作执行异常: {result}") + continue + + if result["action_type"] != "reply": + action_success = result["success"] + action_reply_text = result["result"] + elif result["action_type"] == "reply": + if result["success"]: + reply_loop_info = result["loop_info"] + reply_text_from_reply = result["result"] + else: + logger.warning(f"{self.log_prefix} 回复动作执行失败") + + self.action_planner.add_plan_excute_log(result=excute_result_str) + + # 构建最终的循环信息 + if reply_loop_info: + # 如果有回复信息,使用回复的loop_info作为基础 + loop_info = reply_loop_info + # 更新动作执行信息 + loop_info["loop_action_info"].update( + { + "action_taken": action_success, + "taken_time": time.time(), + } + ) + _reply_text = reply_text_from_reply + else: + # 没有回复信息,构建纯动作的loop_info + loop_info = { + "loop_plan_info": { + "action_result": action_to_use_info, + }, + "loop_action_info": { + "action_taken": action_success, + "reply_text": action_reply_text, + "taken_time": time.time(), + }, + } + _reply_text = action_reply_text + + self.end_cycle(loop_info, cycle_timers) + self.print_cycle_info(cycle_timers) + + end_time = time.time() + if end_time - start_time < global_config.chat.planner_smooth: + wait_time = global_config.chat.planner_smooth - (end_time - start_time) + await asyncio.sleep(wait_time) + else: + await asyncio.sleep(0.1) + return True + + async def _main_chat_loop(self): + """主循环,持续进行计划并可能回复消息,直到被外部取消。""" + try: + while self.running: + # 主循环 + success = await self._loopbody() + await asyncio.sleep(0.1) + if not success: + break + except asyncio.CancelledError: + # 设置了关闭标志位后被取消是正常流程 + logger.info(f"{self.log_prefix} 麦麦已关闭聊天") + except Exception: + logger.error(f"{self.log_prefix} 麦麦聊天意外错误,将于3s后尝试重新启动") + print(traceback.format_exc()) + await asyncio.sleep(3) + self._loop_task = asyncio.create_task(self._main_chat_loop()) + logger.error(f"{self.log_prefix} 结束了当前聊天循环") + + async def _handle_action( + self, + action: str, + action_reasoning: str, + action_data: dict, + cycle_timers: Dict[str, float], + thinking_id: str, + action_message: Optional["DatabaseMessages"] = None, + ) -> tuple[bool, str, str]: + """ + 处理规划动作,使用动作工厂创建相应的动作处理器 + + 参数: + action: 动作类型 + action_reasoning: 决策理由 + action_data: 动作数据,包含不同动作需要的参数 + cycle_timers: 计时器字典 + thinking_id: 思考ID + action_message: 消息数据 + 返回: + tuple[bool, str, str]: (是否执行了动作, 思考消息ID, 命令) + """ + try: + # 使用工厂创建动作处理器实例 + try: + action_handler = self.action_manager.create_action( + action_name=action, + action_data=action_data, + cycle_timers=cycle_timers, + thinking_id=thinking_id, + chat_stream=self.chat_stream, + log_prefix=self.log_prefix, + action_reasoning=action_reasoning, + action_message=action_message, + ) + except Exception as e: + logger.error(f"{self.log_prefix} 创建动作处理器时出错: {e}") + traceback.print_exc() + return False, "" + + # 处理动作并获取结果(固定记录一次动作信息) + result = await action_handler.execute() + success, action_text = result + + return success, action_text + + except Exception as e: + logger.error(f"{self.log_prefix} 处理{action}时出错: {e}") + traceback.print_exc() + return False, "" + + async def _send_response( + self, + reply_set: "ReplySetModel", + message_data: "DatabaseMessages", + selected_expressions: Optional[List[int]] = None, + quote_message: Optional[bool] = None, + ) -> str: + # 根据 llm_quote 配置决定是否使用 quote_message 参数 + if global_config.chat.llm_quote: + # 如果配置为 true,使用 llm_quote 参数决定是否引用回复 + if quote_message is None: + logger.warning(f"{self.log_prefix} quote_message 参数为空,不引用") + need_reply = False + else: + need_reply = quote_message + if need_reply: + logger.info(f"{self.log_prefix} LLM 决定使用引用回复") + else: + # 如果配置为 false,使用原来的模式 + new_message_count = message_api.count_new_messages( + chat_id=self.chat_stream.stream_id, start_time=self.last_read_time, end_time=time.time() + ) + need_reply = new_message_count >= random.randint(2, 3) or time.time() - self.last_read_time > 90 + if need_reply: + logger.info(f"{self.log_prefix} 从思考到回复,共有{new_message_count}条新消息,使用引用回复,或者上次回复时间超过90秒") + + reply_text = "" + first_replied = False + for reply_content in reply_set.reply_data: + if reply_content.content_type != ReplyContentType.TEXT: + continue + data: str = reply_content.content # type: ignore + if not first_replied: + await send_api.text_to_stream( + text=data, + stream_id=self.chat_stream.stream_id, + reply_message=message_data, + set_reply=need_reply, + typing=False, + selected_expressions=selected_expressions, + ) + first_replied = True + else: + await send_api.text_to_stream( + text=data, + stream_id=self.chat_stream.stream_id, + reply_message=message_data, + set_reply=False, + typing=True, + selected_expressions=selected_expressions, + ) + reply_text += data + + return reply_text + + async def _execute_action( + self, + action_planner_info: ActionPlannerInfo, + chosen_action_plan_infos: List[ActionPlannerInfo], + thinking_id: str, + available_actions: Dict[str, ActionInfo], + cycle_timers: Dict[str, float], + ): + """执行单个动作的通用函数""" + try: + with Timer(f"动作{action_planner_info.action_type}", cycle_timers): + # 直接当场执行no_reply逻辑 + if action_planner_info.action_type == "no_reply": + # 直接处理no_reply逻辑,不再通过动作系统 + reason = action_planner_info.reasoning or "选择不回复" + # logger.info(f"{self.log_prefix} 选择不回复,原因: {reason}") + + # 增加连续 no_reply 计数 + self.consecutive_no_reply_count += 1 + + await database_api.store_action_info( + chat_stream=self.chat_stream, + action_build_into_prompt=False, + action_prompt_display=reason, + action_done=True, + thinking_id=thinking_id, + action_data={}, + action_name="no_reply", + action_reasoning=reason, + ) + + return {"action_type": "no_reply", "success": True, "result": "选择不回复", "command": ""} + + elif action_planner_info.action_type == "reply": + # 直接当场执行reply逻辑 + self.questioned = False + # 刷新主动发言状态 + # 重置连续 no_reply 计数 + self.consecutive_no_reply_count = 0 + + reason = action_planner_info.reasoning or "" + # 根据 think_mode 配置决定 think_level 的值 + think_mode = global_config.chat.think_mode + if think_mode == "default": + think_level = 0 + elif think_mode == "deep": + think_level = 1 + elif think_mode == "dynamic": + # dynamic 模式:从 planner 返回的 action_data 中获取 + think_level = action_planner_info.action_data.get("think_level", 1) + else: + # 默认使用 default 模式 + think_level = 0 + # 使用 action_reasoning(planner 的整体思考理由)作为 reply_reason + planner_reasoning = action_planner_info.action_reasoning or reason + + record_replyer_action_temp( + chat_id=self.stream_id, + reason=reason, + think_level=think_level, + ) + + await database_api.store_action_info( + chat_stream=self.chat_stream, + action_build_into_prompt=False, + action_prompt_display=reason, + action_done=True, + thinking_id=thinking_id, + action_data={}, + action_name="reply", + action_reasoning=reason, + ) + + # 从 Planner 的 action_data 中提取未知词语列表(仅在 reply 时使用) + unknown_words = None + quote_message = None + if isinstance(action_planner_info.action_data, dict): + uw = action_planner_info.action_data.get("unknown_words") + if isinstance(uw, list): + cleaned_uw: List[str] = [] + for item in uw: + if isinstance(item, str): + s = item.strip() + if s: + cleaned_uw.append(s) + if cleaned_uw: + unknown_words = cleaned_uw + + # 从 Planner 的 action_data 中提取 quote_message 参数 + qm = action_planner_info.action_data.get("quote") + if qm is not None: + # 支持多种格式:true/false, "true"/"false", 1/0 + if isinstance(qm, bool): + quote_message = qm + elif isinstance(qm, str): + quote_message = qm.lower() in ("true", "1", "yes") + elif isinstance(qm, (int, float)): + quote_message = bool(qm) + + logger.info(f"{self.log_prefix} {qm}引用回复设置: {quote_message}") + + success, llm_response = await generator_api.generate_reply( + chat_stream=self.chat_stream, + reply_message=action_planner_info.action_message, + available_actions=available_actions, + chosen_actions=chosen_action_plan_infos, + reply_reason=planner_reasoning, + unknown_words=unknown_words, + enable_tool=global_config.tool.enable_tool, + request_type="replyer", + from_plugin=False, + reply_time_point=action_planner_info.action_data.get("loop_start_time", time.time()), + think_level=think_level, + ) + + if not success or not llm_response or not llm_response.reply_set: + if action_planner_info.action_message: + logger.info(f"对 {action_planner_info.action_message.processed_plain_text} 的回复生成失败") + else: + logger.info("回复生成失败") + return {"action_type": "reply", "success": False, "result": "回复生成失败", "loop_info": None} + + response_set = llm_response.reply_set + selected_expressions = llm_response.selected_expressions + loop_info, reply_text, _ = await self._send_and_store_reply( + response_set=response_set, + action_message=action_planner_info.action_message, # type: ignore + cycle_timers=cycle_timers, + thinking_id=thinking_id, + actions=chosen_action_plan_infos, + selected_expressions=selected_expressions, + quote_message=quote_message, + ) + self.last_active_time = time.time() + return { + "action_type": "reply", + "success": True, + "result": f"你使用reply动作,对' {action_planner_info.action_message.processed_plain_text} '这句话进行了回复,回复内容为: '{reply_text}'", + "loop_info": loop_info, + } + + else: + # 执行普通动作 + with Timer("动作执行", cycle_timers): + success, result = await self._handle_action( + action=action_planner_info.action_type, + action_reasoning=action_planner_info.action_reasoning or "", + action_data=action_planner_info.action_data or {}, + cycle_timers=cycle_timers, + thinking_id=thinking_id, + action_message=action_planner_info.action_message, + ) + + self.last_active_time = time.time() + return { + "action_type": action_planner_info.action_type, + "success": success, + "result": result, + } + + except Exception as e: + logger.error(f"{self.log_prefix} 执行动作时出错: {e}") + logger.error(f"{self.log_prefix} 错误信息: {traceback.format_exc()}") + return { + "action_type": action_planner_info.action_type, + "success": False, + "result": "", + "loop_info": None, + "error": str(e), + } diff --git a/src/chat/heart_flow/heartFC_chat.py b/src/chat/heart_flow/heartFC_chat.py index 3778a62f..af0beb4e 100644 --- a/src/chat/heart_flow/heartFC_chat.py +++ b/src/chat/heart_flow/heartFC_chat.py @@ -1,231 +1,377 @@ -from rich.traceback import install -from typing import Optional, List, TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import asyncio +import random import time import traceback -import random -from src.common.logger import get_logger -from src.common.utils.utils_config import ExpressionConfigUtils, ChatConfigUtils -from src.config.config import global_config -from src.config.file_watcher import FileChange -from src.chat.message_receive.chat_manager import chat_manager +from rich.traceback import install + from src.bw_learner.expression_learner import ExpressionLearner from src.bw_learner.jargon_miner import JargonMiner +from src.chat.event_helpers import build_event_message +from src.chat.logger.plan_reply_logger import PlanReplyLogger +from src.chat.message_receive.chat_manager import BotChatSession +from src.chat.message_receive.chat_manager import chat_manager as _chat_manager +from src.chat.planner_actions.action_manager import ActionManager +from src.chat.planner_actions.action_modifier import ActionModifier +from src.chat.planner_actions.planner import ActionPlanner +from src.chat.utils.prompt_builder import global_prompt_manager +from src.chat.utils.timer_calculator import Timer +from src.chat.utils.utils import record_replyer_action_temp +from src.common.data_models.info_data_model import ActionPlannerInfo +from src.common.data_models.message_component_data_model import MessageSequence, TextComponent +from src.common.logger import get_logger +from src.common.utils.utils_config import ChatConfigUtils, ExpressionConfigUtils +from src.config.config import global_config +from src.config.file_watcher import FileChange +from src.core.event_bus import event_bus +from src.core.types import ActionInfo, EventType +from src.person_info.person_info import Person +from src.services import ( + database_service as database_api, + generator_service as generator_api, + message_service as message_api, + send_service as send_api, +) +from src.services.message_service import build_readable_messages_with_id, get_messages_before_time_in_chat from .heartFC_utils import CycleDetail if TYPE_CHECKING: from src.chat.message_receive.message import SessionMessage + install(extra_lines=5) logger = get_logger("heartFC_chat") class HeartFChatting: - """ - 管理一个连续的Focus Chat聊天会话 - 用于在特定的聊天会话里面生成回复 - """ + """管理一个持续运行的 Focus Chat 会话。""" def __init__(self, session_id: str): - """ - 初始化 HeartFChatting 实例 - - Args: - session_id: 聊天会话ID - """ - # 基础属性 self.session_id = session_id - session_name = chat_manager.get_session_name(session_id) or session_id + self.chat_stream: BotChatSession = _chat_manager.get_session_by_session_id(self.session_id) # type: ignore[assignment] + if not self.chat_stream: + raise ValueError(f"无法找到聊天会话 {self.session_id}") + + session_name = _chat_manager.get_session_name(session_id) or session_id self.log_prefix = f"[{session_name}]" self.session_name = session_name - # 系统运行状态 + self.action_manager = ActionManager() + self.action_planner = ActionPlanner(chat_id=self.session_id, action_manager=self.action_manager) + self.action_modifier = ActionModifier(action_manager=self.action_manager, chat_id=self.session_id) + self._running: bool = False self._loop_task: Optional[asyncio.Task] = None - self._cycle_counter: int = 0 - self._hfc_lock: asyncio.Lock = asyncio.Lock() # 用于保护 _hfc_func 的并发访问 - # 聊天频率相关 - self._consecutive_no_reply_count = 0 # 跟踪连续 no_reply 次数,用于动态调整阈值 - self._talk_frequency_adjust: float = 1.0 # 发言频率修正值,默认为1.0,可以根据需要调整 - - # HFC内消息缓存 - self.message_cache: List[SessionMessage] = [] - - # Asyncio Event 用于控制循环的开始和结束 self._cycle_event = asyncio.Event() + self._hfc_lock = asyncio.Lock() + + self._cycle_counter = 0 + self._current_cycle_detail: Optional[CycleDetail] = None + self.history_loop: List[CycleDetail] = [] + + self.last_read_time = time.time() - 2 + self.last_active_time = time.time() + self._talk_frequency_adjust = 1.0 + self._consecutive_no_reply_count = 0 + + self.message_cache: List["SessionMessage"] = [] + + self._min_messages_for_extraction = 30 + self._min_extraction_interval = 60 + self._last_extraction_time = 0.0 - # 表达方式相关内容 - self._min_messages_for_extraction = 30 # 最少提取消息数 - self._min_extraction_interval = 60 # 最小提取时间间隔,单位为秒 - self._last_extraction_time: float = 0.0 # 上次提取的时间戳 expr_use, jargon_learn, expr_learn = ExpressionConfigUtils.get_expression_config_for_chat(session_id) - self._enable_expression_use = expr_use # 允许使用表达方式,但不一定启用学习 - self._enable_expression_learning = expr_learn # 允许学习表达方式 - self._enable_jargon_learning = jargon_learn # 允许学习黑话 - # 表达学习器 - self._expression_learner: ExpressionLearner = ExpressionLearner(session_id) - # 黑话挖掘器 - self._jargon_miner: JargonMiner = JargonMiner(session_id, session_name=session_name) - - # TODO: ChatSummarizer 聊天总结器重构 - - # ====== 公开方法 ====== + self._enable_expression_use = expr_use + self._enable_expression_learning = expr_learn + self._enable_jargon_learning = jargon_learn + self._expression_learner = ExpressionLearner(session_id) + self._jargon_miner = JargonMiner(session_id, session_name=session_name) async def start(self): - """启动 HeartFChatting 的主循环""" - # 先检查是否已经启动运行 if self._running: - logger.debug(f"{self.log_prefix} 已经在运行中,无需重复启动") + logger.debug(f"{self.log_prefix} HeartFChatting 已在运行中") return try: self._running = True - self._cycle_event.clear() # 确保事件初始状态为未设置 - + self._cycle_event.clear() self._loop_task = asyncio.create_task(self.main_loop()) self._loop_task.add_done_callback(self._handle_loop_completion) - logger.info(f"{self.log_prefix} HeartFChatting 启动完成") - except Exception as e: - logger.error(f"{self.log_prefix} 启动 HeartFChatting 失败: {e}", exc_info=True) - self._running = False # 确保状态正确 - self._cycle_event.set() # 确保事件被设置,避免死锁 - self._loop_task = None # 确保任务引用被清理 + except Exception as exc: + logger.error(f"{self.log_prefix} HeartFChatting 启动失败: {exc}", exc_info=True) + self._running = False + self._cycle_event.set() + self._loop_task = None raise async def stop(self): - """停止 HeartFChatting 的主循环""" if not self._running: - logger.debug(f"{self.log_prefix} HeartFChatting 已经停止,无需重复停止") + logger.debug(f"{self.log_prefix} HeartFChatting 已停止") return self._running = False - self._cycle_event.set() # 触发事件,通知循环结束 + self._cycle_event.set() if self._loop_task: - self._loop_task.cancel() # 取消主循环任务 + self._loop_task.cancel() try: - await self._loop_task # 等待任务完成 + await self._loop_task except asyncio.CancelledError: - logger.info(f"{self.log_prefix} HeartFChatting 主循环已成功取消") - except Exception as e: - logger.error(f"{self.log_prefix} 停止 HeartFChatting 时发生错误: {e}", exc_info=True) + logger.info(f"{self.log_prefix} HeartFChatting 主循环已取消") + except Exception as exc: + logger.error(f"{self.log_prefix} 停止 HeartFChatting 时发生错误: {exc}", exc_info=True) finally: - self._loop_task = None # 确保任务引用被清理 + self._loop_task = None logger.info(f"{self.log_prefix} HeartFChatting 已停止") def adjust_talk_frequency(self, new_value: float): - """调整发言频率的调整值 - - Args: - new_value: 新的修正值,必须为非负数。值越大,修正发言频率越高;值越小,修正发言频率越低。 - """ self._talk_frequency_adjust = max(0.0, new_value) async def register_message(self, message: "SessionMessage"): - """注册一条消息到 HeartFChatting 的缓存中,并检测其是否产生提及,决定是否唤醒聊天 - - Args: - message: 待注册的消息对象 - """ self.message_cache.append(message) - # 先检查at必回复 + if global_config.chat.inevitable_at_reply and message.is_at: - async with self._hfc_lock: # 确保与主循环逻辑的互斥访问 - await self._judge_and_response(message) - return # 直接返回,避免同一条消息被主循环再次处理 - # 再检查提及必回复 + self.last_read_time = time.time() + async with self._hfc_lock: + await self._judge_and_response(mentioned_message=message, recent_messages_list=[message]) + return + if global_config.chat.mentioned_bot_reply and message.is_mentioned: - # 直接获取锁,确保一定一定触发回复逻辑,不受当前是否正在执行主循环的影响 - async with self._hfc_lock: # 确保与主循环逻辑的互斥访问 - await self._judge_and_response(message) + self.last_read_time = time.time() + async with self._hfc_lock: + await self._judge_and_response(mentioned_message=message, recent_messages_list=[message]) return async def main_loop(self): try: while self._running and not self._cycle_event.is_set(): if not self._hfc_lock.locked(): - async with self._hfc_lock: # 确保主循环逻辑的互斥访问 + async with self._hfc_lock: await self._hfc_func() - await asyncio.sleep(5) + await asyncio.sleep(0.1) except asyncio.CancelledError: - logger.info(f"{self.log_prefix} HeartFChatting: 主循环被取消,正在关闭") - except Exception as e: - logger.error(f"{self.log_prefix} 麦麦聊天意外错误: {e},将于3s后尝试重新启动") - await self.stop() # 确保状态正确 + logger.info(f"{self.log_prefix} HeartFChatting: 主循环被取消") + except Exception as exc: + logger.error(f"{self.log_prefix} HeartFChatting: 主循环异常: {exc}", exc_info=True) + await self.stop() await asyncio.sleep(3) - await self.start() # 尝试重新启动 + await self.start() async def _config_callback(self, file_change: Optional[FileChange] = None): - """配置文件变更回调函数""" - # TODO: 根据配置文件变动重新计算相关参数: - """ - 需要计算的参数: - self._enable_expression_use = expr_use # 允许使用表达方式,但不一定启用学习 - self._enable_expression_learning = expr_learn # 允许学习表达方式 - self._enable_jargon_learning = jargon_learn # 允许学习黑话 - """ + del file_change + expr_use, jargon_learn, expr_learn = ExpressionConfigUtils.get_expression_config_for_chat(self.session_id) + self._enable_expression_use = expr_use + self._enable_expression_learning = expr_learn + self._enable_jargon_learning = jargon_learn - # ====== 心流聊天核心逻辑 ====== - async def _hfc_func(self, mentioned_message: Optional["SessionMessage"] = None): - """心流聊天的主循环逻辑""" - if self._consecutive_no_reply_count >= 5: - threshold = 2 - elif self._consecutive_no_reply_count >= 3: - threshold = 2 if random.random() < 0.5 else 1 - else: - threshold = 1 + async def _hfc_func(self): + recent_messages_list = message_api.get_messages_by_time_in_chat( + chat_id=self.session_id, + start_time=self.last_read_time, + end_time=time.time(), + limit=20, + limit_mode="latest", + filter_mai=True, + filter_command=False, + filter_intercept_message_level=1, + ) - if len(self.message_cache) < threshold: + if len(recent_messages_list) < 1: await asyncio.sleep(0.2) return True - talk_value_threshold = ( - random.random() * ChatConfigUtils.get_talk_value(self.session_id) * self._talk_frequency_adjust - ) - if mentioned_message and global_config.chat.mentioned_bot_reply: - await self._judge_and_response(mentioned_message) - elif random.random() < talk_value_threshold: - await self._judge_and_response() + self.last_read_time = time.time() + + mentioned_message: Optional["SessionMessage"] = None + for message in recent_messages_list: + if global_config.chat.inevitable_at_reply and message.is_at: + mentioned_message = message + elif global_config.chat.mentioned_bot_reply and message.is_mentioned: + mentioned_message = message + + talk_value = ChatConfigUtils.get_talk_value(self.session_id) * self._talk_frequency_adjust + if mentioned_message: + await self._judge_and_response(mentioned_message=mentioned_message, recent_messages_list=recent_messages_list) + elif random.random() < talk_value: + await self._judge_and_response(recent_messages_list=recent_messages_list) return True - async def _judge_and_response(self, mentioned_message: Optional["SessionMessage"] = None): - """判定和生成回复""" - asyncio.create_task(self._trigger_expression_learning(self.message_cache)) - # TODO: 完成反思器之后的逻辑 - start_time = time.time() - current_cycle_detail = self._start_cycle() + async def _judge_and_response( + self, + mentioned_message: Optional["SessionMessage"] = None, + recent_messages_list: Optional[List["SessionMessage"]] = None, + ): + recent_messages = list(recent_messages_list or self.message_cache[-20:]) + if recent_messages: + asyncio.create_task(self._trigger_expression_learning(recent_messages)) + + cycle_timers, thinking_id = self._start_cycle() logger.info(f"{self.log_prefix} 开始第{self._cycle_counter}次思考") - # TODO: 动作检查逻辑 - # TODO: Planner逻辑 - # TODO: 动作执行逻辑 + try: + async with global_prompt_manager.async_message_scope(self._get_template_name()): + available_actions: Dict[str, ActionInfo] = {} + try: + await self.action_modifier.modify_actions() + available_actions = self.action_manager.get_using_actions() + except Exception as exc: + logger.error(f"{self.log_prefix} 动作修改失败: {exc}", exc_info=True) - cycle_detail = self._end_cycle(current_cycle_detail) - if wait_time := global_config.chat.planner_smooth - (time.time() - start_time) > 0: - await asyncio.sleep(wait_time) - else: - await asyncio.sleep(0.1) # 最小等待时间,避免过快循环 - return True + is_group_chat, chat_target_info, _ = self.action_planner.get_necessary_info() + message_list_before_now = get_messages_before_time_in_chat( + chat_id=self.session_id, + timestamp=time.time(), + limit=int(global_config.chat.max_context_size * 0.6), + filter_intercept_message_level=1, + ) + chat_content_block, message_id_list = build_readable_messages_with_id( + messages=message_list_before_now, + timestamp_mode="normal_no_YMD", + read_mark=self.action_planner.last_obs_time_mark, + truncate=True, + show_actions=True, + ) + + prompt, filtered_actions = await self._build_planner_prompt_with_event( + available_actions=available_actions, + is_group_chat=is_group_chat, + chat_target_info=chat_target_info, + chat_content_block=chat_content_block, + message_id_list=message_id_list, + ) + if prompt is None: + return False + + with Timer("规划器", cycle_timers): + reasoning, action_to_use_info, llm_raw_output, llm_reasoning, llm_duration_ms = ( + await self.action_planner._execute_main_planner( + prompt=prompt, + message_id_list=message_id_list, + filtered_actions=filtered_actions, + available_actions=available_actions, + loop_start_time=self.last_read_time, + ) + ) + + action_to_use_info = self._ensure_force_reply_action( + actions=action_to_use_info, + force_reply_message=mentioned_message, + available_actions=available_actions, + ) + self.action_planner.add_plan_log(reasoning, action_to_use_info) + self.action_planner.last_obs_time_mark = time.time() + self._log_plan( + prompt=prompt, + reasoning=reasoning, + llm_raw_output=llm_raw_output, + llm_reasoning=llm_reasoning, + llm_duration_ms=llm_duration_ms, + actions=action_to_use_info, + ) + + logger.info( + f"{self.log_prefix} 决定执行{len(action_to_use_info)}个动作: {' '.join([a.action_type for a in action_to_use_info])}" + ) + + action_tasks = [ + asyncio.create_task( + self._execute_action( + action, + action_to_use_info, + thinking_id, + available_actions, + cycle_timers, + ) + ) + for action in action_to_use_info + ] + results = await asyncio.gather(*action_tasks, return_exceptions=True) + + reply_loop_info = None + reply_text_from_reply = "" + action_success = False + action_reply_text = "" + execute_result_str = "" + + for result in results: + if isinstance(result, BaseException): + logger.error(f"{self.log_prefix} 动作执行异常: {result}", exc_info=True) + continue + + execute_result_str += f"{result['action_type']} 执行结果:{result['result']}\n" + if result["action_type"] == "reply": + if result["success"]: + reply_loop_info = result["loop_info"] + reply_text_from_reply = result["result"] + else: + logger.warning(f"{self.log_prefix} reply 动作执行失败") + else: + action_success = result["success"] + action_reply_text = result["result"] + + self.action_planner.add_plan_excute_log(result=execute_result_str) + + if reply_loop_info: + loop_info = reply_loop_info + loop_info["loop_action_info"].update( + { + "action_taken": action_success, + "taken_time": time.time(), + } + ) + else: + loop_info = { + "loop_plan_info": { + "action_result": action_to_use_info, + }, + "loop_action_info": { + "action_taken": action_success, + "reply_text": action_reply_text, + "taken_time": time.time(), + }, + } + reply_text_from_reply = action_reply_text + + current_cycle_detail = self._end_cycle(self._current_cycle_detail, loop_info) + logger.debug(f"{self.log_prefix} 本轮最终输出: {reply_text_from_reply}") + return current_cycle_detail is not None + except Exception as exc: + logger.error(f"{self.log_prefix} 判定与回复流程失败: {exc}", exc_info=True) + if self._current_cycle_detail: + self._end_cycle( + self._current_cycle_detail, + { + "loop_plan_info": {"action_result": []}, + "loop_action_info": { + "action_taken": False, + "reply_text": "", + "taken_time": time.time(), + "error": str(exc), + }, + }, + ) + return False def _handle_loop_completion(self, task: asyncio.Task): - """当 _hfc_func 任务完成时执行的回调。""" try: if exception := task.exception(): - logger.error(f"{self.log_prefix} HeartFChatting: 脱离了聊天(异常): {exception}") - logger.error(traceback.format_exc()) # Log full traceback for exceptions + logger.error(f"{self.log_prefix} HeartFChatting: 主循环异常退出: {exception}") + logger.error(traceback.format_exc()) else: - logger.info(f"{self.log_prefix} HeartFChatting: 脱离了聊天 (外部停止)") + logger.info(f"{self.log_prefix} HeartFChatting: 主循环已退出") except asyncio.CancelledError: - logger.info(f"{self.log_prefix} HeartFChatting: 结束了聊天") + logger.info(f"{self.log_prefix} HeartFChatting: 聊天已结束") - # ====== 学习器触发逻辑 ====== async def _trigger_expression_learning(self, messages: List["SessionMessage"]): + if not messages: + return + self._expression_learner.add_messages(messages) if time.time() - self._last_extraction_time < self._min_extraction_interval: return @@ -233,12 +379,14 @@ class HeartFChatting: return if not self._enable_expression_learning: return + extraction_end_time = time.time() logger.info( f"聊天流 {self.session_name} 提取到 {len(messages)} 条消息," f"时间窗口: {self._last_extraction_time:.2f} - {extraction_end_time:.2f}" ) self._last_extraction_time = extraction_end_time + try: jargon_miner = self._jargon_miner if self._enable_jargon_learning else None learnt_style = await self._expression_learner.learn(jargon_miner) @@ -246,43 +394,398 @@ class HeartFChatting: logger.info(f"{self.log_prefix} 表达学习完成") else: logger.debug(f"{self.log_prefix} 表达学习未获得有效结果") - except Exception as e: - logger.error(f"{self.log_prefix} 表达学习失败: {e}", exc_info=True) + except Exception as exc: + logger.error(f"{self.log_prefix} 表达学习失败: {exc}", exc_info=True) - # ====== 记录循环执行信息相关逻辑 ====== - def _start_cycle(self) -> CycleDetail: + def _start_cycle(self) -> Tuple[Dict[str, float], str]: self._cycle_counter += 1 - current_cycle_detail = CycleDetail(cycle_id=self._cycle_counter) - current_cycle_detail.thinking_id = f"tid{str(round(time.time(), 2))}" - return current_cycle_detail + self._current_cycle_detail = CycleDetail(cycle_id=self._cycle_counter) + self._current_cycle_detail.thinking_id = f"tid{str(round(time.time(), 2))}" + return self._current_cycle_detail.time_records, self._current_cycle_detail.thinking_id - def _end_cycle(self, cycle_detail: CycleDetail, only_long_execution: bool = True): + def _end_cycle(self, cycle_detail: Optional[CycleDetail], loop_info: Optional[Dict[str, Any]] = None): + if cycle_detail is None: + return None + + cycle_detail.loop_plan_info = (loop_info or {}).get("loop_plan_info") + cycle_detail.loop_action_info = (loop_info or {}).get("loop_action_info") cycle_detail.end_time = time.time() - timer_strings: List[str] = [ + self.history_loop.append(cycle_detail) + + timer_strings = [ f"{name}: {duration:.2f}s" for name, duration in cycle_detail.time_records.items() - if not only_long_execution or duration >= 0.1 + if duration >= 0.1 ] logger.info( - f"{self.log_prefix} 第 {cycle_detail.cycle_id} 个心流循环完成" - f"耗时: {cycle_detail.end_time - cycle_detail.start_time:.2f}秒\n" + f"{self.log_prefix} 第{cycle_detail.cycle_id} 个心流循环完成," + f"耗时: {cycle_detail.end_time - cycle_detail.start_time:.2f}s;" f"详细计时: {', '.join(timer_strings) if timer_strings else '无'}" ) - return cycle_detail - # ====== Action相关逻辑 ====== - async def _execute_action(self, *args, **kwargs): - """原ExecuteAction""" - raise NotImplementedError("执行动作的逻辑尚未实现") # TODO: 实现动作执行的逻辑,替换掉*args, **kwargs*占位符 + async def _execute_action( + self, + action_planner_info: ActionPlannerInfo, + chosen_action_plan_infos: List[ActionPlannerInfo], + thinking_id: str, + available_actions: Dict[str, ActionInfo], + cycle_timers: Dict[str, float], + ): + try: + with Timer(f"动作{action_planner_info.action_type}", cycle_timers): + if action_planner_info.action_type == "no_reply": + reason = action_planner_info.reasoning or "选择不回复" + self._consecutive_no_reply_count += 1 + await database_api.store_action_info( + chat_stream=self.chat_stream, + display_prompt=reason, + thinking_id=thinking_id, + action_data={}, + action_name="no_reply", + action_reasoning=reason, + ) + return { + "action_type": "no_reply", + "success": True, + "result": "选择不回复", + "loop_info": None, + } - async def _execute_other_actions(self, *args, **kwargs): - """原HandleAction""" - raise NotImplementedError( - "执行其他动作的逻辑尚未实现" - ) # TODO: 实现其他动作执行的逻辑, 替换掉*args, **kwargs*占位符 + if action_planner_info.action_type == "reply": + self._consecutive_no_reply_count = 0 + reason = action_planner_info.reasoning or "" + think_level = self._get_think_level(action_planner_info) + planner_reasoning = action_planner_info.action_reasoning or reason - # ====== 响应发送相关方法 ====== - async def _send_response(self, *args, **kwargs): - raise NotImplementedError("发送回复的逻辑尚未实现") # TODO: 实现发送回复的逻辑,替换掉*args, **kwargs*占位符 - # 传入的消息至少应该是个MessageSequence实例,最好是SessionMessage实例,随后可直接转化为MessageSending实例 + record_replyer_action_temp( + chat_id=self.session_id, + reason=reason, + think_level=think_level, + ) + await database_api.store_action_info( + chat_stream=self.chat_stream, + display_prompt=reason, + thinking_id=thinking_id, + action_data={}, + action_name="reply", + action_reasoning=reason, + ) + + unknown_words, quote_message = self._extract_reply_metadata(action_planner_info) + success, llm_response = await generator_api.generate_reply( + chat_stream=self.chat_stream, + reply_message=action_planner_info.action_message, + available_actions=available_actions, + chosen_actions=chosen_action_plan_infos, + reply_reason=planner_reasoning, + unknown_words=unknown_words, + enable_tool=global_config.tool.enable_tool, + request_type="replyer", + from_plugin=False, + reply_time_point=action_planner_info.action_data.get("loop_start_time", time.time()) + if action_planner_info.action_data + else time.time(), + think_level=think_level, + ) + if not success or not llm_response or not llm_response.reply_set: + if action_planner_info.action_message: + logger.info( + f"对 {action_planner_info.action_message.processed_plain_text} 的回复生成失败" + ) + else: + logger.info(f"{self.log_prefix} 回复生成失败") + return { + "action_type": "reply", + "success": False, + "result": "回复生成失败", + "loop_info": None, + } + + loop_info, reply_text, _ = await self._send_and_store_reply( + response_set=llm_response.reply_set, + action_message=action_planner_info.action_message, # type: ignore[arg-type] + cycle_timers=cycle_timers, + thinking_id=thinking_id, + actions=chosen_action_plan_infos, + selected_expressions=llm_response.selected_expressions, + quote_message=quote_message, + ) + self.last_active_time = time.time() + return { + "action_type": "reply", + "success": True, + "result": reply_text, + "loop_info": loop_info, + } + + with Timer("动作执行", cycle_timers): + success, result = await self._handle_action( + action=action_planner_info.action_type, + action_reasoning=action_planner_info.action_reasoning or "", + action_data=action_planner_info.action_data or {}, + cycle_timers=cycle_timers, + thinking_id=thinking_id, + action_message=action_planner_info.action_message, + ) + if success: + self.last_active_time = time.time() + return { + "action_type": action_planner_info.action_type, + "success": success, + "result": result, + "loop_info": None, + } + except Exception as exc: + logger.error(f"{self.log_prefix} 执行动作时出错: {exc}", exc_info=True) + return { + "action_type": action_planner_info.action_type, + "success": False, + "result": "", + "loop_info": None, + "error": str(exc), + } + + async def _handle_action( + self, + action: str, + action_reasoning: str, + action_data: dict, + cycle_timers: Dict[str, float], + thinking_id: str, + action_message: Optional["SessionMessage"] = None, + ) -> Tuple[bool, str]: + try: + action_handler = self.action_manager.create_action( + action_name=action, + action_data=action_data, + action_reasoning=action_reasoning, + cycle_timers=cycle_timers, + thinking_id=thinking_id, + chat_stream=self.chat_stream, + log_prefix=self.log_prefix, + action_message=action_message, + ) + if not action_handler: + logger.warning(f"{self.log_prefix} 未能创建动作处理器: {action}") + return False, "" + + success, action_text = await action_handler.execute() + return success, action_text + except Exception as exc: + logger.error(f"{self.log_prefix} 处理动作 {action} 时出错: {exc}", exc_info=True) + return False, "" + + async def _send_and_store_reply( + self, + response_set: MessageSequence, + action_message: "SessionMessage", + cycle_timers: Dict[str, float], + thinking_id: str, + actions: List[ActionPlannerInfo], + selected_expressions: Optional[List[int]] = None, + quote_message: Optional[bool] = None, + ) -> Tuple[Dict[str, Any], str, Dict[str, float]]: + with Timer("回复发送", cycle_timers): + reply_text = await self._send_response( + reply_set=response_set, + message_data=action_message, + selected_expressions=selected_expressions, + quote_message=quote_message, + ) + + platform = action_message.platform or getattr(self.chat_stream, "platform", "unknown") + person = Person(platform=platform, user_id=action_message.message_info.user_info.user_id) + action_prompt_display = f"你对{person.person_name}进行了回复:{reply_text}" + await database_api.store_action_info( + chat_stream=self.chat_stream, + display_prompt=action_prompt_display, + thinking_id=thinking_id, + action_data={"reply_text": reply_text}, + action_name="reply", + ) + + loop_info: Dict[str, Any] = { + "loop_plan_info": { + "action_result": actions, + }, + "loop_action_info": { + "action_taken": True, + "reply_text": reply_text, + "command": "", + "taken_time": time.time(), + }, + } + return loop_info, reply_text, cycle_timers + + async def _send_response( + self, + reply_set: MessageSequence, + message_data: "SessionMessage", + selected_expressions: Optional[List[int]] = None, + quote_message: Optional[bool] = None, + ) -> str: + if global_config.chat.llm_quote: + need_reply = bool(quote_message) + else: + new_message_count = message_api.count_new_messages( + chat_id=self.session_id, + start_time=self.last_read_time, + end_time=time.time(), + ) + need_reply = new_message_count >= random.randint(2, 3) or time.time() - self.last_read_time > 90 + + reply_text = "" + first_replied = False + for component in reply_set.components: + if not isinstance(component, TextComponent): + continue + data = component.text + if not first_replied: + await send_api.text_to_stream( + text=data, + stream_id=self.session_id, + reply_message=message_data, + set_reply=need_reply, + typing=False, + selected_expressions=selected_expressions, + ) + first_replied = True + else: + await send_api.text_to_stream( + text=data, + stream_id=self.session_id, + reply_message=message_data, + set_reply=False, + typing=True, + selected_expressions=selected_expressions, + ) + reply_text += data + return reply_text + + async def _build_planner_prompt_with_event( + self, + available_actions: Dict[str, ActionInfo], + is_group_chat: bool, + chat_target_info: Any, + chat_content_block: str, + message_id_list: List[Tuple[str, "SessionMessage"]], + ) -> Tuple[Optional[str], Dict[str, ActionInfo]]: + filtered_actions = self.action_planner._filter_actions_by_activation_type(available_actions, chat_content_block) + prompt, _ = await self.action_planner.build_planner_prompt( + is_group_chat=is_group_chat, + chat_target_info=chat_target_info, + current_available_actions=filtered_actions, + chat_content_block=chat_content_block, + message_id_list=message_id_list, + ) + event_message = build_event_message(EventType.ON_PLAN, llm_prompt=prompt, stream_id=self.session_id) + continue_flag, modified_message = await event_bus.emit(EventType.ON_PLAN, event_message) + if not continue_flag: + logger.info(f"{self.log_prefix} ON_PLAN 事件中止了本轮 HFC") + return None, filtered_actions + if modified_message and modified_message._modify_flags.modify_llm_prompt and modified_message.llm_prompt: + prompt = modified_message.llm_prompt + return prompt, filtered_actions + + def _ensure_force_reply_action( + self, + actions: List[ActionPlannerInfo], + force_reply_message: Optional["SessionMessage"], + available_actions: Dict[str, ActionInfo], + ) -> List[ActionPlannerInfo]: + if not force_reply_message: + return actions + + has_reply_to_force_message = any( + action.action_type == "reply" + and action.action_message + and action.action_message.message_id == force_reply_message.message_id + for action in actions + ) + if has_reply_to_force_message: + return actions + + actions = [action for action in actions if action.action_type != "no_reply"] + actions.insert( + 0, + ActionPlannerInfo( + action_type="reply", + reasoning="用户提及了我,必须回复该消息", + action_data={"loop_start_time": self.last_read_time}, + action_message=force_reply_message, + available_actions=available_actions, + action_reasoning=None, + ), + ) + logger.info(f"{self.log_prefix} 检测到强制回复消息,已补充 reply 动作") + return actions + + def _log_plan( + self, + prompt: str, + reasoning: str, + llm_raw_output: Optional[str], + llm_reasoning: Optional[str], + llm_duration_ms: Optional[float], + actions: List[ActionPlannerInfo], + ) -> None: + try: + PlanReplyLogger.log_plan( + chat_id=self.session_id, + prompt=prompt, + reasoning=reasoning, + raw_output=llm_raw_output, + raw_reasoning=llm_reasoning, + actions=actions, + timing={ + "llm_duration_ms": round(llm_duration_ms, 2) if llm_duration_ms is not None else None, + "loop_start_time": self.last_read_time, + }, + extra=None, + ) + except Exception: + logger.exception(f"{self.log_prefix} 记录 plan 日志失败") + + def _extract_reply_metadata( + self, + action_planner_info: ActionPlannerInfo, + ) -> Tuple[Optional[List[str]], Optional[bool]]: + unknown_words: Optional[List[str]] = None + quote_message: Optional[bool] = None + action_data = action_planner_info.action_data or {} + + raw_unknown_words = action_data.get("unknown_words") + if isinstance(raw_unknown_words, list): + cleaned_unknown_words = [] + for item in raw_unknown_words: + if isinstance(item, str) and (cleaned_item := item.strip()): + cleaned_unknown_words.append(cleaned_item) + if cleaned_unknown_words: + unknown_words = cleaned_unknown_words + + raw_quote = action_data.get("quote") + if isinstance(raw_quote, bool): + quote_message = raw_quote + elif isinstance(raw_quote, str): + quote_message = raw_quote.lower() in {"true", "1", "yes"} + elif isinstance(raw_quote, (int, float)): + quote_message = bool(raw_quote) + + return unknown_words, quote_message + + def _get_think_level(self, action_planner_info: ActionPlannerInfo) -> int: + think_mode = global_config.chat.think_mode + if think_mode == "default": + return 0 + if think_mode == "deep": + return 1 + if think_mode == "dynamic": + action_data = action_planner_info.action_data or {} + return int(action_data.get("think_level", 1)) + return 0 + + def _get_template_name(self) -> Optional[str]: + if self.chat_stream.context: + return self.chat_stream.context.template_name + return None diff --git a/src/chat/heart_flow/heartflow.py b/src/chat/heart_flow/heartflow.py new file mode 100644 index 00000000..febff2d5 --- /dev/null +++ b/src/chat/heart_flow/heartflow.py @@ -0,0 +1,42 @@ +import traceback +from typing import Any, Optional, Dict + +from src.chat.message_receive.chat_stream import get_chat_manager +from src.common.logger import get_logger +from src.chat.heart_flow.heartFC_chat import HeartFChatting +from src.chat.brain_chat.brain_chat import BrainChatting +from src.chat.message_receive.chat_stream import ChatStream + +logger = get_logger("heartflow") + + +class Heartflow: + """主心流协调器,负责初始化并协调聊天""" + + def __init__(self): + self.heartflow_chat_list: Dict[Any, HeartFChatting | BrainChatting] = {} + + async def get_or_create_heartflow_chat(self, chat_id: Any) -> Optional[HeartFChatting | BrainChatting]: + """获取或创建一个新的HeartFChatting实例""" + try: + if chat_id in self.heartflow_chat_list: + if chat := self.heartflow_chat_list.get(chat_id): + return chat + else: + chat_stream: ChatStream | None = get_chat_manager().get_stream(chat_id) + if not chat_stream: + raise ValueError(f"未找到 chat_id={chat_id} 的聊天流") + if chat_stream.group_info: + new_chat = HeartFChatting(chat_id=chat_id) + else: + new_chat = BrainChatting(chat_id=chat_id) + await new_chat.start() + self.heartflow_chat_list[chat_id] = new_chat + return new_chat + except Exception as e: + logger.error(f"创建心流聊天 {chat_id} 失败: {e}", exc_info=True) + traceback.print_exc() + return None + + +heartflow = Heartflow()