Merge pull request #1 from Dax233/PFC-fix

先规范个空格(
This commit is contained in:
SmartMita
2025-04-27 21:01:03 +09:00
committed by GitHub
10 changed files with 105 additions and 109 deletions

View File

@@ -311,10 +311,10 @@ class ActionPlanner:
# --- 选择 Prompt --- # --- 选择 Prompt ---
if last_successful_reply_action in ['direct_reply', 'send_new_message']: if last_successful_reply_action in ['direct_reply', 'send_new_message']:
prompt_template = PROMPT_FOLLOW_UP prompt_template = PROMPT_FOLLOW_UP
logger.info("使用 PROMPT_FOLLOW_UP (追问决策)") logger.debug(f"使用 PROMPT_FOLLOW_UP (追问决策)")
else: else:
prompt_template = PROMPT_INITIAL_REPLY prompt_template = PROMPT_INITIAL_REPLY
logger.info("使用 PROMPT_INITIAL_REPLY (首次/非连续回复决策)") logger.debug("使用 PROMPT_INITIAL_REPLY (首次/非连续回复决策)")
# --- 格式化最终的 Prompt --- # --- 格式化最终的 Prompt ---
prompt = prompt_template.format( prompt = prompt_template.format(

View File

@@ -94,11 +94,9 @@ class ChatObserver:
""" """
try: try:
# 发送新消息通知 # 发送新消息通知
# logger.info(f"发送新ccchandleer消息通知: {message}")
notification = create_new_message_notification( notification = create_new_message_notification(
sender="chat_observer", target="observation_info", message=message sender="chat_observer", target="observation_info", message=message
) )
# logger.info(f"发送新消ddddd息通知: {notification}")
# print(self.notification_manager) # print(self.notification_manager)
await self.notification_manager.send_notification(notification) await self.notification_manager.send_notification(notification)
except Exception as e: except Exception as e:
@@ -289,7 +287,7 @@ class ChatObserver:
self._running = True self._running = True
self._task = asyncio.create_task(self._update_loop()) 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): def stop(self):
"""停止观察器""" """停止观察器"""
@@ -298,7 +296,7 @@ class ChatObserver:
self._update_complete.set() # 设置完成事件以解除等待 self._update_complete.set() # 设置完成事件以解除等待
if self._task: if self._task:
self._task.cancel() 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): async def process_chat_history(self, messages: list):
"""处理聊天历史 """处理聊天历史

View File

@@ -98,15 +98,11 @@ class NotificationManager:
notification_type: 要处理的通知类型 notification_type: 要处理的通知类型
handler: 处理器实例 handler: 处理器实例
""" """
# print(1145145511114445551111444)
if target not in self._handlers: if target not in self._handlers:
# print("没11有target")
self._handlers[target] = {} self._handlers[target] = {}
if notification_type not in self._handlers[target]: if notification_type not in self._handlers[target]:
# print("没11有notification_type")
self._handlers[target][notification_type] = [] self._handlers[target][notification_type] = []
# print(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) self._handlers[target][notification_type].append(handler)
# print(self._handlers[target][notification_type]) # print(self._handlers[target][notification_type])
@@ -132,7 +128,6 @@ class NotificationManager:
async def send_notification(self, notification: Notification): async def send_notification(self, notification: Notification):
"""发送通知""" """发送通知"""
self._notification_history.append(notification) self._notification_history.append(notification)
# print("kaishichul-----------------------------------i")
# 如果是状态通知,更新活跃状态 # 如果是状态通知,更新活跃状态
if isinstance(notification, StateNotification): if isinstance(notification, StateNotification):
@@ -145,7 +140,6 @@ class NotificationManager:
target = notification.target target = notification.target
if target in self._handlers: if target in self._handlers:
handlers = self._handlers[target].get(notification.type, []) handlers = self._handlers[target].get(notification.type, [])
# print(1111111)
# print(handlers) # print(handlers)
for handler in handlers: for handler in handlers:
# print(f"调用处理器: {handler}") # print(f"调用处理器: {handler}")

View File

@@ -1,8 +1,10 @@
import time import time
import asyncio import asyncio
import datetime import datetime
# from .message_storage import MongoDBMessageStorage # from .message_storage import MongoDBMessageStorage
from src.plugins.utils.chat_message_builder import build_readable_messages, get_raw_msg_before_timestamp_with_chat 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 ...config.config import global_config
from typing import Dict, Any, Optional from typing import Dict, Any, Optional
from ..chat.message import Message from ..chat.message import Message
@@ -144,7 +146,7 @@ class Conversation:
# --- 在规划前记录当前新消息数量 --- # --- 在规划前记录当前新消息数量 ---
initial_new_message_count = 0 initial_new_message_count = 0
if hasattr(self.observation_info, "new_messages_count"): 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: else:
logger.warning("ObservationInfo missing 'new_messages_count' before planning.") logger.warning("ObservationInfo missing 'new_messages_count' before planning.")
@@ -265,7 +267,7 @@ class Conversation:
): ):
"""处理规划的行动""" """处理规划的行动"""
logger.info(f"执行行动: {action}, 原因: {reason}") logger.debug(f"执行行动: {action}, 原因: {reason}")
# 记录action历史 (逻辑不变) # 记录action历史 (逻辑不变)
current_action_record = { current_action_record = {
@@ -306,7 +308,7 @@ class Conversation:
# 2. 检查回复 (逻辑不变) # 2. 检查回复 (逻辑不变)
self.state = ConversationState.CHECKING self.state = ConversationState.CHECKING
try: 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( is_suitable, check_reason, need_replan = await self.reply_generator.check_reply(
reply=self.generated_reply, reply=self.generated_reply,
goal=current_goal_str, goal=current_goal_str,
@@ -390,7 +392,7 @@ class Conversation:
# 2. 检查回复 # 2. 检查回复
self.state = ConversationState.CHECKING self.state = ConversationState.CHECKING
try: 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( is_suitable, check_reason, need_replan = await self.reply_generator.check_reply(
reply=self.generated_reply, reply=self.generated_reply,
goal=current_goal_str, goal=current_goal_str,

View File

@@ -140,7 +140,6 @@ class ObservationInfo:
self.chat_observer.notification_manager.register_handler( self.chat_observer.notification_manager.register_handler(
target="observation_info", notification_type=NotificationType.COLD_CHAT, handler=self.handler target="observation_info", notification_type=NotificationType.COLD_CHAT, handler=self.handler
) )
print("1919810------------------------绑定-----------------------------")
def unbind_from_chat_observer(self): def unbind_from_chat_observer(self):
"""解除与chat_observer的绑定""" """解除与chat_observer的绑定"""
@@ -159,7 +158,6 @@ class ObservationInfo:
Args: Args:
message: 消息数据 message: 消息数据
""" """
# print("1919810-----------------------------------------------------")
# logger.debug(f"更新信息from_message: {message}") # logger.debug(f"更新信息from_message: {message}")
self.last_message_time = message["time"] self.last_message_time = message["time"]
self.last_message_id = message["message_id"] self.last_message_id = message["message_id"]

View File

@@ -250,15 +250,13 @@ class GoalAnalyzer:
async def analyze_conversation(self, goal, reasoning): async def analyze_conversation(self, goal, reasoning):
messages = self.chat_observer.get_cached_messages() messages = self.chat_observer.get_cached_messages()
chat_history_text = "" chat_history_text = await build_readable_messages(
for msg in messages: messages,
time_str = datetime.datetime.fromtimestamp(msg["time"]).strftime("%H:%M:%S") replace_bot_name=True,
user_info = UserInfo.from_dict(msg.get("user_info", {})) merge_messages=False,
sender = user_info.user_nickname or f"用户{user_info.user_id}" timestamp_mode="relative",
if sender == self.name: read_mark=0.0,
sender = "你说" )
chat_history_text += f"{time_str},{sender}:{msg.get('processed_plain_text', '')}\n"
identity_details_only = self.identity_detail_info identity_details_only = self.identity_detail_info
identity_addon = "" identity_addon = ""
if isinstance(identity_details_only, str): if isinstance(identity_details_only, str):

View File

@@ -5,6 +5,7 @@ from ..models.utils_model import LLMRequest
from ...config.config import global_config from ...config.config import global_config
from ..chat.message import Message from ..chat.message import Message
from ..knowledge.knowledge_lib import qa_manager from ..knowledge.knowledge_lib import qa_manager
from ..utils.chat_message_builder import build_readable_messages
logger = get_module_logger("knowledge_fetcher") logger = get_module_logger("knowledge_fetcher")
@@ -50,10 +51,13 @@ class KnowledgeFetcher:
Tuple[str, str]: (获取的知识, 知识来源) Tuple[str, str]: (获取的知识, 知识来源)
""" """
# 构建查询上下文 # 构建查询上下文
chat_history_text = "" chat_history_text = await build_readable_messages(
for msg in chat_history: chat_history,
# sender = msg.message_info.user_info.user_nickname or f"用户{msg.message_info.user_info.user_id}" replace_bot_name=True,
chat_history_text += f"{msg.detailed_plain_text}\n" merge_messages=False,
timestamp_mode="relative",
read_mark=0.0,
)
# 从记忆中获取相关知识 # 从记忆中获取相关知识
related_memory = await HippocampusManager.get_instance().get_memory_from_text( related_memory = await HippocampusManager.get_instance().get_memory_from_text(

View File

@@ -47,9 +47,11 @@ class PFCManager:
return self._instances[stream_id] return self._instances[stream_id]
if stream_id in self._instances: if stream_id in self._instances:
instance = self._instances[stream_id] instance = self._instances[stream_id]
if hasattr(instance, 'ignore_until_timestamp') and \ if (
instance.ignore_until_timestamp and \ hasattr(instance, "ignore_until_timestamp")
time.time() < instance.ignore_until_timestamp: and instance.ignore_until_timestamp
and time.time() < instance.ignore_until_timestamp
):
logger.debug(f"会话实例当前处于忽略状态: {stream_id}") logger.debug(f"会话实例当前处于忽略状态: {stream_id}")
# 返回 None 阻止交互。或者可以返回实例但标记它被忽略了喵? # 返回 None 阻止交互。或者可以返回实例但标记它被忽略了喵?
# 还是返回 None 吧喵。 # 还是返回 None 吧喵。

View File

@@ -162,7 +162,7 @@ class ReplyGenerator:
logger.debug(f"发送到LLM的生成提示词:\n------\n{prompt}\n------") logger.debug(f"发送到LLM的生成提示词:\n------\n{prompt}\n------")
try: try:
content, _ = await self.llm.generate_response_async(prompt) content, _ = await self.llm.generate_response_async(prompt)
logger.info(f"生成的回复: {content}") logger.debug(f"生成的回复: {content}")
# 移除旧的检查新消息逻辑,这应该由 conversation 控制流处理 # 移除旧的检查新消息逻辑,这应该由 conversation 控制流处理
return content return content

View File

@@ -46,7 +46,7 @@ class Waiter:
return True # 返回 True 表示超时 return True # 返回 True 表示超时
await asyncio.sleep(5) # 每 5 秒检查一次 await asyncio.sleep(5) # 每 5 秒检查一次
logger.info("等待中...") # 可以考虑把这个频繁日志注释掉,只在超时或收到消息时输出 logger.debug("等待中...") # 可以考虑把这个频繁日志注释掉,只在超时或收到消息时输出
async def wait_listening(self, conversation_info: ConversationInfo) -> bool: async def wait_listening(self, conversation_info: ConversationInfo) -> bool:
"""倾听用户发言或超时""" """倾听用户发言或超时"""
@@ -73,4 +73,4 @@ class Waiter:
return True # 返回 True 表示超时 return True # 返回 True 表示超时
await asyncio.sleep(5) # 每 5 秒检查一次 await asyncio.sleep(5) # 每 5 秒检查一次
logger.info("倾听等待中...") # 同上,可以考虑注释掉 logger.debug("倾听等待中...") # 同上,可以考虑注释掉