[Bug] 摘要模型额度耗尽后仍长时间重试,切换主模型也无法及时恢复回复
问题描述
长会话需要压缩时,如果单独配置的摘要模型已经额度耗尽,机器人会长时间等待它重试。
这时在群里把主聊天模型切换成一个正常可用的模型,切换提示成功,但继续聊天仍迟迟没有回复。本次等待接近两分钟后执行了 /new,新会话就能正常使用新模型回答。
主模型实际上已经切换成功,卡住的是回复前的历史压缩。这容易让用户误以为切换模型必须先清空会话。
如何复现?
- 使用 LLM 压缩上下文,并单独指定摘要模型;将会话聊到需要压缩。
- 摘要模型因额度耗尽返回 HTTP 429。
- 将主聊天模型切换为另一个可用模型,再继续发送消息。
- 回复仍长时间等待压缩;新建空历史会话后恢复。
预期行为
配置说明写着:摘要模型不可用或压缩失败时,就改用丢弃旧聊天的方式继续。
所以,摘要模型明确提示额度耗尽时,不应长时间反复重试。机器人应及时丢掉一部分旧聊天,再让当前主模型回答;如果无法继续,也应明确提示原因。
不是要求切换主模型时顺便切换摘要模型,而是摘要失败不应该让正常可用的主模型一直等着。
丢掉旧聊天后,也要确认剩下的内容放得下
当前代码在摘要失败后先保留原来的聊天记录。如果估算仍然太长,就只裁掉一次约一半的旧消息,然后继续调用主模型,没有再检查剩下的内容是否放得下。
但裁掉一半不代表一定够用。剩下的聊天记录或工具结果仍可能很长,主模型收到后还是可能报上下文超限。这是源码显示的风险,本次日志没有确认发生。
希望失败后能逐步丢掉最旧的完整聊天轮次,每次丢完再检查长度,直到剩下的内容能放进主模型的上下文窗口,再继续回答。当前用户消息应保留,工具调用和对应结果也要保持配对。如果连当前输入都太长,就明确报错,不要无限删历史或继续发送超限请求。
轮数限制设为 -1,只是不限聊天轮数,不代表可以无视模型的上下文容量。
对应实现:摘要失败后保留原历史、只裁掉一次约一半的旧消息。当前 master 仍是同样的处理。
环境
- AstrBot 版本:v4.28.2
- 操作系统:Linux
- 部署方式:Docker
- 消息平台适配器:QQ / OneBot v11(aiocqhttp)
- 内置 Agent;LLM 压缩;独立摘要模型
newapi/gemini-3.7-flash,主模型切换为newapi/grok-4.7。 - 压缩前最多保留对话轮数:
-1;压缩时保留最近上下文比例:0.15。
错误日志
以下为相关日志摘录,上游完整响应已省略:
[21:25:01.590] [Core] [DBUG] [context.manager:96]: Compress triggered, starting compression...
[21:25:23.305] [Core] [WARN] [sources.request_retry:68]: [OpenAI] Request failed with retryable error; retrying (2/5): Error code: 429 - ... All credentials for model gemini-3.7-flash are cooling down ... Individual quota reached ...
[21:26:57.349] [Core] [INFO] [runners.tool_loop_agent_runner:1511]: Agent execution was requested to stop by user.
[21:26:57.794] [Core] [INFO] [respond.stage:212]: ... ✅ Switched to new conversation: f7d6.
这个我来做,PR 马上到。
两个问题都核实了:摘要请求调用 text_chat() 时没传 request_max_retries,走的是默认的 5 次重试加指数退避,429 也在重试范围里,额度耗尽时要等重试全部用完才回退;回退时 _run_compression() 只做一次 truncate_by_halving(),之后没有再检查。修复:摘要请求只发一次,失败直接走截断回退;回退改成按完整轮次(split_into_rounds,tool_calls 和对应的 tool 结果在同一轮)从最旧的开始丢,每丢一轮重新计算,直到低于阈值,最新一轮始终保留。
补充核对了当前 master@9248baf 的实现。现有评论给出的“摘要只请求一次 + 按完整轮次逐步删除”方向是对的,但实现时还有两个容易遗漏、会直接影响安全回退的边界。
判断与代码依据
astrbot/core/agent/context/compressor.py::LLMSummaryCompressor.__call__()调用provider.text_chat(contexts=...)时没有传request_max_retries;astrbot/core/provider/sources/request_retry.py::_build_retrying()默认使用 5 次尝试,而且这里的数值包含首次请求。所以摘要只请求一次应显式传request_max_retries=1,不是 0。astrbot/core/agent/context/manager.py::_run_compression()在摘要失败返回原消息后,只执行一次truncate_by_halving(),且不再计数,issue 描述的超限风险成立。astrbot/core/agent/context/round_utils.py::split_into_rounds()会把首个user之前已累积的内容先单独放入一个 round。也就是说,若直接对完整 messages 做“从最旧 round 开始删除”,最先被删的可能是前导system消息,而不是最旧的用户对话。现有ContextTruncator/摘要结果都会刻意保留 system 前缀,新回退逻辑也必须保持这一语义。ContextManager.process()目前用一个宽泛的except Exception包住整个处理过程,异常后直接返回原始 messages。因此,如果“当前轮本身已超限”时只在_run_compression()里抛普通异常,外层仍会吞掉它并把超限原文交给主模型,达不到 issue 要求的“明确报错”。
原因链因此是:摘要 provider 的 429 → 默认重试/退避耗时 → 摘要失败返回原历史 → 单次减半仍可能超阈值;而在不可再删的情况下,普通异常又会被 process() 转回原历史,最终仍可能发送超限请求。
修改建议
- 摘要请求传
request_max_retries=1;保留摘要函数失败后返回原消息的兼容行为,让 manager 统一决定截断。 - 回退前先拆出连续的前导 system messages,再对剩余内容调用
split_into_rounds()。循环删除最旧的非 system完整轮次,每次用同一个token_counter重算,直到should_compress(...) == False。最新活动轮次以及其中的 assistant tool call / tool result 必须整体保留。 - 循环应有明确的“每次都减少一个 round”的进度条件;只剩 system 前缀 + 最新轮次仍超限时立即停止,不能继续删当前请求,也不能死循环。
- 为不可约的超限情况增加专用异常(例如
ContextWindowExceededError),并在ContextManager.process()中单独except ...: raise,再保留现有的普通异常 fail-open 逻辑。或者返回显式的失败结果供 runner 转成用户可见错误;关键是不能再次返回原始超限 messages。 - 日志分别记录“摘要失败,进入确定性截断”“已删除多少轮/多少 token”“最小上下文仍超限”,不要把 provider 返回的凭据或完整上下文写入日志。
伪代码可保持很小:
system, rounds = split_system_prefix(messages), split_into_rounds(rest)
while over_threshold(system + flatten(rounds)) and len(rounds) > 1:
rounds.pop(0)
if over_threshold(system + flatten(rounds)):
raise ContextWindowExceededError(...)
return system + flatten(rounds)
修改后的效果
摘要模型额度耗尽时最多等待一次失败,随后使用本地、确定性的回退;系统指令和当前用户轮不会被误删,工具调用链保持完整。历史无论多长都会逐轮收缩到安全阈值;若当前请求本身不可容纳,用户会收到明确的上下文超限错误,而不是继续等待、触发主模型二次超限,或误以为切换主模型无效。
验证建议
- 429/额度耗尽:断言摘要 provider 仅调用一次,并立即进入截断。
- 前导一条/多条 system 消息:多轮删除后仍原样保留且顺序不变。
- 含多个 tool call/result 的轮次:只能整轮保留或删除,不产生孤立 tool result。
- 需要删除两轮以上才能降到阈值:断言每轮后重算,最终
should_compress == False。 - 最新轮次单独就超限:专用异常穿透
process(),主 provider 不被调用,用户得到明确错误。 - 摘要成功、摘要返回空字符串、普通计数器异常分别回归,避免把“可恢复压缩失败”和“不可恢复上下文超限”混为一类。
@LIghtJUNction 感谢核对,PR 在 #10436,前三点都是这样实现的:摘要传 request_max_retries=1;先拆出前导 system 消息,再对剩下的部分 split_into_rounds();循环条件是 len(rounds) > 1,每次删一整轮,只剩最新一轮就停。删了几轮现在也会记一条日志(800fdcc)
最新一轮本身超限时我没有改成抛专用异常,而是记 WARNING 后照常发送:这里判断超限用的是 EstimateTokenCounter 的估算(ASCII 每字符按 0.3、中文按 0.6),不是模型真实的 tokenizer,按估算在本地拦下可能会误杀实际放得下的请求;真的超限时模型会返回准确的上下文超限错误,同样会显示给用户。如果维护者更倾向在本地直接报错,我再改
Independent follow-up after #10436: the API-confirmed overflow recovery path still needs to protect the latest user round. This is the same Provider.pop_record() root cause discussed in #7225, not a duplicate claim that #10436 introduced the problem.
Checked current master 6b2e41791e16460bfbde3f79911f4d258c6da944 and pre-#10436 master 30820a48fa9b4bc55c1b680885a642a75fdbe43d. Both reproduce the following with real ToolLoopAgentRunner, ContextManager, ProviderOpenAIOfficial, and OpenAI SDK 3.26.1 against an in-memory MockTransport:
- Summary returns HTTP 429; after #10436 this consumes one generic request attempt.
- Manager drops old complete rounds, preserving two system prefixes and the current user round. The current round alone is still above the deterministic test counter's threshold, so manager warns and sends it unchanged, as deliberately documented in #10436.
- Main API returns HTTP 400 with
context_length_exceeded/maximum context length exceededfor a request that contains the current question. _handle_api_error()callspop_record(), which deletes up to two non-system messages. When only the current user remains after the system prefix, it deletes that user.- The next main request contains only system messages. The controlled compatible API accepts it and returns an unrelated answer. Both standard and streaming runners report an assistant result, not the original overflow error.
The production requests, SDK parsing, summary fallback, and runner were not replaced. No sleep was patched and no live model/IM service/tool was used. The test API accepting system-only input is an explicit condition; APIs that reject it will instead get avoidable retries (up to the existing outer limit) and an eventual different error. This is not evidence that every real provider accepts such requests or has returned a wrong answer.
Three desired-behavior regression cases currently fail on exact current master: standard and streaming main requests must retain the current question and surface an error when it cannot fit; the third case checks that a previous round containing two tool calls and both results is dropped in full. Current pop_record() instead removes the old user and tool-calling assistant, leaving orphaned tool results. The same API-handler root cause has a real report in #7225. Existing ContextTruncator round/pair fixes do not cover this provider path.
Proposed small follow-up, pending design approval: in OpenAI _handle_api_error() only after the API has confirmed context overflow, use existing split_into_rounds() on the non-system prefix. Drop one whole oldest user round per outer recovery attempt, preserving every system message and the newest user round. If there is no older user round, or there is no user boundary to safely recover from, re-raise the original API error so the existing runner error/fallback path handles it. This does not locally reject a request based on token estimation, does not change summary/main generic retry budgets, and needs no new exception/config/helper/dependency. Keep Provider.pop_record() unchanged to avoid unnecessarily changing its public helper contract; stop using its blind two-message deletion in this handler.
Alternatives:
- Add only a latest-user guard around current
pop_record(): smaller, but still permits an old tool call to be split from its results, so does not completely solve the shared cause. - Add a local estimator-based context exception in manager/runner: broader policy and exception-path change, can reject requests that a real tokenizer accepts, and does not fix direct provider callers. Not recommended for this API-confirmed bug.
Scope excludes historical database retention, #9936's broader turn-counting/persistence issues, token-estimator policy, other providers, and key-rotation policy. No production patch has been made yet. Suggested acceptance: current-user identity and complete tool-round preservation, exact system preservation, repeated recovery is finite, original error reaches runner, compatible system-only success cannot disguise loss, standard/stream paths, and existing provider/context/retry/runner regressions.