解决UnboundLocalError

pull/1224/head
UnCLAS-Prommer 2025-08-31 12:30:11 +08:00
parent 4bee6002ff
commit aa1155cc5b
No known key found for this signature in database
9 changed files with 65 additions and 67 deletions

View File

@ -1117,6 +1117,7 @@ class ParahippocampalGyrus:
# 4. 创建所有话题的摘要生成任务
tasks: List[Tuple[str, Coroutine[Any, Any, Tuple[str, Tuple[str, str, List | None]]]]] = []
topic_what_prompt: str = ""
for topic in filtered_topics:
# 调用修改后的 topic_what不再需要 time_info
topic_what_prompt = self.hippocampus.topic_what(input_text, topic)

View File

@ -84,7 +84,7 @@ class Message(MessageBase):
return await self._process_single_segment(segment) # type: ignore
@abstractmethod
async def _process_single_segment(self, segment):
async def _process_single_segment(self, segment) -> str:
pass
@ -353,44 +353,44 @@ class MessageProcessBase(Message):
self.thinking_time = round(time.time() - self.thinking_start_time, 2)
return self.thinking_time
async def _process_single_segment(self, seg: Seg) -> str | None:
async def _process_single_segment(self, segment: Seg) -> str:
"""处理单个消息段
Args:
seg: 要处理的消息段
segment: 要处理的消息段
Returns:
str: 处理后的文本
"""
try:
if seg.type == "text":
return seg.data # type: ignore
elif seg.type == "image":
if segment.type == "text":
return segment.data # type: ignore
elif segment.type == "image":
# 如果是base64图片数据
if isinstance(seg.data, str):
return await get_image_manager().get_image_description(seg.data)
if isinstance(segment.data, str):
return await get_image_manager().get_image_description(segment.data)
return "[图片,网卡了加载不出来]"
elif seg.type == "emoji":
if isinstance(seg.data, str):
return await get_image_manager().get_emoji_tag(seg.data)
elif segment.type == "emoji":
if isinstance(segment.data, str):
return await get_image_manager().get_emoji_tag(segment.data)
return "[表情,网卡了加载不出来]"
elif seg.type == "voice":
if isinstance(seg.data, str):
return await get_voice_text(seg.data)
elif segment.type == "voice":
if isinstance(segment.data, str):
return await get_voice_text(segment.data)
return "[发了一段语音,网卡了加载不出来]"
elif seg.type == "at":
return f"[@{seg.data}]"
elif seg.type == "reply":
elif segment.type == "at":
return f"[@{segment.data}]"
elif segment.type == "reply":
if self.reply and hasattr(self.reply, "processed_plain_text"):
# print(f"self.reply.processed_plain_text: {self.reply.processed_plain_text}")
# print(f"reply: {self.reply}")
return f"[回复<{self.reply.message_info.user_info.user_nickname}:{self.reply.message_info.user_info.user_id}> 的消息:{self.reply.processed_plain_text}]" # type: ignore
return None
return ""
else:
return f"[{seg.type}:{str(seg.data)}]"
return f"[{segment.type}:{str(segment.data)}]"
except Exception as e:
logger.error(f"处理消息段失败: {str(e)}, 类型: {seg.type}, 数据: {seg.data}")
return f"[处理失败的{seg.type}消息]"
logger.error(f"处理消息段失败: {str(e)}, 类型: {segment.type}, 数据: {segment.data}")
return f"[处理失败的{segment.type}消息]"
def _generate_detailed_text(self) -> str:
"""生成详细文本,包含时间和用户信息"""

View File

@ -510,7 +510,7 @@ class ActionPlanner:
)
self.last_obs_time_mark = time.time()
all_sub_planner_results: List[ActionPlannerInfo] = [] # 防止Unbound
try:
sub_planner_actions: Dict[str, ActionInfo] = {}
@ -581,7 +581,6 @@ class ActionPlanner:
sub_plan_results = await asyncio.gather(*sub_plan_tasks)
# 收集所有结果
all_sub_planner_results: List[ActionPlannerInfo] = []
for sub_result in sub_plan_results:
all_sub_planner_results.extend(sub_result)
@ -726,9 +725,7 @@ class ActionPlanner:
action_str = ""
for action_planner_info in actions:
action_str += f"{action_planner_info.action_type} "
logger.info(
f"{self.log_prefix}大脑小脑决定执行{len(actions)}个动作: {action_str}"
)
logger.info(f"{self.log_prefix}大脑小脑决定执行{len(actions)}个动作: {action_str}")
else:
# 如果为假,只返回副规划器的结果
actions = self._filter_no_actions(all_sub_planner_results)

View File

