Repository navigation
ZH Course 06 动态压缩与长会话
lloydzhou edited this page Jun 1, 2026
·
3 revisions
长会话需要压缩,但过早压缩会浪费 token,也可能破坏缓存复用。bash-agent 将压缩视为经济决策,而不是简单阈值判断。
agent_compact_context() {
local trigger=${1:-auto} total_lines keep_lines drop tmp_dropped dropped_messages summary_response
keep_lines=$(store_conv_dp_decision \
"$(store_stats_get current_turn_count)" "$(store_stats_get agent_request_count)" \
"$(store_stats_get compact_request_count)" "$(store_stats_get total_input_tokens)") || true
[[ -n "$keep_lines" ]] || keep_lines=0
total_lines=$(store_conv_line_count)
# drop old lines, summarize them, keep recent turns
}摘要请求复用相同的 system prompt 和工具前缀形态。这样即使旧 conversation 被压缩,提供方的 KV cache 也更容易命中。
摘要结果写入 summary.txt,之后作为稳定上下文进入 system prompt。
DP 模型同时权衡:
- 未来缓存收益
- cache miss 成本
- 摘要生成成本
- 信息损失
- 长上下文质量惩罚
完整公式见:
决策由统计数据驱动。下面是简化示例:
| 场景 | 观测信号 | 预期动作 |
|---|---|---|
| 短会话、刚开始 | 总输入 token 低、轮次少 | 不压缩 |
| 长会话且反复缓存未命中 | token 高、miss 成本上升 | 压缩旧轮次,仅保留近期窗口 |
| 长会话但缓存复用稳定 | token 高、cache hit 稳定 | 延后压缩 |
store_conv_dp_decision 会基于当前 stats 计算保留窗口(keep_lines),而不是使用固定阈值。
压缩会丢弃旧对话行,但会保持外层 prompt 结构稳定:
[system sections]
[instruction-files]
[summary]
[recent conversation window]
[current user input]
关键不变量是结构一致性。变化的是 summary 内容和 recent window 内容。
如果摘要生成失败,运行时优先保证安全可继续:
- 当前轮继续执行,不注入损坏 summary
- 保留近期对话行作为最小可用上下文
- 条件改善后再尝试下一次压缩
这个回退策略避免上下文污染,同时保证长会话不中断。
工具调用 解释在会话和提示词层具备后,模型请求如何变成运行时动作。