AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Bug] 【定时任务】Active Agent Cron 重复调用工具,失败后仍显示 completed

Open camera-2018 opened this issue 2 months ago • 7 comments

环境

  • AstrBot v4.27.5
  • Docker Compose
  • active_agent 持久化定时任务
  • 任务绑定已有 QQ 私聊会话

问题

定时任务会继承绑定会话的完整历史。会话较长时,Agent 连续 30 次使用完全相同的参数调用同一个工具,随后达到最大步骤数。

强制生成最终回复时模型返回 malformed_function_call,Agent 最终状态为 ERROR,但 cron_jobs 中仍显示:

status=completed
last_error=NULL

用户只会收到“正在读取/分析”等中间消息,没有最终结果,看起来像任务没有触发。

日志摘要

AgentState.IDLE -> RUNNING
somellmtool({"action":"read"}) 重复调用 30 次
Agent reached max steps (30)
finish_reason=malformed_function_call
AgentState.RUNNING -> ERROR

camera-2018 avatar Sep 08 '26 05:09 camera-2018

可能原因

  1. Cron 绕过了上下文压缩
  2. Agent 失败被 Cron 当成成功

工具重复调用问题尚不清楚 可能是上下文没压缩导致的

camera-2018 avatar Sep 08 '26 05:09 camera-2018

我按当前默认分支 master@a412146 把 Cron、Agent runner 和普通消息管线对了一遍,日志里的两个现象都有可定位的代码路径。

