🤖 自动格式化代码 [skip ci]

This commit is contained in:
github-actions[bot]
2025-04-27 14:45:21 +00:00
parent d0cdaac7d0
commit 80fdefeeea
4 changed files with 78 additions and 70 deletions

View File

@@ -104,7 +104,12 @@ class ActionPlanner:
# self.action_planner_info = ActionPlannerInfo() # 移除未使用的变量 # self.action_planner_info = ActionPlannerInfo() # 移除未使用的变量
# 修改 plan 方法签名,增加 last_successful_reply_action 参数 # 修改 plan 方法签名,增加 last_successful_reply_action 参数
async def plan(self, observation_info: ObservationInfo, conversation_info: ConversationInfo, last_successful_reply_action: Optional[str]) -> Tuple[str, str]: async def plan(
self,
observation_info: ObservationInfo,
conversation_info: ConversationInfo,
last_successful_reply_action: Optional[str],
) -> Tuple[str, str]:
"""规划下一步行动 """规划下一步行动
Args: Args:
@@ -142,7 +147,6 @@ class ActionPlanner:
except Exception as e: except Exception as e:
logger.warning(f"获取 Bot 上次发言时间时出错: {e}") logger.warning(f"获取 Bot 上次发言时间时出错: {e}")
# --- 获取超时提示信息 --- # --- 获取超时提示信息 ---
# (这部分逻辑不变) # (这部分逻辑不变)
timeout_context = "" timeout_context = ""
@@ -244,7 +248,6 @@ class ActionPlanner:
identity_addon = f"并且{cleaned_details}" identity_addon = f"并且{cleaned_details}"
persona_text = f"你的名字是{self.name}{self.personality_info}{identity_addon}" persona_text = f"你的名字是{self.name}{self.personality_info}{identity_addon}"
# 构建行动历史和上一次行动结果 (action_history_summary, last_action_context) # 构建行动历史和上一次行动结果 (action_history_summary, last_action_context)
# (这部分逻辑不变) # (这部分逻辑不变)
action_history_summary = "你最近执行的行动历史:\n" action_history_summary = "你最近执行的行动历史:\n"
@@ -313,7 +316,7 @@ class ActionPlanner:
# self.last_successful_action_type = None # 非完成状态,清除记录 # self.last_successful_action_type = None # 非完成状态,清除记录
# --- 选择 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.debug("使用 PROMPT_FOLLOW_UP (追问决策)") logger.debug("使用 PROMPT_FOLLOW_UP (追问决策)")
else: else:
@@ -328,7 +331,7 @@ class ActionPlanner:
last_action_context=last_action_context, last_action_context=last_action_context,
time_since_last_bot_message_info=time_since_last_bot_message_info, time_since_last_bot_message_info=time_since_last_bot_message_info,
timeout_context=timeout_context, timeout_context=timeout_context,
chat_history_text=chat_history_text if chat_history_text.strip() else "还没有聊天记录。" chat_history_text=chat_history_text if chat_history_text.strip() else "还没有聊天记录。",
) )
logger.debug(f"发送到LLM的最终提示词:\n------\n{prompt}\n------") logger.debug(f"发送到LLM的最终提示词:\n------\n{prompt}\n------")
@@ -356,7 +359,7 @@ class ActionPlanner:
"listening", "listening",
"rethink_goal", "rethink_goal",
"end_conversation", "end_conversation",
"block_and_ignore" "block_and_ignore",
] ]
if action not in valid_actions: if action not in valid_actions:
logger.warning(f"LLM返回了未知的行动类型: '{action}',强制改为 wait") logger.warning(f"LLM返回了未知的行动类型: '{action}',强制改为 wait")

View File

