mirror of https://github.com/Mai-with-u/MaiBot.git
解决UnboundLocalError
parent
4bee6002ff
commit
aa1155cc5b
|
|
@ -1117,6 +1117,7 @@ class ParahippocampalGyrus:
|
||||||
|
|
||||||
# 4. 创建所有话题的摘要生成任务
|
# 4. 创建所有话题的摘要生成任务
|
||||||
tasks: List[Tuple[str, Coroutine[Any, Any, Tuple[str, Tuple[str, str, List | None]]]]] = []
|
tasks: List[Tuple[str, Coroutine[Any, Any, Tuple[str, Tuple[str, str, List | None]]]]] = []
|
||||||
|
topic_what_prompt: str = ""
|
||||||
for topic in filtered_topics:
|
for topic in filtered_topics:
|
||||||
# 调用修改后的 topic_what,不再需要 time_info
|
# 调用修改后的 topic_what,不再需要 time_info
|
||||||
topic_what_prompt = self.hippocampus.topic_what(input_text, topic)
|
topic_what_prompt = self.hippocampus.topic_what(input_text, topic)
|
||||||
|
|
|
||||||
|
|
@ -84,7 +84,7 @@ class Message(MessageBase):
|
||||||
return await self._process_single_segment(segment) # type: ignore
|
return await self._process_single_segment(segment) # type: ignore
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def _process_single_segment(self, segment):
|
async def _process_single_segment(self, segment) -> str:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -353,44 +353,44 @@ class MessageProcessBase(Message):
|
||||||
self.thinking_time = round(time.time() - self.thinking_start_time, 2)
|
self.thinking_time = round(time.time() - self.thinking_start_time, 2)
|
||||||
return self.thinking_time
|
return self.thinking_time
|
||||||
|
|
||||||
async def _process_single_segment(self, seg: Seg) -> str | None:
|
async def _process_single_segment(self, segment: Seg) -> str:
|
||||||
"""处理单个消息段
|
"""处理单个消息段
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
seg: 要处理的消息段
|
segment: 要处理的消息段
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str: 处理后的文本
|
str: 处理后的文本
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if seg.type == "text":
|
if segment.type == "text":
|
||||||
return seg.data # type: ignore
|
return segment.data # type: ignore
|
||||||
elif seg.type == "image":
|
elif segment.type == "image":
|
||||||
# 如果是base64图片数据
|
# 如果是base64图片数据
|
||||||
if isinstance(seg.data, str):
|
if isinstance(segment.data, str):
|
||||||
return await get_image_manager().get_image_description(seg.data)
|
return await get_image_manager().get_image_description(segment.data)
|
||||||
return "[图片,网卡了加载不出来]"
|
return "[图片,网卡了加载不出来]"
|
||||||
elif seg.type == "emoji":
|
elif segment.type == "emoji":
|
||||||
if isinstance(seg.data, str):
|
if isinstance(segment.data, str):
|
||||||
return await get_image_manager().get_emoji_tag(seg.data)
|
return await get_image_manager().get_emoji_tag(segment.data)
|
||||||
return "[表情,网卡了加载不出来]"
|
return "[表情,网卡了加载不出来]"
|
||||||
elif seg.type == "voice":
|
elif segment.type == "voice":
|
||||||
if isinstance(seg.data, str):
|
if isinstance(segment.data, str):
|
||||||
return await get_voice_text(seg.data)
|
return await get_voice_text(segment.data)
|
||||||
return "[发了一段语音,网卡了加载不出来]"
|
return "[发了一段语音,网卡了加载不出来]"
|
||||||
elif seg.type == "at":
|
elif segment.type == "at":
|
||||||
return f"[@{seg.data}]"
|
return f"[@{segment.data}]"
|
||||||
elif seg.type == "reply":
|
elif segment.type == "reply":
|
||||||
if self.reply and hasattr(self.reply, "processed_plain_text"):
|
if self.reply and hasattr(self.reply, "processed_plain_text"):
|
||||||
# print(f"self.reply.processed_plain_text: {self.reply.processed_plain_text}")
|
# print(f"self.reply.processed_plain_text: {self.reply.processed_plain_text}")
|
||||||
# print(f"reply: {self.reply}")
|
# 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 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:
|
else:
|
||||||
return f"[{seg.type}:{str(seg.data)}]"
|
return f"[{segment.type}:{str(segment.data)}]"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"处理消息段失败: {str(e)}, 类型: {seg.type}, 数据: {seg.data}")
|
logger.error(f"处理消息段失败: {str(e)}, 类型: {segment.type}, 数据: {segment.data}")
|
||||||
return f"[处理失败的{seg.type}消息]"
|
return f"[处理失败的{segment.type}消息]"
|
||||||
|
|
||||||
def _generate_detailed_text(self) -> str:
|
def _generate_detailed_text(self) -> str:
|
||||||
"""生成详细文本,包含时间和用户信息"""
|
"""生成详细文本,包含时间和用户信息"""
|
||||||
|
|
|
||||||
|
|
@ -510,7 +510,7 @@ class ActionPlanner:
|
||||||
)
|
)
|
||||||
|
|
||||||
self.last_obs_time_mark = time.time()
|
self.last_obs_time_mark = time.time()
|
||||||
|
all_sub_planner_results: List[ActionPlannerInfo] = [] # 防止Unbound
|
||||||
try:
|
try:
|
||||||
sub_planner_actions: Dict[str, ActionInfo] = {}
|
sub_planner_actions: Dict[str, ActionInfo] = {}
|
||||||
|
|
||||||
|
|
@ -581,7 +581,6 @@ class ActionPlanner:
|
||||||
sub_plan_results = await asyncio.gather(*sub_plan_tasks)
|
sub_plan_results = await asyncio.gather(*sub_plan_tasks)
|
||||||
|
|
||||||
# 收集所有结果
|
# 收集所有结果
|
||||||
all_sub_planner_results: List[ActionPlannerInfo] = []
|
|
||||||
for sub_result in sub_plan_results:
|
for sub_result in sub_plan_results:
|
||||||
all_sub_planner_results.extend(sub_result)
|
all_sub_planner_results.extend(sub_result)
|
||||||
|
|
||||||
|
|
@ -726,9 +725,7 @@ class ActionPlanner:
|
||||||
action_str = ""
|
action_str = ""
|
||||||
for action_planner_info in actions:
|
for action_planner_info in actions:
|
||||||
action_str += f"{action_planner_info.action_type} "
|
action_str += f"{action_planner_info.action_type} "
|
||||||
logger.info(
|
logger.info(f"{self.log_prefix}大脑小脑决定执行{len(actions)}个动作: {action_str}")
|
||||||
f"{self.log_prefix}大脑小脑决定执行{len(actions)}个动作: {action_str}"
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
# 如果为假,只返回副规划器的结果
|
# 如果为假,只返回副规划器的结果
|
||||||
actions = self._filter_no_actions(all_sub_planner_results)
|
actions = self._filter_no_actions(all_sub_planner_results)
|
||||||
|
|
|
||||||
|
|
@ -651,9 +651,11 @@ class DefaultReplyer:
|
||||||
action_name = action_plan_info.action_type
|
action_name = action_plan_info.action_type
|
||||||
if action_name == "reply":
|
if action_name == "reply":
|
||||||
continue
|
continue
|
||||||
|
action_description: str = "无描述"
|
||||||
|
reasoning: str = "无原因"
|
||||||
if action := available_actions.get(action_name):
|
if action := available_actions.get(action_name):
|
||||||
action_description = action.description or "无描述"
|
action_description = action.description or action_description
|
||||||
reasoning = action_plan_info.reasoning or "无原因"
|
reasoning = action_plan_info.reasoning or reasoning
|
||||||
|
|
||||||
chosen_action_descriptions += f"- {action_name}: {action_description},原因:{reasoning}\n"
|
chosen_action_descriptions += f"- {action_name}: {action_description},原因:{reasoning}\n"
|
||||||
|
|
||||||
|
|
@ -705,22 +707,22 @@ class DefaultReplyer:
|
||||||
is_group_chat = bool(chat_stream.group_info)
|
is_group_chat = bool(chat_stream.group_info)
|
||||||
platform = chat_stream.platform
|
platform = chat_stream.platform
|
||||||
|
|
||||||
|
user_id = "用户ID"
|
||||||
|
person_name = "用户"
|
||||||
|
sender = "用户"
|
||||||
|
target = "消息"
|
||||||
|
|
||||||
if reply_message:
|
if reply_message:
|
||||||
user_id = reply_message.user_info.user_id
|
user_id = reply_message.user_info.user_id
|
||||||
person = Person(platform=platform, user_id=user_id)
|
person = Person(platform=platform, user_id=user_id)
|
||||||
person_name = person.person_name or user_id
|
person_name = person.person_name or user_id
|
||||||
sender = person_name
|
sender = person_name
|
||||||
target = reply_message.processed_plain_text
|
target = reply_message.processed_plain_text
|
||||||
else:
|
|
||||||
person_name = "用户"
|
|
||||||
sender = "用户"
|
|
||||||
target = "消息"
|
|
||||||
|
|
||||||
|
mood_prompt: str = ""
|
||||||
if global_config.mood.enable_mood:
|
if global_config.mood.enable_mood:
|
||||||
chat_mood = mood_manager.get_mood_by_chat_id(chat_id)
|
chat_mood = mood_manager.get_mood_by_chat_id(chat_id)
|
||||||
mood_prompt = chat_mood.mood_state
|
mood_prompt = chat_mood.mood_state
|
||||||
else:
|
|
||||||
mood_prompt = ""
|
|
||||||
|
|
||||||
target = replace_user_references(target, chat_stream.platform, replace_bot_name=True)
|
target = replace_user_references(target, chat_stream.platform, replace_bot_name=True)
|
||||||
|
|
||||||
|
|
@ -939,9 +941,7 @@ class DefaultReplyer:
|
||||||
else:
|
else:
|
||||||
chat_target_name = "对方"
|
chat_target_name = "对方"
|
||||||
if self.chat_target_info:
|
if self.chat_target_info:
|
||||||
chat_target_name = (
|
chat_target_name = self.chat_target_info.person_name or self.chat_target_info.user_nickname or "对方"
|
||||||
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_1 = await global_prompt_manager.format_prompt(
|
||||||
"chat_target_private1", sender_name=chat_target_name
|
"chat_target_private1", sender_name=chat_target_name
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -203,18 +203,21 @@ def get_actions_by_timestamp_with_chat(
|
||||||
query = query.order_by(ActionRecords.time.asc())
|
query = query.order_by(ActionRecords.time.asc())
|
||||||
|
|
||||||
actions = list(query)
|
actions = list(query)
|
||||||
return [DatabaseActionRecords(
|
return [
|
||||||
action_id=action.action_id,
|
DatabaseActionRecords(
|
||||||
time=action.time,
|
action_id=action.action_id,
|
||||||
action_name=action.action_name,
|
time=action.time,
|
||||||
action_data=action.action_data,
|
action_name=action.action_name,
|
||||||
action_done=action.action_done,
|
action_data=action.action_data,
|
||||||
action_build_into_prompt=action.action_build_into_prompt,
|
action_done=action.action_done,
|
||||||
action_prompt_display=action.action_prompt_display,
|
action_build_into_prompt=action.action_build_into_prompt,
|
||||||
chat_id=action.chat_id,
|
action_prompt_display=action.action_prompt_display,
|
||||||
chat_info_stream_id=action.chat_info_stream_id,
|
chat_id=action.chat_id,
|
||||||
chat_info_platform=action.chat_info_platform,
|
chat_info_stream_id=action.chat_info_stream_id,
|
||||||
) for action in actions]
|
chat_info_platform=action.chat_info_platform,
|
||||||
|
)
|
||||||
|
for action in actions
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def get_actions_by_timestamp_with_chat_inclusive(
|
def get_actions_by_timestamp_with_chat_inclusive(
|
||||||
|
|
@ -474,7 +477,7 @@ def _build_readable_messages_internal(
|
||||||
|
|
||||||
truncated_content = content
|
truncated_content = content
|
||||||
if 0 < limit < original_len:
|
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))
|
detailed_message.append((timestamp, name, truncated_content, is_action))
|
||||||
else:
|
else:
|
||||||
|
|
@ -544,7 +547,7 @@ def build_pic_mapping_info(pic_id_mapping: Dict[str, str]) -> str:
|
||||||
return "\n".join(mapping_lines)
|
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)
|
格式: 在()分钟前,你使用了(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)
|
action_time_struct = time.localtime(action_time)
|
||||||
time_str = time.strftime("%H:%M:%S", action_time_struct)
|
time_str = time.strftime("%H:%M:%S", action_time_struct)
|
||||||
time_ago_str = f"在{time_str}"
|
time_ago_str = f"在{time_str}"
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported mode: {mode}")
|
||||||
|
|
||||||
line = f"{time_ago_str},你使用了“{action_name}”,具体内容是:“{action_prompt_display}”"
|
line = f"{time_ago_str},你使用了“{action_name}”,具体内容是:“{action_prompt_display}”"
|
||||||
output_lines.append(line)
|
output_lines.append(line)
|
||||||
|
|
|
||||||
|
|
@ -86,6 +86,8 @@ def _convert_messages(
|
||||||
role = "model"
|
role = "model"
|
||||||
elif message.role == RoleType.User:
|
elif message.role == RoleType.User:
|
||||||
role = "user"
|
role = "user"
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unsupported role: {message.role}")
|
||||||
|
|
||||||
# 添加Content
|
# 添加Content
|
||||||
if isinstance(message.content, str):
|
if isinstance(message.content, str):
|
||||||
|
|
|
||||||
19
src/main.py
19
src/main.py
|
|
@ -37,10 +37,9 @@ logger = get_logger("main")
|
||||||
class MainSystem:
|
class MainSystem:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
# 根据配置条件性地初始化记忆系统
|
# 根据配置条件性地初始化记忆系统
|
||||||
|
self.hippocampus_manager = None
|
||||||
if global_config.memory.enable_memory:
|
if global_config.memory.enable_memory:
|
||||||
self.hippocampus_manager = hippocampus_manager
|
self.hippocampus_manager = hippocampus_manager
|
||||||
else:
|
|
||||||
self.hippocampus_manager = None
|
|
||||||
|
|
||||||
# 使用消息API替代直接的FastAPI实例
|
# 使用消息API替代直接的FastAPI实例
|
||||||
self.app: MessageServer = get_global_api()
|
self.app: MessageServer = get_global_api()
|
||||||
|
|
@ -81,12 +80,12 @@ class MainSystem:
|
||||||
# 启动API服务器
|
# 启动API服务器
|
||||||
# start_api_server()
|
# start_api_server()
|
||||||
# logger.info("API服务器启动成功")
|
# logger.info("API服务器启动成功")
|
||||||
|
|
||||||
# 启动LPMM
|
# 启动LPMM
|
||||||
lpmm_start_up()
|
lpmm_start_up()
|
||||||
|
|
||||||
# 加载所有actions,包括默认的和插件的
|
# 加载所有actions,包括默认的和插件的
|
||||||
plugin_manager.load_all_plugins()
|
plugin_manager.load_all_plugins()
|
||||||
|
|
||||||
# 初始化表情管理器
|
# 初始化表情管理器
|
||||||
get_emoji_manager().initialize()
|
get_emoji_manager().initialize()
|
||||||
|
|
@ -114,16 +113,14 @@ class MainSystem:
|
||||||
|
|
||||||
# 将bot.py中的chat_bot.message_process消息处理函数注册到api.py的消息处理基类中
|
# 将bot.py中的chat_bot.message_process消息处理函数注册到api.py的消息处理基类中
|
||||||
self.app.register_message_handler(chat_bot.message_process)
|
self.app.register_message_handler(chat_bot.message_process)
|
||||||
|
|
||||||
await check_and_run_migrations()
|
await check_and_run_migrations()
|
||||||
|
|
||||||
|
|
||||||
# 触发 ON_START 事件
|
# 触发 ON_START 事件
|
||||||
from src.plugin_system.core.events_manager import events_manager
|
from src.plugin_system.core.events_manager import events_manager
|
||||||
from src.plugin_system.base.component_types import EventType
|
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 事件")
|
# logger.info("已触发 ON_START 事件")
|
||||||
try:
|
try:
|
||||||
init_time = int(1000 * (time.time() - init_start_time))
|
init_time = int(1000 * (time.time() - init_start_time))
|
||||||
|
|
@ -162,8 +159,6 @@ class MainSystem:
|
||||||
logger.info("[记忆遗忘] 记忆遗忘完成")
|
logger.info("[记忆遗忘] 记忆遗忘完成")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
"""主函数"""
|
"""主函数"""
|
||||||
system = MainSystem()
|
system = MainSystem()
|
||||||
|
|
@ -175,5 +170,3 @@ async def main():
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -99,6 +99,8 @@ async def _send_to_target(
|
||||||
# 创建消息段
|
# 创建消息段
|
||||||
message_segment = Seg(type=message_type, data=content) # type: ignore
|
message_segment = Seg(type=message_type, data=content) # type: ignore
|
||||||
|
|
||||||
|
reply_to_platform_id = ""
|
||||||
|
anchor_message: Union["MessageRecv", None] = None
|
||||||
if reply_message:
|
if reply_message:
|
||||||
anchor_message = message_dict_to_message_recv(reply_message.flatten())
|
anchor_message = message_dict_to_message_recv(reply_message.flatten())
|
||||||
if anchor_message:
|
if anchor_message:
|
||||||
|
|
@ -107,9 +109,6 @@ async def _send_to_target(
|
||||||
reply_to_platform_id = (
|
reply_to_platform_id = (
|
||||||
f"{anchor_message.message_info.platform}:{anchor_message.message_info.user_info.user_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(
|
bot_message = MessageSending(
|
||||||
|
|
|
||||||
|
|
@ -124,6 +124,7 @@ class ComponentRegistry:
|
||||||
self._components_classes[namespaced_name] = component_class
|
self._components_classes[namespaced_name] = component_class
|
||||||
|
|
||||||
# 根据组件类型进行特定注册(使用原始名称)
|
# 根据组件类型进行特定注册(使用原始名称)
|
||||||
|
ret = False
|
||||||
match component_type:
|
match component_type:
|
||||||
case ComponentType.ACTION:
|
case ComponentType.ACTION:
|
||||||
assert isinstance(component_info, ActionInfo)
|
assert isinstance(component_info, ActionInfo)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue