AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Bug] `<system_reminder>` 每轮写入对话历史且不被清理,导致上下文持续增长

Open lingyun14beta opened this issue 2 months ago • 3 comments

问题描述

_append_system_reminders 在追加"当前时间"提醒时没有调用 .mark_as_temp(),导致这条本应只对当前请求生效的临时内容被持久化进对话历史,并在之后每一轮请求中重复发送。

同一个文件里的知识库注入(astr_main_agent.py:310-314)正确调用了 .mark_as_temp(),说明这是遗漏而非设计。

影响

  • 对话历史随轮次线性增长,每轮多一条时间提醒,且永不清理
  • 过期的时间信息对当前轮次无意义,属于无效上下文
  • 白占 token,并会更早触发上下文压缩;压缩会额外调用一次 LLM 做总结,增加成本与延迟

如何复现?

在同一会话中连续进行多轮对话 通过 on_llm_request 钩子抓取请求,观察 req.contexts

AstrBot 版本

null

操作系统

Windows

部署方式

null

使用的消息平台适配器

nc

错误日志

-

辅助信息

No response

检查清单

  • [x] 我已在 Issue 列表中搜索过相关问题仍无法解决,或该问题从未被报告过。
  • [x] 我已尝试过禁用所有插件,排除了可能是因插件导致的问题。
  • [x] 我报告的问题与 AstrBot 本体相关,而非在报告某一插件的问题。
  • [x] 我已阅读并同意本项目的贡献者行为准则。
  • [ ] (可选)我愿意提交 PR 以帮助修复该问题。

lingyun14beta avatar Sep 10 '26 14:09 lingyun14beta

这个现象本身可以从当前源码确认,但“直接补 .mark_as_temp()”不是无副作用修复。关联的 PR #10044 已因上下文缓存影响关闭;我补充一下完整原因链,避免把它与知识库注入简单类比。

已确认的代码行为

  • astrbot/core/astr_main_agent.py::_append_system_reminders 把当前时间、用户标识、群名组成 TextPart 放进 ProviderRequest.extra_user_content_parts,当前确实没有 mark_as_temp()。
  • astrbot/core/provider/entities.py::ProviderRequest.assemble_context 把这些 part 合并到本轮 user message。
  • 持久化路径 astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py::_save_to_history 会通过 dump_messages_with_checkpoints 过滤 _no_save 内容;tests/test_conversation_checkpoint.py 也验证了临时 part 不会保存。因此 #10044 的一行修改确实能阻止旧 reminder 留在历史中。
  • 但这与知识库结果不完全等价:时间提醒每轮都处在“本轮 user 后、assistant 前”。若第 N 轮发给 provider 的输入包含 user_N + reminder_N,保存时却删掉 reminder_N,第 N+1 轮重放的历史会变成 user_N + assistant_N。它与第 N 轮已缓存输入在上一条 user message 内发生分叉,后续 assistant/新消息无法继续命中同一前缀。保留 reminder 则能逐字重放上一轮输入,维持最长前缀缓存。

所以应区分:

  • 事实:旧 reminder 会随历史增长,可能增加 token/更早触发压缩。
  • 事实:标记 temporary 会改变下一轮重放的字节序列。
  • 需要实测的权衡:节省的 reminder token/压缩次数,是否大于不同 provider 上减少的 cached-token 命中。现有单元测试 test_append_system_reminders_includes_weekday 只测内容,没有回答这个成本问题。

建议

当前不建议直接重新提交 #10044 的一行改动。若要继续优化,应先做 provider payload 级的两轮/多轮基准:

  1. 固定同一 conversation,记录第 N、N+1 轮最终序列化的 messages,明确最长公共前缀;
  2. 分别统计 OpenAI-compatible/Anthropic/Gemini 等实际返回的 cached input tokens、总输入 token、压缩触发轮次和延迟;
  3. 覆盖仅 datetime、identifier/group name、工具调用、图片、上下文压缩后的路径。

如果数据证明历史增长更昂贵,再考虑可配置策略(例如“最大缓存优先”保留、或“最小历史优先”临时化),并在配置说明中写清成本语义;不要改变默认值却没有迁移/成本说明。更长期的实现可以评估 provider 原生的 cache-control/ephemeral 元数据,但必须按 provider 能力分支,不能假设所有兼容接口语义一致。