判断与代码依据

  1. AgentState.ERROR 会被 Cron 记成 completed,这是已确认的状态传播缺口。

    • astrbot/core/cron/manager.py::CronJobManager._run_job() 先把局部变量设成 status = "completed",只有下层抛出异常才改成 failed。
    • 同文件 _woke_main_agent() 在 runner.step_until_done(agent_max_step) 后只读取 runner.get_final_llm_resp(),没有检查 runner 的最终状态。无响应、非法 session、build_main_agent() 返回空值等路径也只是记录日志后 return。
    • astrbot/core/agent/runners/tool_loop_agent_runner.py::step() 收到 role == "err" 时会把 runner 转为 AgentState.ERROR,但异步生成器是正常结束,并不会向 Cron 抛异常。因此调用链是:provider 返回 malformed_function_call 错误响应 → runner 转为 ERROR → _woke_main_agent() 正常返回 → _run_job() 保留默认 completed/NULL。这与 issue 中的日志完全一致。
  2. “Cron 完全绕过上下文压缩”与当前源码不完全相符,但 Cron 确实没有沿用普通消息的上下文配置。

    • _woke_main_agent() 会把绑定会话的 conv.history 全量装入 req.contexts。
    • 随后 astrbot/core/astr_main_agent.py::build_main_agent() 仍会把请求交给 runner;runner 的 step() 会调用 ContextManager.process(),所以仍存在按轮次和 token 的处理。
    • 差异在于 Cron 构造 MainAgentBuildConfig 时只传了少数字段,context_limit_reached_strategy、llm_compress_provider_id、max_context_length、dequeue_context_length 等都落到 dataclass 默认值。普通消息则在 astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py 的配置构造块里完整读取 compression_config。因此用户在配置档案里设置的压缩策略/轮次上限不会完整作用到 Cron;当前 Cron 默认最多保留 50 轮,并按 provider 的 token 上限再处理。长历史是否直接导致该模型重复调用仍缺少同一次请求压缩前后 token/消息数的日志,暂时只能视为合理推断。
  3. 相同工具循环目前只有提示,没有熔断。

    ToolLoopAgentRunner._track_tool_call_streak() 已按“工具名 + 参数”计数,_build_repeated_tool_call_guidance() 在第 3/4/5 次向 tool result 追加逐级提示(来源是已合并的 #9311);第 5 次以后仍只追加 L3 提示,工具照常执行,直到 step_until_done() 的全局 max_step。所以完全相同的调用达到 30 次符合当前实现,并非检测器没有识别。

另外,达到最大步数后 step_until_done() 会移除全部工具并强制请求一次纯文本总结;_woke_main_agent() 的 async for _ 会丢弃这些 AgentResponse,只持久化最终 LLM 文本,没有把这次无工具的最终文本发往绑定会话。这能解释“收到中间消息、收不到最终结果”;即使最终生成成功,也缺少显式投递路径。

修改建议

建议分成三个小改动,避免把模型行为和任务状态混在一起:

  1. 让 active-agent 执行结果显式传播。 给 runner 暴露只读的最终状态/结果(或让 _woke_main_agent() 返回一个包含 state、llm_response、reached_max_steps 的结果对象)。ERROR、构建失败、非法 session、最终响应为空/非 assistant 都应抛出带简短原因的异常或返回失败结果,由 _run_job() 统一写入 status="failed" 与 last_error。历史持久化可放在 finally,但不能吞掉执行失败。

    最小逻辑大致为:

    outcome = await run_active_agent(...)
    if outcome.state is AgentState.ERROR:
        raise RuntimeError(outcome.error_message or "active agent failed")
    
  2. 复用普通消息的 Agent 配置解析。 把 internal.py 中从 abconf 构造 MainAgentBuildConfig 的逻辑提成共享 factory,普通消息与 Cron 都传入同一个 cfg。这样配置档案里的压缩策略、max turns、fallback provider、重试等语义一致,也能避免今后继续漂移。不要在 Cron 再复制一套字段列表。

  3. 为确定性的重复调用增加保守熔断,并补齐强制总结投递。 现有提示可保留;达到可配置阈值后,至少停止再次执行“同名、同参且结果也未变化”的调用,转入一次无工具总结。把“结果未变化”纳入条件可避免误伤轮询类/有外部状态变化的工具。runner 应记录 reached_max_steps/repetition_breaker_triggered,Cron 在这种无工具收尾路径中把最终 assistant 文本明确发送到 delivery_session_str;需记录本轮是否已经发送最终结果,防止与 send_message_to_user 正常成功路径重复投递。若强制总结仍返回 role=err,任务应失败并保存错误,不应伪造成功消息。

修改后的效果

  • Dashboard 能区分 Agent 真正完成与 provider/runner 失败,last_error 可用于定位,现有正常任务仍显示 completed。
  • Cron 与普通会话使用相同上下文限制;用户配置较小的 max turns 或 LLM 压缩后,定时任务也会生效。
  • 确定性死循环会在较小上限内停止,减少重复工具副作用、LLM 调用和耗时;对参数变化或返回内容变化的合法连续调用保持兼容。
  • 最大步数后的总结能实际送达;失败路径不会只留下“正在分析”的中间消息。

建议验证

  • 在 tests/unit/test_cron_manager.py 增加 runner 最终为 DONE、ERROR(role=err)、无 final response、build 失败四组测试,分别断言数据库最终状态、last_error 和 next_run_time。
  • 增加“最大步数 + 强制总结成功”测试,断言最终文本恰好投递一次;再加 malformed_function_call,断言不投递伪成功文本且任务为 failed。
  • 在 tests/test_tool_loop_agent_runner.py 覆盖:同名同参同结果触发熔断;同名但参数变化不触发;同名同参但结果变化的轮询不误杀;阈值边界及多工具调用。
  • 增加 Cron/普通消息共享配置解析测试,给非默认 max_turns、overflow_strategy=llm_compress 和 compression provider,断言两条入口传给 runner 的 reset 参数一致。

如果要进一步确认“长历史是否是这次模型循环的直接诱因”,建议补充同一次 Cron 执行的 [BefCompact]/[AftCompact] 消息数、压缩前后 token 日志以及 provider/model 名称;这些分别用于验证 ContextManager.process() 是否触发,以及问题是否集中在特定 provider 的强制收尾响应。

LIghtJUNction avatar Sep 08 '26 07:09 LIghtJUNction

Taking the status-propagation half of this. I verified the mechanism on current master independently of the analysis above (which is correct, credit where due): _run_job presets status = "completed" and only flips on an escaped exception, while _woke_main_agent never looks at the runner's terminal state — a run ending in AgentState.ERROR (max steps + malformed_function_call, as in your log) records completed with last_error=NULL. The agent-build failure path has the same silent-completed shape.

PR incoming: _woke_main_agent raises when the runner ends in ERROR (with the final error text when available) or when the agent cannot be built, so _run_job's existing handler records failed + last_error. The runner base gains a read-only state property. Two regression tests on _run_job cover both paths, red on current master, green with the fix.

The repeated-tool-call half (why the model looped somellmtool 30 times, likely the long inherited history with no compression in the cron path) is a separate root cause and I am not touching it here.

he-yufeng avatar Sep 08 '26 17:09 he-yufeng

已提交上下文压缩配置部分的修复:#9992。

确认当前 master 不是完全绕过 ContextManager:历史已经放在正常的 req.contexts 中,但 Cron 构造 Agent 时没有传入绑定会话的 agent_runner.config.compression,导致面板中设置的摘要模型、压缩策略、轮次限制等没有生效,而是使用构造默认值。

这个 PR 让 Cron 和普通聊天共用压缩配置解析,包含摘要模型/指令、近期原文 token 保留比例、最大轮数、截断批次和上下文 token 上限兜底。

与 #9987 的失败状态传播修复互补

camera-2018 avatar Sep 09 '26 07:09 camera-2018

Taking the final-response delivery half of this issue. I verified the mechanism on current master (312ec36d5) and it's still present after #9987 / #9992:

  • cron/manager.py::_woke_main_agent() and astr_agent_tool_exec.py::_wake_main_agent_for_background_result() both consume runner.step_until_done() with async for _ ... pass, so the final assistant text is only folded into summary_note and persisted to history — never sent to delivery_session_str.
  • The conflict is structural: at forced wrap-up (tool_loop_agent_runner.py::step_until_done, max steps reached) all tools are removed, so the model cannot use send_message_to_user even though the cron system prompt asks it to "summarize and output your actions and results". Meanwhile SendMessageToUserTool's description explicitly says "For other normal text replies, you can output directly and no need to use this tool", so models that follow that hint output plain text that gets discarded.

Plan: deliver the final assistant text to the bound session when the runner ends in a done state and no send_message_to_user delivery already happened this run (guarded to avoid double-delivery), for both the cron and background-result wake paths. Will include unit tests in tests/unit/test_cron_manager.py covering delivered / already-delivered / ERROR-state cases.

xiaoyuyu6420 avatar Sep 09 '26 16:09 xiaoyuyu6420

@xiaoyuyu6420 感谢定位强制收尾时发送工具不可用的问题。不过,这里的自动投递方案似乎不只覆盖达到最大执行步数的情况,也覆盖正常结束的任务,需要区分“最终结果漏发”和“任务有意保持静默”。 现有 Cron 提示词要求按需调用 send_message_to_user,后台唤醒提示词也明确允许没有有意义的结果时不回复。因此,保存执行总结与向用户发送通知,不一定是同一件事。 例如:“每小时检查 AstrBot 是否达到 4 万 Star,仅达标时通知,否则保持静默。”未达标时,模型可能不调用发送工具,但生成“尚未达标,本轮无需通知”的执行总结。如果框架自动投递这段最终文字,就会把条件通知变成每小时发送未达标消息。即使只在本轮没有工具投递时补发,也无法区分这种有意静默。 DONE 只能说明执行完成,不能说明需要通知

camera-2018 avatar Sep 10 '26 06:09 camera-2018

@camera-2018 你说得对,这个反例成立。"DONE 只能说明执行完成,不能说明需要通知"——按需通知(send_message_to_user if needed)是现有提示词明确支持的行为,框架替模型决定"总结也要发出去"会把条件静默任务变成定时骚扰。

已在 #10008 收窄(0b030f9d2):ToolLoopAgentRunner 新增 reached_max_steps,只在 step_until_done 的强制收尾分支(拔掉全部工具那一步)置位。cron 与后台唤醒路径仅在 reached_max_steps 时补投最终文本——那是模型唯一"想发也没渠道"的场景;正常结束一律不动,静默权完全留给模型。

这样三个语义分开:

  • 执行总结 → 只进历史(persist_agent_history),行为不变
  • 主动通知 → 模型通过 send_message_to_user 决定,行为不变
  • 强制收尾兜底 → 框架补投一次,且仍带"本轮已发送过同文本则跳过"守卫

补了 test_normal_completion_stays_silent 覆盖你说的"未达标静默"场景,全量 2422 测试通过。

xiaoyuyu6420 avatar Sep 10 '26 09:09 xiaoyuyu6420