🤖 自动格式化代码 [skip ci]
This commit is contained in:
@@ -16,6 +16,7 @@ pfc_action_log_config = LogConfig(
|
||||
|
||||
logger = get_module_logger("action_planner", config=pfc_action_log_config)
|
||||
|
||||
|
||||
# 注意:这个 ActionPlannerInfo 类似乎没有在 ActionPlanner 中使用,
|
||||
# 如果确实没用,可以考虑移除,但暂时保留以防万一。
|
||||
class ActionPlannerInfo:
|
||||
@@ -25,9 +26,11 @@ class ActionPlannerInfo:
|
||||
self.knowledge_list = []
|
||||
self.memory_list = []
|
||||
|
||||
|
||||
# ActionPlanner 类定义,顶格
|
||||
class ActionPlanner:
|
||||
"""行动规划器"""
|
||||
|
||||
def __init__(self, stream_id: str):
|
||||
self.llm = LLMRequest(
|
||||
model=global_config.llm_PFC_action_planner,
|
||||
@@ -54,18 +57,20 @@ class ActionPlanner:
|
||||
time_since_last_bot_message_info = ""
|
||||
try:
|
||||
bot_id = str(global_config.BOT_QQ)
|
||||
if hasattr(observation_info, 'chat_history') and observation_info.chat_history:
|
||||
if hasattr(observation_info, "chat_history") and observation_info.chat_history:
|
||||
for i in range(len(observation_info.chat_history) - 1, -1, -1):
|
||||
msg = observation_info.chat_history[i]
|
||||
if not isinstance(msg, dict):
|
||||
continue
|
||||
sender_info = msg.get('user_info', {})
|
||||
sender_id = str(sender_info.get('user_id')) if isinstance(sender_info, dict) else None
|
||||
msg_time = msg.get('time')
|
||||
sender_info = msg.get("user_info", {})
|
||||
sender_id = str(sender_info.get("user_id")) if isinstance(sender_info, dict) else None
|
||||
msg_time = msg.get("time")
|
||||
if sender_id == bot_id and msg_time:
|
||||
time_diff = time.time() - msg_time
|
||||
if time_diff < 60.0:
|
||||
time_since_last_bot_message_info = f"提示:你上一条成功发送的消息是在 {time_diff:.1f} 秒前。\n"
|
||||
time_since_last_bot_message_info = (
|
||||
f"提示:你上一条成功发送的消息是在 {time_diff:.1f} 秒前。\n"
|
||||
)
|
||||
break
|
||||
else:
|
||||
logger.debug("Observation info chat history is empty or not available for bot time check.")
|
||||
@@ -76,31 +81,31 @@ class ActionPlanner:
|
||||
# --- 获取 Bot 上次发言时间信息结束 ---
|
||||
|
||||
timeout_context = ""
|
||||
try: # 添加 try-except 以增加健壮性
|
||||
if hasattr(conversation_info, 'goal_list') and conversation_info.goal_list:
|
||||
try: # 添加 try-except 以增加健壮性
|
||||
if hasattr(conversation_info, "goal_list") and conversation_info.goal_list:
|
||||
last_goal_tuple = conversation_info.goal_list[-1]
|
||||
if isinstance(last_goal_tuple, tuple) and len(last_goal_tuple) > 0:
|
||||
last_goal_text = last_goal_tuple[0]
|
||||
if isinstance(last_goal_text, str) and "分钟,思考接下来要做什么" in last_goal_text:
|
||||
try:
|
||||
timeout_minutes_text = last_goal_text.split(',')[0].replace('你等待了','')
|
||||
timeout_minutes_text = last_goal_text.split(",")[0].replace("你等待了", "")
|
||||
timeout_context = f"重要提示:你刚刚因为对方长时间({timeout_minutes_text})没有回复而结束了等待,这可能代表在对方看来本次聊天已结束,请基于此情况规划下一步,不要重复等待前的发言。\n"
|
||||
except Exception:
|
||||
timeout_context = "重要提示:你刚刚因为对方长时间没有回复而结束了等待,这可能代表在对方看来本次聊天已结束,请基于此情况规划下一步,不要重复等待前的发言。\n"
|
||||
else:
|
||||
logger.debug("Conversation info goal_list is empty or not available for timeout check.")
|
||||
except AttributeError:
|
||||
logger.warning("ConversationInfo object might not have goal_list attribute yet for timeout check.")
|
||||
logger.warning("ConversationInfo object might not have goal_list attribute yet for timeout check.")
|
||||
except Exception as e:
|
||||
logger.warning(f"检查超时目标时出错: {e}")
|
||||
logger.warning(f"检查超时目标时出错: {e}")
|
||||
|
||||
# 构建提示词
|
||||
logger.debug(f"开始规划行动:当前目标: {getattr(conversation_info, 'goal_list', '不可用')}") # 使用 getattr
|
||||
logger.debug(f"开始规划行动:当前目标: {getattr(conversation_info, 'goal_list', '不可用')}") # 使用 getattr
|
||||
|
||||
# 构建对话目标 (goals_str)
|
||||
goals_str = ""
|
||||
try: # 添加 try-except
|
||||
if hasattr(conversation_info, 'goal_list') and conversation_info.goal_list:
|
||||
try: # 添加 try-except
|
||||
if hasattr(conversation_info, "goal_list") and conversation_info.goal_list:
|
||||
for goal_reason in conversation_info.goal_list:
|
||||
if isinstance(goal_reason, tuple) and len(goal_reason) > 0:
|
||||
goal = goal_reason[0]
|
||||
@@ -114,36 +119,36 @@ class ActionPlanner:
|
||||
goal = str(goal) if goal is not None else "目标内容缺失"
|
||||
reasoning = str(reasoning) if reasoning is not None else "没有明确原因"
|
||||
goals_str += f"- 目标:{goal}\n 原因:{reasoning}\n"
|
||||
if not goals_str: # 如果循环后 goals_str 仍为空
|
||||
if not goals_str: # 如果循环后 goals_str 仍为空
|
||||
goals_str = "- 目前没有明确对话目标,请考虑设定一个。\n"
|
||||
except AttributeError:
|
||||
logger.warning("ConversationInfo object might not have goal_list attribute yet.")
|
||||
goals_str = "- 获取对话目标时出错。\n"
|
||||
logger.warning("ConversationInfo object might not have goal_list attribute yet.")
|
||||
goals_str = "- 获取对话目标时出错。\n"
|
||||
except Exception as e:
|
||||
logger.error(f"构建对话目标字符串时出错: {e}")
|
||||
goals_str = "- 构建对话目标时出错。\n"
|
||||
logger.error(f"构建对话目标字符串时出错: {e}")
|
||||
goals_str = "- 构建对话目标时出错。\n"
|
||||
|
||||
# 获取聊天历史记录 (chat_history_text)
|
||||
chat_history_text = ""
|
||||
try:
|
||||
if hasattr(observation_info, 'chat_history') and observation_info.chat_history:
|
||||
if hasattr(observation_info, "chat_history") and observation_info.chat_history:
|
||||
chat_history_list = observation_info.chat_history[-20:]
|
||||
for msg in chat_history_list:
|
||||
if isinstance(msg, dict) and 'detailed_plain_text' in msg:
|
||||
if isinstance(msg, dict) and "detailed_plain_text" in msg:
|
||||
chat_history_text += f"{msg.get('detailed_plain_text', '')}\n"
|
||||
elif isinstance(msg, str):
|
||||
chat_history_text += f"{msg}\n"
|
||||
if not chat_history_text: # 如果历史记录是空列表
|
||||
chat_history_text = "还没有聊天记录。\n"
|
||||
if not chat_history_text: # 如果历史记录是空列表
|
||||
chat_history_text = "还没有聊天记录。\n"
|
||||
else:
|
||||
chat_history_text = "还没有聊天记录。\n"
|
||||
|
||||
if hasattr(observation_info, 'new_messages_count') and observation_info.new_messages_count > 0:
|
||||
if hasattr(observation_info, 'unprocessed_messages') and observation_info.unprocessed_messages:
|
||||
if hasattr(observation_info, "new_messages_count") and observation_info.new_messages_count > 0:
|
||||
if hasattr(observation_info, "unprocessed_messages") and observation_info.unprocessed_messages:
|
||||
new_messages_list = observation_info.unprocessed_messages
|
||||
chat_history_text += f"--- 以下是 {observation_info.new_messages_count} 条新消息 ---\n"
|
||||
for msg in new_messages_list:
|
||||
if isinstance(msg, dict) and 'detailed_plain_text' in msg:
|
||||
if isinstance(msg, dict) and "detailed_plain_text" in msg:
|
||||
chat_history_text += f"{msg.get('detailed_plain_text', '')}\n"
|
||||
elif isinstance(msg, str):
|
||||
chat_history_text += f"{msg}\n"
|
||||
@@ -151,7 +156,9 @@ class ActionPlanner:
|
||||
# if hasattr(observation_info, 'clear_unprocessed_messages'):
|
||||
# observation_info.clear_unprocessed_messages()
|
||||
else:
|
||||
logger.warning("ObservationInfo has new_messages_count > 0 but unprocessed_messages is empty or missing.")
|
||||
logger.warning(
|
||||
"ObservationInfo has new_messages_count > 0 but unprocessed_messages is empty or missing."
|
||||
)
|
||||
except AttributeError:
|
||||
logger.warning("ObservationInfo object might be missing expected attributes for chat history.")
|
||||
chat_history_text = "获取聊天记录时出错。\n"
|
||||
@@ -159,7 +166,6 @@ class ActionPlanner:
|
||||
logger.error(f"处理聊天记录时发生未知错误: {e}")
|
||||
chat_history_text = "处理聊天记录时出错。\n"
|
||||
|
||||
|
||||
# 构建 Persona 文本 (persona_text)
|
||||
identity_details_only = self.identity_detail_info
|
||||
identity_addon = ""
|
||||
@@ -168,11 +174,11 @@ class ActionPlanner:
|
||||
# original_details = identity_details_only
|
||||
for p in pronouns:
|
||||
if identity_details_only.startswith(p):
|
||||
identity_details_only = identity_details_only[len(p):]
|
||||
identity_details_only = identity_details_only[len(p) :]
|
||||
break
|
||||
if identity_details_only.endswith("。"):
|
||||
identity_details_only = identity_details_only[:-1]
|
||||
cleaned_details = identity_details_only.strip(',, ')
|
||||
identity_details_only = identity_details_only[:-1]
|
||||
cleaned_details = identity_details_only.strip(",, ")
|
||||
if cleaned_details:
|
||||
identity_addon = f"并且{cleaned_details}"
|
||||
persona_text = f"你的名字是{self.name},{self.personality_info}{identity_addon}。"
|
||||
@@ -182,15 +188,15 @@ class ActionPlanner:
|
||||
last_action_context = "关于你【上一次尝试】的行动:\n"
|
||||
|
||||
action_history_list = []
|
||||
try: # 添加 try-except
|
||||
if hasattr(conversation_info, 'done_action') and conversation_info.done_action:
|
||||
try: # 添加 try-except
|
||||
if hasattr(conversation_info, "done_action") and conversation_info.done_action:
|
||||
action_history_list = conversation_info.done_action[-5:]
|
||||
else:
|
||||
logger.debug("Conversation info done_action is empty or not available.")
|
||||
except AttributeError:
|
||||
logger.warning("ConversationInfo object might not have done_action attribute yet.")
|
||||
logger.warning("ConversationInfo object might not have done_action attribute yet.")
|
||||
except Exception as e:
|
||||
logger.error(f"访问行动历史时出错: {e}")
|
||||
logger.error(f"访问行动历史时出错: {e}")
|
||||
|
||||
if not action_history_list:
|
||||
action_history_summary += "- 还没有执行过行动。\n"
|
||||
@@ -210,13 +216,13 @@ 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:
|
||||
if len(action_data) > 0:
|
||||
action_type = action_data[0]
|
||||
if len(action_data) > 1:
|
||||
if len(action_data) > 1:
|
||||
plan_reason = action_data[1]
|
||||
if len(action_data) > 2:
|
||||
if len(action_data) > 2:
|
||||
status = action_data[2]
|
||||
if status == "recall" and len(action_data) > 3:
|
||||
if status == "recall" and len(action_data) > 3:
|
||||
final_reason = action_data[3]
|
||||
|
||||
reason_text = f", 失败/取消原因: {final_reason}" if final_reason else ""
|
||||
@@ -231,9 +237,9 @@ class ActionPlanner:
|
||||
elif status == "recall":
|
||||
last_action_context += "- 但该行动最终【未能执行/被取消】。\n"
|
||||
if final_reason:
|
||||
last_action_context += f"- 【重要】失败/取消的具体原因是: “{final_reason}”\n"
|
||||
last_action_context += f"- 【重要】失败/取消的具体原因是: “{final_reason}”\n"
|
||||
else:
|
||||
last_action_context += "- 【重要】失败/取消原因未明确记录。\n"
|
||||
last_action_context += "- 【重要】失败/取消原因未明确记录。\n"
|
||||
else:
|
||||
last_action_context += f"- 该行动当前状态: {status}\n"
|
||||
|
||||
@@ -279,14 +285,15 @@ end_conversation: 决定结束对话,对方长时间没回复或者当你觉
|
||||
logger.debug(f"LLM原始返回内容: {content}")
|
||||
|
||||
success, result = get_items_from_json(
|
||||
content, "action", "reason",
|
||||
default_values={"action": "wait", "reason": "LLM返回格式错误或未提供原因,默认等待"}
|
||||
content,
|
||||
"action",
|
||||
"reason",
|
||||
default_values={"action": "wait", "reason": "LLM返回格式错误或未提供原因,默认等待"},
|
||||
)
|
||||
|
||||
action = result.get("action", "wait")
|
||||
reason = result.get("reason", "LLM未提供原因,默认等待")
|
||||
|
||||
|
||||
# 验证action类型
|
||||
valid_actions = ["direct_reply", "fetch_knowledge", "wait", "listening", "rethink_goal", "end_conversation"]
|
||||
if action not in valid_actions:
|
||||
@@ -300,4 +307,4 @@ end_conversation: 决定结束对话,对方长时间没回复或者当你觉
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"规划行动时调用 LLM 或处理结果出错: {str(e)}")
|
||||
return "wait", f"行动规划处理中发生错误,暂时等待: {str(e)}"
|
||||
return "wait", f"行动规划处理中发生错误,暂时等待: {str(e)}"
|
||||
|
||||
Reference in New Issue
Block a user