修改后的合理目标不是单纯“历史里看不到 reminder”,而是:用户回答仍获得当前时间,持久化增长有界,同时可观测的缓存命中率和成本不发生不可接受回退。

LIghtJUNction avatar Sep 13 '26 08:09 LIghtJUNction

结论:本体 bug,现象可复现。

根因:reminder 以普通内容块形式并入本轮 user 消息,未标记为临时内容,因此随历史一起落库 —— astrbot/core/astr_main_agent.py:1017 @ 4007d64;同文件的知识库注入(:313)有 .mark_as_temp()。

建议:为该 part 加 .mark_as_temp()(落库侧已按 part 过滤此类内容,已有单测覆盖),本轮请求内容不变,仅不写入历史。缓存影响已本地模拟量化(重建逐轮 payload 比较公共前缀):前缀仍逐字复用,仅每轮多算约一条 reminder(≈183 字符),而保留会每轮永久累积,按缓存折扣计价约第 5 轮起"保留"成本反超。

需要补充的信息:AstrBot 版本 为空,行号与版本对齐需要确认。

建议标签:area:core


🤖 本评论由 AI 生成,结论已基于仓库代码核实;如有出入,以维护者判断为准。

silvaling avatar Sep 13 '26 15:09 silvaling

I think the cache objection on #10044 is real but points the other way, and the "it would drop the whole message" worry does not apply. Both are checkable against the code.

The whole-message worry does not apply. The save path filters at the part level, not the message level:

# astrbot/core/agent/message.py, dump_messages_with_checkpoints
message_data["content"] = [
    part.model_dump()
    for part in message.content
    if not getattr(part, "_no_save", False)
]

The message-level _no_save check in internal.py:580 is a separate mechanism, used for whole injected messages (persona_mgr.py:410). Running the real functions over two turns:

=== TODAY (persisted) ===
  user      ['user prompt 1', '<system_reminder>Current datetime: ... 11:00</system_reminder>']
  assistant ['reply 1']
  user      ['user prompt 2', '<system_reminder>Current datetime: ... 12:00</system_reminder>']
  assistant ['reply 2']

=== WITH mark_as_temp() ===
  user      ['user prompt 1']
  assistant ['reply 1']
  user      ['user prompt 2']
  assistant ['reply 2']

The user's own prompt survives in the same message. That is exactly what the knowledge-base injection at astr_main_agent.py:306-310 already relies on.

The cache objection, stated precisely. Persisting does buy something. At turn N the prompt becomes an exact extension of turn N-1's entire prompt, so the cached prefix reaches through u(N-1) + r(N-1). With mark_as_temp() the prefix reaches through u(N-1) only, and the match ends just before that turn's reminder. So the objection is not imaginary.

It is the size of the trade that decides it. The saving is one reminder, once. The cost is every previous reminder, forever:

turn |  dead reminders carried   |  cache reuse gained by persisting
-----+---------------------------+----------------------------------
   2 |   1 reminder,   131 chars |  1 reminder, 131 chars
   5 |   4 reminders,  524 chars |  1 reminder, 131 chars
  10 |   9 reminders, 1179 chars |  1 reminder, 131 chars
  50 |  49 reminders, 6419 chars |  1 reminder, 131 chars

(131 chars is a reminder carrying both identifier and datetime_system_prompt.)

The two are equal at turn 2 and diverge linearly after it. Past the second turn, persisting pays a growing bill to avoid re-processing a fixed 131 characters — and those extra characters are themselves sent on every subsequent request, cached or not. The report's other point compounds it: they push the conversation into compaction earlier, and compaction spends an extra LLM call.

There is also a correctness side that caching cannot offset. Every persisted reminder states a time that has passed, so a long session hands the model a list of stale timestamps alongside the current one. datetime_system_prompt exists to tell the model what time it is now.

If maintainers agree, I am happy to send the one-line change with a regression cell pinning that the user's prompt survives while the reminder does not — and, if the cache behaviour is worth keeping visible, a note in the function saying why the trade goes this way. If the position is that the last turn's cache reach matters more, then this issue is really a request to stop accumulating them, and the fix would be pruning older reminders rather than marking them temp. Either is fine; the current state does both things badly.

L4XB avatar Sep 15 '26 19:09 L4XB