@@ -153,9 +153,7 @@ class Conversation:
# --- 调用 Action Planner --- # --- 调用 Action Planner ---
# 传递 self.conversation_info.last_successful_reply_action # 传递 self.conversation_info.last_successful_reply_action
action, reason = await self.action_planner.plan( action, reason = await self.action_planner.plan(
self.observation_info, self.observation_info, self.conversation_info, self.conversation_info.last_successful_reply_action
self.conversation_info,
self.conversation_info.last_successful_reply_action
) )
# --- 规划后检查是否有 *更多* 新消息到达 --- # --- 规划后检查是否有 *更多* 新消息到达 ---
@@ -184,7 +182,6 @@ class Conversation:
else: else:
logger.error("无法清理未处理消息: ObservationInfo 缺少 clear_unprocessed_messages 方法!") logger.error("无法清理未处理消息: ObservationInfo 缺少 clear_unprocessed_messages 方法!")
await self._handle_action(action, reason, self.observation_info, self.conversation_info) await self._handle_action(action, reason, self.observation_info, self.conversation_info)
# 检查是否需要结束对话 (逻辑不变) # 检查是否需要结束对话 (逻辑不变)
@@ -205,7 +202,6 @@ class Conversation:
self.should_continue = False self.should_continue = False
logger.info("检测到'结束对话'目标,停止循环。") logger.info("检测到'结束对话'目标,停止循环。")
except Exception as loop_err: except Exception as loop_err:
logger.error(f"PFC主循环出错: {loop_err}") logger.error(f"PFC主循环出错: {loop_err}")
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
@@ -219,14 +215,16 @@ class Conversation:
def _check_new_messages_after_planning(self): def _check_new_messages_after_planning(self):
"""检查在规划后是否有新消息""" """检查在规划后是否有新消息"""
# 检查 ObservationInfo 是否已初始化并且有 new_messages_count 属性 # 检查 ObservationInfo 是否已初始化并且有 new_messages_count 属性
if not hasattr(self, 'observation_info') or not hasattr(self.observation_info, 'new_messages_count'): if not hasattr(self, "observation_info") or not hasattr(self.observation_info, "new_messages_count"):
logger.warning("ObservationInfo 未初始化或缺少 'new_messages_count' 属性,无法检查新消息。") logger.warning("ObservationInfo 未初始化或缺少 'new_messages_count' 属性,无法检查新消息。")
return False # 或者根据需要抛出错误 return False # 或者根据需要抛出错误
if self.observation_info.new_messages_count > 2: if self.observation_info.new_messages_count > 2:
logger.info(f"生成/执行动作期间收到 {self.observation_info.new_messages_count} 条新消息,取消当前动作并重新规划") logger.info(
f"生成/执行动作期间收到 {self.observation_info.new_messages_count} 条新消息,取消当前动作并重新规划"
)
# 如果有新消息,也应该重置上次回复状态 # 如果有新消息,也应该重置上次回复状态
if hasattr(self, 'conversation_info'): # 确保 conversation_info 已初始化 if hasattr(self, "conversation_info"): # 确保 conversation_info 已初始化
self.conversation_info.last_successful_reply_action = None self.conversation_info.last_successful_reply_action = None
else: else:
logger.warning("ConversationInfo 未初始化,无法重置 last_successful_reply_action。") logger.warning("ConversationInfo 未初始化,无法重置 last_successful_reply_action。")
@@ -278,7 +276,7 @@ class Conversation:
"final_reason": None, "final_reason": None,
} }
# 确保 done_action 列表存在 # 确保 done_action 列表存在
if not hasattr(conversation_info, 'done_action'): if not hasattr(conversation_info, "done_action"):
conversation_info.done_action = [] conversation_info.done_action = []
conversation_info.done_action.append(current_action_record) conversation_info.done_action.append(current_action_record)
action_index = len(conversation_info.done_action) - 1 action_index = len(conversation_info.done_action) - 1
@@ -302,7 +300,9 @@ class Conversation:
self.state = ConversationState.GENERATING self.state = ConversationState.GENERATING
# 1. 生成回复 (调用 generate 时传入 action_type) # 1. 生成回复 (调用 generate 时传入 action_type)
self.generated_reply = await self.reply_generator.generate(observation_info, conversation_info, action_type='send_new_message') self.generated_reply = await self.reply_generator.generate(
observation_info, conversation_info, action_type="send_new_message"
)
logger.info(f"{reply_attempt_count} 次生成的追问回复: {self.generated_reply}") logger.info(f"{reply_attempt_count} 次生成的追问回复: {self.generated_reply}")
# 2. 检查回复 (逻辑不变) # 2. 检查回复 (逻辑不变)
@@ -323,7 +323,9 @@ class Conversation:
final_reply_to_send = self.generated_reply final_reply_to_send = self.generated_reply
break break
elif need_replan: elif need_replan:
logger.warning(f"{reply_attempt_count} 次追问检查建议重新规划,停止尝试。原因: {check_reason}") logger.warning(
f"{reply_attempt_count} 次追问检查建议重新规划,停止尝试。原因: {check_reason}"
)
break break
except Exception as check_err: except Exception as check_err:
logger.error(f"{reply_attempt_count} 次调用 ReplyChecker (追问) 时出错: {check_err}") logger.error(f"{reply_attempt_count} 次调用 ReplyChecker (追问) 时出错: {check_err}")
@@ -346,7 +348,7 @@ class Conversation:
await self._send_reply() # <--- 调用恢复后的函数 await self._send_reply() # <--- 调用恢复后的函数
# 更新状态: 标记上次成功是 send_new_message # 更新状态: 标记上次成功是 send_new_message
self.conversation_info.last_successful_reply_action = 'send_new_message' self.conversation_info.last_successful_reply_action = "send_new_message"
action_successful = True # 标记动作成功 action_successful = True # 标记动作成功
else: else:
@@ -371,7 +373,6 @@ class Conversation:
} }
conversation_info.done_action.append(wait_action_record) conversation_info.done_action.append(wait_action_record)
elif action == "direct_reply": elif action == "direct_reply":
max_reply_attempts = 3 max_reply_attempts = 3
reply_attempt_count = 0 reply_attempt_count = 0
@@ -386,7 +387,9 @@ class Conversation:
self.state = ConversationState.GENERATING self.state = ConversationState.GENERATING
# 1. 生成回复 # 1. 生成回复
self.generated_reply = await self.reply_generator.generate(observation_info, conversation_info, action_type='direct_reply') self.generated_reply = await self.reply_generator.generate(
observation_info, conversation_info, action_type="direct_reply"
)
logger.info(f"{reply_attempt_count} 次生成的首次回复: {self.generated_reply}") logger.info(f"{reply_attempt_count} 次生成的首次回复: {self.generated_reply}")
# 2. 检查回复 # 2. 检查回复
@@ -407,7 +410,9 @@ class Conversation:
final_reply_to_send = self.generated_reply final_reply_to_send = self.generated_reply
break break
elif need_replan: elif need_replan:
logger.warning(f"{reply_attempt_count} 次首次回复检查建议重新规划,停止尝试。原因: {check_reason}") logger.warning(
f"{reply_attempt_count} 次首次回复检查建议重新规划,停止尝试。原因: {check_reason}"
)
break break
except Exception as check_err: except Exception as check_err:
logger.error(f"{reply_attempt_count} 次调用 ReplyChecker (首次回复) 时出错: {check_err}") logger.error(f"{reply_attempt_count} 次调用 ReplyChecker (首次回复) 时出错: {check_err}")
@@ -430,7 +435,7 @@ class Conversation:
await self._send_reply() # <--- 调用恢复后的函数 await self._send_reply() # <--- 调用恢复后的函数
# 更新状态: 标记上次成功是 direct_reply # 更新状态: 标记上次成功是 direct_reply
self.conversation_info.last_successful_reply_action = 'direct_reply' self.conversation_info.last_successful_reply_action = "direct_reply"
action_successful = True # 标记动作成功 action_successful = True # 标记动作成功
else: else:
@@ -460,7 +465,7 @@ class Conversation:
knowledge_query = reason knowledge_query = reason
try: try:
# 检查 knowledge_fetcher 是否存在 # 检查 knowledge_fetcher 是否存在
if not hasattr(self, 'knowledge_fetcher'): if not hasattr(self, "knowledge_fetcher"):
logger.error("KnowledgeFetcher 未初始化,无法获取知识。") logger.error("KnowledgeFetcher 未初始化,无法获取知识。")
raise AttributeError("KnowledgeFetcher not initialized") raise AttributeError("KnowledgeFetcher not initialized")
@@ -468,9 +473,11 @@ class Conversation:
logger.info(f"获取到知识: {knowledge[:100]}..., 来源: {source}") logger.info(f"获取到知识: {knowledge[:100]}..., 来源: {source}")
if knowledge: if knowledge:
# 确保 knowledge_list 存在 # 确保 knowledge_list 存在
if not hasattr(conversation_info, 'knowledge_list'): if not hasattr(conversation_info, "knowledge_list"):
conversation_info.knowledge_list = [] conversation_info.knowledge_list = []
conversation_info.knowledge_list.append({"query": knowledge_query, "knowledge": knowledge, "source": source}) conversation_info.knowledge_list.append(
{"query": knowledge_query, "knowledge": knowledge, "source": source}
)
action_successful = True action_successful = True
except Exception as fetch_err: except Exception as fetch_err:
logger.error(f"获取知识时出错: {fetch_err}") logger.error(f"获取知识时出错: {fetch_err}")
@@ -479,12 +486,11 @@ class Conversation:
) )
self.conversation_info.last_successful_reply_action = None # 重置状态 self.conversation_info.last_successful_reply_action = None # 重置状态
elif action == "rethink_goal": elif action == "rethink_goal":
self.state = ConversationState.RETHINKING self.state = ConversationState.RETHINKING
try: try:
# 检查 goal_analyzer 是否存在 # 检查 goal_analyzer 是否存在
if not hasattr(self, 'goal_analyzer'): if not hasattr(self, "goal_analyzer"):
logger.error("GoalAnalyzer 未初始化,无法重新思考目标。") logger.error("GoalAnalyzer 未初始化,无法重新思考目标。")
raise AttributeError("GoalAnalyzer not initialized") raise AttributeError("GoalAnalyzer not initialized")
await self.goal_analyzer.analyze_goal(conversation_info, observation_info) await self.goal_analyzer.analyze_goal(conversation_info, observation_info)
@@ -496,13 +502,12 @@ class Conversation:
) )
self.conversation_info.last_successful_reply_action = None # 重置状态 self.conversation_info.last_successful_reply_action = None # 重置状态
elif action == "listening": elif action == "listening":
self.state = ConversationState.LISTENING self.state = ConversationState.LISTENING
logger.info("倾听对方发言...") logger.info("倾听对方发言...")
try: try:
# 检查 waiter 是否存在 # 检查 waiter 是否存在
if not hasattr(self, 'waiter'): if not hasattr(self, "waiter"):
logger.error("Waiter 未初始化,无法倾听。") logger.error("Waiter 未初始化,无法倾听。")
raise AttributeError("Waiter not initialized") raise AttributeError("Waiter not initialized")
await self.waiter.wait_listening(conversation_info) await self.waiter.wait_listening(conversation_info)
@@ -514,7 +519,6 @@ class Conversation:
) )
self.conversation_info.last_successful_reply_action = None # 重置状态 self.conversation_info.last_successful_reply_action = None # 重置状态
elif action == "end_conversation": elif action == "end_conversation":
self.should_continue = False self.should_continue = False
logger.info("决定结束对话...") logger.info("决定结束对话...")
@@ -533,7 +537,7 @@ class Conversation:
logger.info("等待更多信息...") logger.info("等待更多信息...")
try: try:
# 检查 waiter 是否存在 # 检查 waiter 是否存在
if not hasattr(self, 'waiter'): if not hasattr(self, "waiter"):
logger.error("Waiter 未初始化,无法等待。") logger.error("Waiter 未初始化,无法等待。")
raise AttributeError("Waiter not initialized") raise AttributeError("Waiter not initialized")
_timeout_occurred = await self.waiter.wait(self.conversation_info) _timeout_occurred = await self.waiter.wait(self.conversation_info)
@@ -555,7 +559,7 @@ class Conversation:
} }
) )
# 重置状态: 对于非回复类动作的成功,清除上次回复状态 # 重置状态: 对于非回复类动作的成功,清除上次回复状态
if action not in ['direct_reply', 'send_new_message']: if action not in ["direct_reply", "send_new_message"]:
self.conversation_info.last_successful_reply_action = None self.conversation_info.last_successful_reply_action = None
logger.debug(f"动作 {action} 成功完成,重置 last_successful_reply_action") logger.debug(f"动作 {action} 成功完成,重置 last_successful_reply_action")
# 如果动作是 recall 状态,在各自的处理逻辑中已经更新了 done_action # 如果动作是 recall 状态,在各自的处理逻辑中已经更新了 done_action
@@ -571,7 +575,7 @@ class Conversation:
reply_content = self.generated_reply reply_content = self.generated_reply
# 发送消息 (确保 direct_sender 和 chat_stream 有效) # 发送消息 (确保 direct_sender 和 chat_stream 有效)
if not hasattr(self, 'direct_sender') or not self.direct_sender: if not hasattr(self, "direct_sender") or not self.direct_sender:
logger.error("DirectMessageSender 未初始化,无法发送回复。") logger.error("DirectMessageSender 未初始化,无法发送回复。")
return return
if not self.chat_stream: if not self.chat_stream:

View File

@@ -1,4 +1,6 @@
from typing import Optional from typing import Optional
class ConversationInfo: class ConversationInfo:
def __init__(self): def __init__(self):
self.done_action = [] self.done_action = []

View File

@@ -75,7 +75,9 @@ class ReplyGenerator:
self.reply_checker = ReplyChecker(stream_id) self.reply_checker = ReplyChecker(stream_id)
# 修改 generate 方法签名,增加 action_type 参数 # 修改 generate 方法签名,增加 action_type 参数
async def generate(self, observation_info: ObservationInfo, conversation_info: ConversationInfo, action_type: str) -> str: async def generate(
self, observation_info: ObservationInfo, conversation_info: ConversationInfo, action_type: str
) -> str:
"""生成回复 """生成回复
Args: Args:
@@ -126,7 +128,6 @@ class ReplyGenerator:
elif not chat_history_text: elif not chat_history_text:
chat_history_text = "还没有聊天记录。" chat_history_text = "还没有聊天记录。"
# 构建 Persona 文本 (persona_text) # 构建 Persona 文本 (persona_text)
identity_details_only = self.identity_detail_info identity_details_only = self.identity_detail_info
identity_addon = "" identity_addon = ""
@@ -144,7 +145,7 @@ class ReplyGenerator:
persona_text = f"你的名字是{self.name}{self.personality_info}{identity_addon}" persona_text = f"你的名字是{self.name}{self.personality_info}{identity_addon}"
# --- 选择 Prompt --- # --- 选择 Prompt ---
if action_type == 'send_new_message': if action_type == "send_new_message":
prompt_template = PROMPT_SEND_NEW_MESSAGE prompt_template = PROMPT_SEND_NEW_MESSAGE
logger.info("使用 PROMPT_SEND_NEW_MESSAGE (追问生成)") logger.info("使用 PROMPT_SEND_NEW_MESSAGE (追问生成)")
else: # 默认使用 direct_reply 的 prompt else: # 默认使用 direct_reply 的 prompt
@@ -153,9 +154,7 @@ class ReplyGenerator:
# --- 格式化最终的 Prompt --- # --- 格式化最终的 Prompt ---
prompt = prompt_template.format( prompt = prompt_template.format(
persona_text=persona_text, persona_text=persona_text, goals_str=goals_str, chat_history_text=chat_history_text
goals_str=goals_str,
chat_history_text=chat_history_text
) )
# --- 调用 LLM 生成 --- # --- 调用 LLM 生成 ---