@ -651,9 +651,11 @@ class DefaultReplyer:
action_name = action_plan_info.action_type
if action_name == "reply":
continue
action_description: str = "无描述"
reasoning: str = "无原因"
if action := available_actions.get(action_name):
action_description = action.description or "无描述"
reasoning = action_plan_info.reasoning or "无原因"
action_description = action.description or action_description
reasoning = action_plan_info.reasoning or reasoning
chosen_action_descriptions += f"- {action_name}: {action_description},原因:{reasoning}\n"
@ -705,22 +707,22 @@ class DefaultReplyer:
is_group_chat = bool(chat_stream.group_info)
platform = chat_stream.platform
user_id = "用户ID"
person_name = "用户"
sender = "用户"
target = "消息"
if reply_message:
user_id = reply_message.user_info.user_id
person = Person(platform=platform, user_id=user_id)
person_name = person.person_name or user_id
sender = person_name
target = reply_message.processed_plain_text
else:
person_name = "用户"
sender = "用户"
target = "消息"
mood_prompt: str = ""
if global_config.mood.enable_mood:
chat_mood = mood_manager.get_mood_by_chat_id(chat_id)
mood_prompt = chat_mood.mood_state
else:
mood_prompt = ""
target = replace_user_references(target, chat_stream.platform, replace_bot_name=True)
@ -939,9 +941,7 @@ class DefaultReplyer:
else:
chat_target_name = "对方"
if self.chat_target_info:
chat_target_name = (
self.chat_target_info.person_name or self.chat_target_info.user_nickname or "对方"
)
chat_target_name = self.chat_target_info.person_name or self.chat_target_info.user_nickname or "对方"
chat_target_1 = await global_prompt_manager.format_prompt(
"chat_target_private1", sender_name=chat_target_name
)

View File

@ -203,7 +203,8 @@ def get_actions_by_timestamp_with_chat(
query = query.order_by(ActionRecords.time.asc())
actions = list(query)
return [DatabaseActionRecords(
return [
DatabaseActionRecords(
action_id=action.action_id,
time=action.time,
action_name=action.action_name,
@ -214,7 +215,9 @@ def get_actions_by_timestamp_with_chat(
chat_id=action.chat_id,
chat_info_stream_id=action.chat_info_stream_id,
chat_info_platform=action.chat_info_platform,
) for action in actions]
)
for action in actions
]
def get_actions_by_timestamp_with_chat_inclusive(
@ -474,7 +477,7 @@ def _build_readable_messages_internal(
truncated_content = content
if 0 < limit < original_len:
truncated_content = f"{content[:limit]}{replace_content}"
truncated_content = f"{content[:limit]}{replace_content}" # pyright: ignore[reportPossiblyUnboundVariable]
detailed_message.append((timestamp, name, truncated_content, is_action))
else:
@ -544,7 +547,7 @@ def build_pic_mapping_info(pic_id_mapping: Dict[str, str]) -> str:
return "\n".join(mapping_lines)
def build_readable_actions(actions: List[DatabaseActionRecords],mode:str="relative") -> str:
def build_readable_actions(actions: List[DatabaseActionRecords], mode: str = "relative") -> str:
"""
将动作列表转换为可读的文本格式
格式: 分钟前你使用了(action_name)具体内容是action_prompt_display
@ -585,6 +588,8 @@ def build_readable_actions(actions: List[DatabaseActionRecords],mode:str="relati
action_time_struct = time.localtime(action_time)
time_str = time.strftime("%H:%M:%S", action_time_struct)
time_ago_str = f"{time_str}"
else:
raise ValueError(f"Unsupported mode: {mode}")
line = f"{time_ago_str},你使用了“{action_name}”,具体内容是:“{action_prompt_display}"
output_lines.append(line)

View File

@ -86,6 +86,8 @@ def _convert_messages(
role = "model"
elif message.role == RoleType.User:
role = "user"
else:
raise ValueError(f"Unsupported role: {message.role}")
# 添加Content
if isinstance(message.content, str):

View File

@ -37,10 +37,9 @@ logger = get_logger("main")
class MainSystem:
def __init__(self):
# 根据配置条件性地初始化记忆系统
self.hippocampus_manager = None
if global_config.memory.enable_memory:
self.hippocampus_manager = hippocampus_manager
else:
self.hippocampus_manager = None
# 使用消息API替代直接的FastAPI实例
self.app: MessageServer = get_global_api()
@ -117,13 +116,11 @@ class MainSystem:
await check_and_run_migrations()
# 触发 ON_START 事件
from src.plugin_system.core.events_manager import events_manager
from src.plugin_system.base.component_types import EventType
await events_manager.handle_mai_events(
event_type=EventType.ON_START
)
await events_manager.handle_mai_events(event_type=EventType.ON_START)
# logger.info("已触发 ON_START 事件")
try:
init_time = int(1000 * (time.time() - init_start_time))
@ -162,8 +159,6 @@ class MainSystem:
logger.info("[记忆遗忘] 记忆遗忘完成")
async def main():
"""主函数"""
system = MainSystem()
@ -175,5 +170,3 @@ async def main():
if __name__ == "__main__":
asyncio.run(main())

View File

@ -99,6 +99,8 @@ async def _send_to_target(
# 创建消息段
message_segment = Seg(type=message_type, data=content) # type: ignore
reply_to_platform_id = ""
anchor_message: Union["MessageRecv", None] = None
if reply_message:
anchor_message = message_dict_to_message_recv(reply_message.flatten())
if anchor_message:
@ -107,9 +109,6 @@ async def _send_to_target(
reply_to_platform_id = (
f"{anchor_message.message_info.platform}:{anchor_message.message_info.user_info.user_id}"
)
else:
reply_to_platform_id = ""
anchor_message = None
# 构建发送消息对象
bot_message = MessageSending(

View File

@ -124,6 +124,7 @@ class ComponentRegistry:
self._components_classes[namespaced_name] = component_class
# 根据组件类型进行特定注册(使用原始名称)
ret = False
match component_type:
case ComponentType.ACTION:
assert isinstance(component_info, ActionInfo)