feat(proactive_thinker): 启用并优化主动思考插件

- 默认启用主动思考插件,并进行多项功能增强和修复。
- 修复了日常唤醒任务中 `stream_id` 的格式问题,确保能正确调用执行器。
- 调整了冷启动任务的初始等待时间,以更好地适应系统启动流程。
- 优化了执行器中获取日程和聊天流的逻辑,使其更加健壮。
- 简化了部分日志输出,使其更清晰。
- 增加了在调试模式下打印 Planner 和 Responder 提示词的功能,便于调试。
This commit is contained in:
minecraft1024a
2025-10-03 15:15:21 +08:00
parent 7617f85b92
commit 9b7077e773
3 changed files with 27 additions and 12 deletions

View File

@@ -18,13 +18,12 @@ class ProactiveThinkerPlugin(BasePlugin):
"""一个主动思考的插件,但现在还只是个空壳子""" """一个主动思考的插件,但现在还只是个空壳子"""
plugin_name: str = "proactive_thinker" plugin_name: str = "proactive_thinker"
enable_plugin: bool = False enable_plugin: bool = True
dependencies: list[str] = [] dependencies: list[str] = []
python_dependencies: list[str] = [] python_dependencies: list[str] = []
config_file_name: str = "config.toml" config_file_name: str = "config.toml"
config_schema: dict = { config_schema: dict = {
"plugin": { "plugin": {
"enabled": ConfigField(bool, default=False, description="是否启用插件"),
"config_version": ConfigField(type=str, default="1.1.0", description="配置文件版本"), "config_version": ConfigField(type=str, default="1.1.0", description="配置文件版本"),
}, },
} }

View File

@@ -33,7 +33,7 @@ class ColdStartTask(AsyncTask):
"""任务主循环,周期性地检查是否有需要“破冰”的新用户。""" """任务主循环,周期性地检查是否有需要“破冰”的新用户。"""
logger.info("冷启动任务已启动,将周期性检查白名单中的新朋友。") logger.info("冷启动任务已启动,将周期性检查白名单中的新朋友。")
# 初始等待一段时间,确保其他服务(如数据库)完全启动 # 初始等待一段时间,确保其他服务(如数据库)完全启动
await asyncio.sleep(20) await asyncio.sleep(100)
while True: while True:
try: try:
@@ -179,7 +179,16 @@ class ProactiveThinkingTask(AsyncTask):
f"【日常唤醒】聊天流 {stream.stream_id} 已冷却 {time_since_last_active:.2f} 秒,触发主动对话。" f"【日常唤醒】聊天流 {stream.stream_id} 已冷却 {time_since_last_active:.2f} 秒,触发主动对话。"
) )
await self.executor.execute(stream_id=stream.stream_id, start_mode="wake_up") # 构建符合 executor 期望的 stream_id 格式
if stream.group_info and stream.group_info.group_id:
formatted_stream_id = f"{stream.user_info.platform}:{stream.group_info.group_id}:group"
elif stream.user_info and stream.user_info.user_id:
formatted_stream_id = f"{stream.user_info.platform}:{stream.user_info.user_id}:private"
else:
logger.warning(f"【日常唤醒】跳过 stream {stream.stream_id},因为它缺少有效的用户信息或群组信息。")
continue
await self.executor.execute(stream_id=formatted_stream_id, start_mode="wake_up")
# 【关键步骤】在触发后,立刻更新活跃时间并保存。 # 【关键步骤】在触发后,立刻更新活跃时间并保存。
# 这可以防止在同一个检查周期内,对同一个目标因为意外的延迟而发送多条消息。 # 这可以防止在同一个检查周期内,对同一个目标因为意外的延迟而发送多条消息。
@@ -203,17 +212,15 @@ class ProactiveThinkerEventHandler(BaseEventHandler):
async def execute(self, kwargs: dict | None) -> "HandlerResult": async def execute(self, kwargs: dict | None) -> "HandlerResult":
"""在机器人启动时执行,根据配置决定是否启动后台任务。""" """在机器人启动时执行,根据配置决定是否启动后台任务。"""
logger.info("检测到插件启动事件,正在初始化【主动思考】插件...") logger.info("检测到插件启动事件,正在初始化【主动思考】")
# 检查总开关 # 检查总开关
if global_config.proactive_thinking.enable: if global_config.proactive_thinking.enable:
# 启动负责“日常唤醒”的核心任务 # 启动负责“日常唤醒”的核心任务
logger.info("【主动思考】功能已启用,正在启动“日常唤醒”任务...")
proactive_task = ProactiveThinkingTask() proactive_task = ProactiveThinkingTask()
await async_task_manager.add_task(proactive_task) await async_task_manager.add_task(proactive_task)
# 检查“冷启动”功能的独立开关 # 检查“冷启动”功能的独立开关
if global_config.proactive_thinking.enable_cold_start: if global_config.proactive_thinking.enable_cold_start:
logger.info("“冷启动”功能已启用,正在启动“破冰”任务...")
cold_start_task = ColdStartTask() cold_start_task = ColdStartTask()
await async_task_manager.add_task(cold_start_task) await async_task_manager.add_task(cold_start_task)

View File

@@ -95,9 +95,9 @@ class ProactiveThinkerExecutor:
try: try:
platform, chat_id, stream_type = stream_id.split(":") platform, chat_id, stream_type = stream_id.split(":")
if stream_type == "private": if stream_type == "private":
return chat_api.ChatManager.get_private_stream_by_user_id(platform, chat_id) return chat_api.ChatManager.get_private_stream_by_user_id(platform=platform, user_id=chat_id)
elif stream_type == "group": elif stream_type == "group":
return chat_api.ChatManager.get_group_stream_by_group_id(platform, chat_id) return chat_api.ChatManager.get_group_stream_by_group_id(platform=platform,group_id=chat_id)
except Exception as e: except Exception as e:
logger.error(f"解析 stream_id ({stream_id}) 或获取 stream 失败: {e}") logger.error(f"解析 stream_id ({stream_id}) 或获取 stream 失败: {e}")
return None return None
@@ -122,7 +122,12 @@ class ProactiveThinkerExecutor:
# 获取日程 # 获取日程
schedules = await schedule_api.ScheduleAPI.get_today_schedule() schedules = await schedule_api.ScheduleAPI.get_today_schedule()
schedule_context = ( schedule_context = (
"\n".join([f"- {s['title']} ({s['start_time']}-{s['end_time']})" for s in schedules]) "\n".join(
[
f"- {s.get('time_range', '未知时间')}: {s.get('activity', '未知活动')}"
for s in schedules
]
)
if schedules if schedules
else "今天没有日程安排。" else "今天没有日程安排。"
) )
@@ -157,7 +162,6 @@ class ProactiveThinkerExecutor:
"schedule_context": schedule_context, "schedule_context": schedule_context,
"recent_chat_history": recent_chat_history, "recent_chat_history": recent_chat_history,
"action_history_context": action_history_context, "action_history_context": action_history_context,
"relationship": {"short_impression": short_impression, "impression": impression, "attitude": attitude},
"persona": { "persona": {
"core": global_config.personality.personality_core, "core": global_config.personality.personality_core,
"side": global_config.personality.personality_side, "side": global_config.personality.personality_side,
@@ -219,7 +223,8 @@ class ProactiveThinkerExecutor:
请输出你的决策: 请输出你的决策:
""" """
if global_config.debug.show_prompt:
logger.info(f"主动思考规划器原始提示词:{prompt}")
is_success, response, _, _ = await llm_api.generate_with_model( is_success, response, _, _ = await llm_api.generate_with_model(
prompt=prompt, model_config=model_config.model_task_config.utils prompt=prompt, model_config=model_config.model_task_config.utils
) )
@@ -229,6 +234,8 @@ class ProactiveThinkerExecutor:
try: try:
# 假设LLM返回JSON格式的决策结果 # 假设LLM返回JSON格式的决策结果
if global_config.debug.show_prompt:
logger.info(f"主动思考规划器响应:{response}")
decision = orjson.loads(response) decision = orjson.loads(response)
return decision return decision
except orjson.JSONDecodeError: except orjson.JSONDecodeError:
@@ -298,4 +305,6 @@ class ProactiveThinkerExecutor:
- 你的语气应该符合你的人设以及你对Ta的好感度。 - 你的语气应该符合你的人设以及你对Ta的好感度。
- 直接输出你要说的第一句话,不要包含任何额外的前缀或解释。 - 直接输出你要说的第一句话,不要包含任何额外的前缀或解释。
""" """
if global_config.debug.show_prompt:
logger.info(f"主动思考回复器原始提示词:{prompt}")
return prompt return prompt