diff --git a/src/plugins/PFC/action_planner.py b/src/plugins/PFC/action_planner.py index 701770181..7cdb48e9c 100644 --- a/src/plugins/PFC/action_planner.py +++ b/src/plugins/PFC/action_planner.py @@ -279,7 +279,7 @@ class ActionPlanner: final_reason = action_data.get("final_reason", "") action_time = action_data.get("time", "") elif isinstance(action_data, tuple): - # 假设旧格式兼容 + # 假设旧格式兼容 if len(action_data) > 0: action_type = action_data[0] if len(action_data) > 1: plan_reason = action_data[1] # 可能是规划原因或最终原因 if len(action_data) > 2: status = action_data[2] @@ -311,10 +311,10 @@ class ActionPlanner: # --- 选择 Prompt --- if last_successful_reply_action in ['direct_reply', 'send_new_message']: prompt_template = PROMPT_FOLLOW_UP - logger.info("使用 PROMPT_FOLLOW_UP (追问决策)") + logger.debug(f"使用 PROMPT_FOLLOW_UP (追问决策)") else: prompt_template = PROMPT_INITIAL_REPLY - logger.info("使用 PROMPT_INITIAL_REPLY (首次/非连续回复决策)") + logger.debug("使用 PROMPT_INITIAL_REPLY (首次/非连续回复决策)") # --- 格式化最终的 Prompt --- prompt = prompt_template.format( diff --git a/src/plugins/PFC/chat_observer.py b/src/plugins/PFC/chat_observer.py index 697833c84..915618474 100644 --- a/src/plugins/PFC/chat_observer.py +++ b/src/plugins/PFC/chat_observer.py @@ -94,11 +94,9 @@ class ChatObserver: """ try: # 发送新消息通知 - # logger.info(f"发送新ccchandleer消息通知: {message}") notification = create_new_message_notification( sender="chat_observer", target="observation_info", message=message ) - # logger.info(f"发送新消ddddd息通知: {notification}") # print(self.notification_manager) await self.notification_manager.send_notification(notification) except Exception as e: @@ -289,7 +287,7 @@ class ChatObserver: self._running = True self._task = asyncio.create_task(self._update_loop()) - logger.info(f"ChatObserver for {self.stream_id} started") + logger.debug(f"ChatObserver for {self.stream_id} started") def stop(self): """停止观察器""" @@ -298,7 +296,7 @@ class ChatObserver: self._update_complete.set() # 设置完成事件以解除等待 if self._task: self._task.cancel() - logger.info(f"ChatObserver for {self.stream_id} stopped") + logger.debug(f"ChatObserver for {self.stream_id} stopped") async def process_chat_history(self, messages: list): """处理聊天历史 diff --git a/src/plugins/PFC/chat_states.py b/src/plugins/PFC/chat_states.py index 1f8ee15fb..4b839b7bd 100644 --- a/src/plugins/PFC/chat_states.py +++ b/src/plugins/PFC/chat_states.py @@ -98,15 +98,11 @@ class NotificationManager: notification_type: 要处理的通知类型 handler: 处理器实例 """ - # print(1145145511114445551111444) if target not in self._handlers: - # print("没11有target") self._handlers[target] = {} if notification_type not in self._handlers[target]: - # print("没11有notification_type") self._handlers[target][notification_type] = [] # print(self._handlers[target][notification_type]) - # print(f"注册1111111111111111111111处理器: {target} {notification_type} {handler}") self._handlers[target][notification_type].append(handler) # print(self._handlers[target][notification_type]) @@ -132,7 +128,6 @@ class NotificationManager: async def send_notification(self, notification: Notification): """发送通知""" self._notification_history.append(notification) - # print("kaishichul-----------------------------------i") # 如果是状态通知,更新活跃状态 if isinstance(notification, StateNotification): @@ -145,7 +140,6 @@ class NotificationManager: target = notification.target if target in self._handlers: handlers = self._handlers[target].get(notification.type, []) - # print(1111111) # print(handlers) for handler in handlers: # print(f"调用处理器: {handler}") diff --git a/src/plugins/PFC/conversation.py b/src/plugins/PFC/conversation.py index 500990805..394fc1d74 100644 --- a/src/plugins/PFC/conversation.py +++ b/src/plugins/PFC/conversation.py @@ -1,8 +1,10 @@ import time import asyncio import datetime + # from .message_storage import MongoDBMessageStorage from src.plugins.utils.chat_message_builder import build_readable_messages, get_raw_msg_before_timestamp_with_chat + # from ...config.config import global_config from typing import Dict, Any, Optional from ..chat.message import Message @@ -133,18 +135,18 @@ class Conversation: while self.should_continue: # 忽略逻辑 if self.ignore_until_timestamp and time.time() < self.ignore_until_timestamp: - await asyncio.sleep(30) - continue + await asyncio.sleep(30) + continue elif self.ignore_until_timestamp and time.time() >= self.ignore_until_timestamp: - logger.info(f"忽略时间已到 {self.stream_id},准备结束对话。") - self.ignore_until_timestamp = None - self.should_continue = False - continue + logger.info(f"忽略时间已到 {self.stream_id},准备结束对话。") + self.ignore_until_timestamp = None + self.should_continue = False + continue try: # --- 在规划前记录当前新消息数量 --- initial_new_message_count = 0 if hasattr(self.observation_info, "new_messages_count"): - initial_new_message_count = self.observation_info.new_messages_count + initial_new_message_count = self.observation_info.new_messages_count + 1 # 算上麦麦自己发的那一条 else: logger.warning("ObservationInfo missing 'new_messages_count' before planning.") @@ -237,13 +239,13 @@ class Conversation: # 尝试从 msg_dict 直接获取 chat_stream,如果失败则从全局 chat_manager 获取 chat_info = msg_dict.get("chat_info") if chat_info and isinstance(chat_info, dict): - chat_stream = ChatStream.from_dict(chat_info) + chat_stream = ChatStream.from_dict(chat_info) elif self.chat_stream: # 使用实例变量中的 chat_stream - chat_stream = self.chat_stream + chat_stream = self.chat_stream else: # Fallback: 尝试从 manager 获取 (可能需要 stream_id) - chat_stream = chat_manager.get_stream(self.stream_id) - if not chat_stream: - raise ValueError(f"无法确定 ChatStream for stream_id {self.stream_id}") + chat_stream = chat_manager.get_stream(self.stream_id) + if not chat_stream: + raise ValueError(f"无法确定 ChatStream for stream_id {self.stream_id}") user_info = UserInfo.from_dict(msg_dict.get("user_info", {})) @@ -265,7 +267,7 @@ class Conversation: ): """处理规划的行动""" - logger.info(f"执行行动: {action}, 原因: {reason}") + logger.debug(f"执行行动: {action}, 原因: {reason}") # 记录action历史 (逻辑不变) current_action_record = { @@ -306,7 +308,7 @@ class Conversation: # 2. 检查回复 (逻辑不变) self.state = ConversationState.CHECKING try: - current_goal_str = conversation_info.goal_list[0][0] if conversation_info.goal_list else "" + current_goal_str = conversation_info.goal_list[0]["goal"] if conversation_info.goal_list else "" is_suitable, check_reason, need_replan = await self.reply_generator.check_reply( reply=self.generated_reply, goal=current_goal_str, @@ -390,7 +392,7 @@ class Conversation: # 2. 检查回复 self.state = ConversationState.CHECKING try: - current_goal_str = conversation_info.goal_list[0][0] if conversation_info.goal_list else "" + current_goal_str = conversation_info.goal_list[0]["goal"] if conversation_info.goal_list else "" is_suitable, check_reason, need_replan = await self.reply_generator.check_reply( reply=self.generated_reply, goal=current_goal_str, @@ -414,7 +416,7 @@ class Conversation: # 循环结束,处理最终结果 if is_suitable: - # 检查是否有新消息 + # 检查是否有新消息 if self._check_new_messages_after_planning(): logger.info("生成首次回复期间收到新消息,取消发送,重新规划行动") conversation_info.done_action[action_index].update( @@ -459,58 +461,58 @@ class Conversation: try: # 检查 knowledge_fetcher 是否存在 if not hasattr(self, 'knowledge_fetcher'): - logger.error("KnowledgeFetcher 未初始化,无法获取知识。") - raise AttributeError("KnowledgeFetcher not initialized") + logger.error("KnowledgeFetcher 未初始化,无法获取知识。") + raise AttributeError("KnowledgeFetcher not initialized") knowledge, source = await self.knowledge_fetcher.fetch(knowledge_query, observation_info.chat_history) logger.info(f"获取到知识: {knowledge[:100]}..., 来源: {source}") if knowledge: - # 确保 knowledge_list 存在 - if not hasattr(conversation_info, 'knowledge_list'): - conversation_info.knowledge_list = [] - conversation_info.knowledge_list.append({"query": knowledge_query, "knowledge": knowledge, "source": source}) + # 确保 knowledge_list 存在 + if not hasattr(conversation_info, 'knowledge_list'): + conversation_info.knowledge_list = [] + conversation_info.knowledge_list.append({"query": knowledge_query, "knowledge": knowledge, "source": source}) action_successful = True except Exception as fetch_err: - logger.error(f"获取知识时出错: {fetch_err}") - conversation_info.done_action[action_index].update( - {"status": "recall", "final_reason": f"获取知识失败: {fetch_err}"} - ) - self.conversation_info.last_successful_reply_action = None # 重置状态 + logger.error(f"获取知识时出错: {fetch_err}") + conversation_info.done_action[action_index].update( + {"status": "recall", "final_reason": f"获取知识失败: {fetch_err}"} + ) + self.conversation_info.last_successful_reply_action = None # 重置状态 elif action == "rethink_goal": self.state = ConversationState.RETHINKING try: - # 检查 goal_analyzer 是否存在 + # 检查 goal_analyzer 是否存在 if not hasattr(self, 'goal_analyzer'): - logger.error("GoalAnalyzer 未初始化,无法重新思考目标。") - raise AttributeError("GoalAnalyzer not initialized") + logger.error("GoalAnalyzer 未初始化,无法重新思考目标。") + raise AttributeError("GoalAnalyzer not initialized") await self.goal_analyzer.analyze_goal(conversation_info, observation_info) action_successful = True except Exception as rethink_err: - logger.error(f"重新思考目标时出错: {rethink_err}") - conversation_info.done_action[action_index].update( - {"status": "recall", "final_reason": f"重新思考目标失败: {rethink_err}"} - ) - self.conversation_info.last_successful_reply_action = None # 重置状态 + logger.error(f"重新思考目标时出错: {rethink_err}") + conversation_info.done_action[action_index].update( + {"status": "recall", "final_reason": f"重新思考目标失败: {rethink_err}"} + ) + self.conversation_info.last_successful_reply_action = None # 重置状态 elif action == "listening": self.state = ConversationState.LISTENING logger.info("倾听对方发言...") try: - # 检查 waiter 是否存在 + # 检查 waiter 是否存在 if not hasattr(self, 'waiter'): - logger.error("Waiter 未初始化,无法倾听。") - raise AttributeError("Waiter not initialized") + logger.error("Waiter 未初始化,无法倾听。") + raise AttributeError("Waiter not initialized") timeout_occurred = await self.waiter.wait_listening(conversation_info) action_successful = True # Listening 完成就算成功 except Exception as listen_err: - logger.error(f"倾听时出错: {listen_err}") - conversation_info.done_action[action_index].update( - {"status": "recall", "final_reason": f"倾听失败: {listen_err}"} - ) - self.conversation_info.last_successful_reply_action = None # 重置状态 + logger.error(f"倾听时出错: {listen_err}") + conversation_info.done_action[action_index].update( + {"status": "recall", "final_reason": f"倾听失败: {listen_err}"} + ) + self.conversation_info.last_successful_reply_action = None # 重置状态 elif action == "end_conversation": @@ -519,29 +521,29 @@ class Conversation: action_successful = True # 标记动作成功 elif action == "block_and_ignore": - logger.info("不想再理你了...") - ignore_duration_seconds = 10 * 60 - self.ignore_until_timestamp = time.time() + ignore_duration_seconds - logger.info(f"将忽略此对话直到: {datetime.datetime.fromtimestamp(self.ignore_until_timestamp)}") - self.state = ConversationState.IGNORED - action_successful = True # 标记动作成功 + logger.info("不想再理你了...") + ignore_duration_seconds = 10 * 60 + self.ignore_until_timestamp = time.time() + ignore_duration_seconds + logger.info(f"将忽略此对话直到: {datetime.datetime.fromtimestamp(self.ignore_until_timestamp)}") + self.state = ConversationState.IGNORED + action_successful = True # 标记动作成功 else: # 对应 'wait' 动作 self.state = ConversationState.WAITING logger.info("等待更多信息...") try: - # 检查 waiter 是否存在 + # 检查 waiter 是否存在 if not hasattr(self, 'waiter'): - logger.error("Waiter 未初始化,无法等待。") - raise AttributeError("Waiter not initialized") + logger.error("Waiter 未初始化,无法等待。") + raise AttributeError("Waiter not initialized") timeout_occurred = await self.waiter.wait(self.conversation_info) action_successful = True # Wait 完成就算成功 except Exception as wait_err: - logger.error(f"等待时出错: {wait_err}") - conversation_info.done_action[action_index].update( - {"status": "recall", "final_reason": f"等待失败: {wait_err}"} - ) - self.conversation_info.last_successful_reply_action = None # 重置状态 + logger.error(f"等待时出错: {wait_err}") + conversation_info.done_action[action_index].update( + {"status": "recall", "final_reason": f"等待失败: {wait_err}"} + ) + self.conversation_info.last_successful_reply_action = None # 重置状态 # --- 更新 Action History 状态 --- # 只有当动作本身成功时,才更新状态为 done @@ -570,11 +572,11 @@ class Conversation: # 发送消息 (确保 direct_sender 和 chat_stream 有效) if not hasattr(self, 'direct_sender') or not self.direct_sender: - logger.error("DirectMessageSender 未初始化,无法发送回复。") - return + logger.error("DirectMessageSender 未初始化,无法发送回复。") + return if not self.chat_stream: - logger.error("ChatStream 未初始化,无法发送回复。") - return + logger.error("ChatStream 未初始化,无法发送回复。") + return await self.direct_sender.send_message(chat_stream=self.chat_stream, content=reply_content) diff --git a/src/plugins/PFC/observation_info.py b/src/plugins/PFC/observation_info.py index 072b1fb6f..050d839fb 100644 --- a/src/plugins/PFC/observation_info.py +++ b/src/plugins/PFC/observation_info.py @@ -140,7 +140,6 @@ class ObservationInfo: self.chat_observer.notification_manager.register_handler( target="observation_info", notification_type=NotificationType.COLD_CHAT, handler=self.handler ) - print("1919810------------------------绑定-----------------------------") def unbind_from_chat_observer(self): """解除与chat_observer的绑定""" @@ -159,7 +158,6 @@ class ObservationInfo: Args: message: 消息数据 """ - # print("1919810-----------------------------------------------------") # logger.debug(f"更新信息from_message: {message}") self.last_message_time = message["time"] self.last_message_id = message["message_id"] diff --git a/src/plugins/PFC/pfc.py b/src/plugins/PFC/pfc.py index 5a70d02f3..a3acee47b 100644 --- a/src/plugins/PFC/pfc.py +++ b/src/plugins/PFC/pfc.py @@ -250,15 +250,13 @@ class GoalAnalyzer: async def analyze_conversation(self, goal, reasoning): messages = self.chat_observer.get_cached_messages() - chat_history_text = "" - for msg in messages: - time_str = datetime.datetime.fromtimestamp(msg["time"]).strftime("%H:%M:%S") - user_info = UserInfo.from_dict(msg.get("user_info", {})) - sender = user_info.user_nickname or f"用户{user_info.user_id}" - if sender == self.name: - sender = "你说" - chat_history_text += f"{time_str},{sender}:{msg.get('processed_plain_text', '')}\n" - + chat_history_text = await build_readable_messages( + messages, + replace_bot_name=True, + merge_messages=False, + timestamp_mode="relative", + read_mark=0.0, + ) identity_details_only = self.identity_detail_info identity_addon = "" if isinstance(identity_details_only, str): diff --git a/src/plugins/PFC/pfc_KnowledgeFetcher.py b/src/plugins/PFC/pfc_KnowledgeFetcher.py index 95e66c8cd..958b05bf8 100644 --- a/src/plugins/PFC/pfc_KnowledgeFetcher.py +++ b/src/plugins/PFC/pfc_KnowledgeFetcher.py @@ -5,6 +5,7 @@ from ..models.utils_model import LLMRequest from ...config.config import global_config from ..chat.message import Message from ..knowledge.knowledge_lib import qa_manager +from ..utils.chat_message_builder import build_readable_messages logger = get_module_logger("knowledge_fetcher") @@ -50,10 +51,13 @@ class KnowledgeFetcher: Tuple[str, str]: (获取的知识, 知识来源) """ # 构建查询上下文 - chat_history_text = "" - for msg in chat_history: - # sender = msg.message_info.user_info.user_nickname or f"用户{msg.message_info.user_info.user_id}" - chat_history_text += f"{msg.detailed_plain_text}\n" + chat_history_text = await build_readable_messages( + chat_history, + replace_bot_name=True, + merge_messages=False, + timestamp_mode="relative", + read_mark=0.0, + ) # 从记忆中获取相关知识 related_memory = await HippocampusManager.get_instance().get_memory_from_text( diff --git a/src/plugins/PFC/pfc_manager.py b/src/plugins/PFC/pfc_manager.py index 2b91c0a9c..9aae33f24 100644 --- a/src/plugins/PFC/pfc_manager.py +++ b/src/plugins/PFC/pfc_manager.py @@ -47,18 +47,20 @@ class PFCManager: return self._instances[stream_id] if stream_id in self._instances: instance = self._instances[stream_id] - if hasattr(instance, 'ignore_until_timestamp') and \ - instance.ignore_until_timestamp and \ - time.time() < instance.ignore_until_timestamp: + if ( + hasattr(instance, "ignore_until_timestamp") + and instance.ignore_until_timestamp + and time.time() < instance.ignore_until_timestamp + ): logger.debug(f"会话实例当前处于忽略状态: {stream_id}") - # 返回 None 阻止交互。或者可以返回实例但标记它被忽略了喵? - # 还是返回 None 吧喵。 + # 返回 None 阻止交互。或者可以返回实例但标记它被忽略了喵? + # 还是返回 None 吧喵。 return None - # 检查 should_continue 状态 + # 检查 should_continue 状态 if instance.should_continue: - logger.debug(f"使用现有会话实例: {stream_id}") - return instance + logger.debug(f"使用现有会话实例: {stream_id}") + return instance # else: 实例存在但不应继续 try: # 创建新实例 diff --git a/src/plugins/PFC/reply_generator.py b/src/plugins/PFC/reply_generator.py index ebde0a67a..59e261ac5 100644 --- a/src/plugins/PFC/reply_generator.py +++ b/src/plugins/PFC/reply_generator.py @@ -114,15 +114,15 @@ class ReplyGenerator: # 获取聊天历史记录 (chat_history_text) chat_history_text = observation_info.chat_history_str if observation_info.new_messages_count > 0 and observation_info.unprocessed_messages: - new_messages_list = observation_info.unprocessed_messages - new_messages_str = await build_readable_messages( - new_messages_list, - replace_bot_name=True, - merge_messages=False, - timestamp_mode="relative", - read_mark=0.0, - ) - chat_history_text += f"\n--- 以下是 {observation_info.new_messages_count} 条新消息 ---\n{new_messages_str}" + new_messages_list = observation_info.unprocessed_messages + new_messages_str = await build_readable_messages( + new_messages_list, + replace_bot_name=True, + merge_messages=False, + timestamp_mode="relative", + read_mark=0.0, + ) + chat_history_text += f"\n--- 以下是 {observation_info.new_messages_count} 条新消息 ---\n{new_messages_str}" elif not chat_history_text: chat_history_text = "还没有聊天记录。" @@ -162,7 +162,7 @@ class ReplyGenerator: logger.debug(f"发送到LLM的生成提示词:\n------\n{prompt}\n------") try: content, _ = await self.llm.generate_response_async(prompt) - logger.info(f"生成的回复: {content}") + logger.debug(f"生成的回复: {content}") # 移除旧的检查新消息逻辑,这应该由 conversation 控制流处理 return content diff --git a/src/plugins/PFC/waiter.py b/src/plugins/PFC/waiter.py index eaf8a768a..2362e74ed 100644 --- a/src/plugins/PFC/waiter.py +++ b/src/plugins/PFC/waiter.py @@ -46,7 +46,7 @@ class Waiter: return True # 返回 True 表示超时 await asyncio.sleep(5) # 每 5 秒检查一次 - logger.info("等待中...") # 可以考虑把这个频繁日志注释掉,只在超时或收到消息时输出 + logger.debug("等待中...") # 可以考虑把这个频繁日志注释掉,只在超时或收到消息时输出 async def wait_listening(self, conversation_info: ConversationInfo) -> bool: """倾听用户发言或超时""" @@ -73,4 +73,4 @@ class Waiter: return True # 返回 True 表示超时 await asyncio.sleep(5) # 每 5 秒检查一次 - logger.info("倾听等待中...") # 同上,可以考虑注释掉 + logger.debug("倾听等待中...") # 同上,可以考虑注释掉