Files
chatgpt-on-wechat/docs/memory/context.mdx
zhayujie 33cf1bc4c3 feat(memory): async LLM context summary injection on trim
- Unified flush + context injection into a single async LLM call
  (flush_from_messages accepts context_summary_callback)
- Fixed response parsing bug: handle generator returns and Claude-format
  dicts from bot.call_with_tools, which previously caused all LLM
  summaries to silently fail (falling back to rule-based extraction)
- Removed standalone context summary prompts and methods; reuse the
  existing [DAILY]/[MEMORY] summarization pipeline
- Updated docs (zh/en/ja) to reflect the new injection behavior
2026-04-13 20:13:05 +08:00

82 lines
3.4 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: 短期记忆
description: 对话上下文 — 消息管理、压缩策略和上下文操作
---
对话上下文是 Agent 的短期记忆包含当前会话中的所有消息用户输入、Agent 回复、工具调用及结果)。合理管理上下文对于 Agent 的推理质量和成本控制至关重要。
## 上下文结构
每一轮对话由以下消息组成:
```
用户消息 → Agent 思考 → 工具调用 → 工具结果 → ... → Agent 最终回复
```
一轮中可能包含多次工具调用Agent 的决策步数由 `agent_max_steps` 控制),所有工具调用和结果都会保留在上下文中,直到被压缩或裁剪。
## 关键配置
| 参数 | 说明 | 默认值 |
| --- | --- | --- |
| `agent_max_context_tokens` | 上下文最大 token 预算 | `50000` |
| `agent_max_context_turns` | 上下文最大对话轮次 | `20` |
| `agent_max_steps` | 单轮对话最大决策步数(工具调用次数) | `15` |
可通过 `config.json` 或对话中的 `/config` 命令修改。
## 压缩策略
当上下文超出限制时,系统会自动执行压缩以释放空间。整个过程分为多个阶段:
### 1. 工具结果截断
在每次决策循环开始前,系统会检查历史轮次中的工具调用结果。超过 **20000 字符** 的工具结果会被截断,仅保留首尾内容和截断说明。当前轮次的工具结果不受影响。
### 2. 轮次裁剪
当对话轮次超过 `agent_max_context_turns` 时:
- 裁剪 **最早一半** 的完整轮次(保证工具调用链的完整性)
- 被裁剪的消息会通过 LLM 总结后**写入当天的日级记忆文件**
- LLM 摘要完成后,同时将摘要**注入到保留消息的第一条用户消息开头**,帮助模型在后续对话中保持上下文连贯性
- 摘要注入在后台异步完成,不阻塞当前回复;注入的摘要在下一轮对话时生效
### 3. Token 预算裁剪
裁剪轮次后,如果 token 数仍超出预算:
- **轮次 < 5 时**:对所有轮次进行**文本压缩** — 每轮只保留第一条用户文本和最后一条 Agent 回复,去掉中间的工具调用链
- **轮次 ≥ 5 时**:再次裁剪**前半轮次**,被丢弃内容同样写入记忆并注入上下文摘要
### 4. 溢出应急处理
当模型 API 返回上下文溢出错误时:
1. 先将当前所有消息总结写入记忆
2. 执行激进裁剪(工具结果限制 10K 字符、用户文本限制 10K、最多保留 5 轮)
3. 如果仍然溢出,清空整个对话上下文
## 会话持久化
对话消息会持久化到本地数据库,服务重启后自动恢复。恢复策略:
- 恢复最近的 **`max(3, max_context_turns / 6)`** 轮对话
- 只保留每轮的**用户文本和 Agent 最终回复**,不恢复中间工具调用链
- 超过 **30 天**的历史会话自动清理
## 操作命令
在对话中可以使用以下命令管理上下文:
| 命令 | 说明 |
| --- | --- |
| `/context` | 查看当前上下文统计(消息数、角色分布、总字符数) |
| `/context clear` | 清空当前会话上下文 |
| `/config agent_max_context_tokens 80000` | 调整上下文 token 预算 |
| `/config agent_max_context_turns 30` | 调整上下文轮次上限 |
<Tip>
清空上下文后Agent 会"忘记"之前的对话内容。被裁剪和清空的内容如果已经写入长期记忆,仍可通过记忆检索找回。
</Tip>