AI应用开发 - Context Engineering(上下文工程)
External Memory
什么是 External Memory?
External Memory(外部记忆) 是一种解决 LLM "冷启动"问题的技术。想象一下:你每天早上上班都要重新向同事介绍自己是谁、你的工作习惯、你喜欢怎么沟通——这就是当前 LLM 的问题。每次新对话都要重复告诉 Agent 你的偏好(比如用 Python 3.13 而不是 3.12)、项目结构(数据库表名、S3 前缀)等信息,效率很低。
External Memory 的核心思想是:把每次交互中学到的有用信息存到一个独立文件里,下次对话时 Agent 自动读取这些"记忆",避免重复指令。
解决的问题
| 痛点 | 没有 External Memory | 有 External Memory |
|---|---|---|
| Python 版本 | 每次都要说"用 3.13" | Agent 自己记得 |
| 类型规范 | 每次强调"不用 Any 类型" | Agent 自己记得 |
| 项目信息 | 每次查表名/S3 前缀 | Agent 直接知道 |
| 错误纠正 | 同类错误重复出现 | Agent 记住纠正方法 |
“使用 AI Agent 的目的是提高效率,重复指令与之相悖”
如何实现:agents.md
最简单的方法是在项目根目录创建一个 agents.md 文件。
方法一:错误时记录
当 Agent 犯错时,告诉它纠正方法并存入 agents.md:
❌ 错误:使用了 Python 3.12 语法
✅ 纠正:项目要求 Python 3.13,记得检查版本
方法二:线程结束时总结
对话结束后,用这个提示词让 Agent 自动总结:
Generalize the knowledge from this thread, and remember it for later.
Anything that could be useful to know for a later interaction,
when doing similar things. Store in agents.md
agents.md 示例
# 项目记忆
## 代码规范
- 始终使用 Python 3.13 语法
- 函数必须添加返回类型注解
- 禁止使用 Any 类型,使用 Union 或具体类型替代
## 项目结构
- 文档表名:documents_table
- S3 存储前缀:s3://my-bucket/docs/
- CloudWatch 日志组:/ecs/my-service
## 常见错误
- CSV 解析时记得处理 BOM 头
- API 超时重试最多 3 次
不用担心文件膨胀
有人担心 agents.md 会越来越大影响性能。实际上:
- LLM 擅长压缩信息:会自动把相似内容合并、精简
- 上下文窗口足够大:前沿模型支持数十万 token
- 成本反而降低:Agent 不需要每次重新查询信息
“Heavy usage of agents.md will both make LLM usage faster, and reduce cost”
Claude Code 的记忆功能
Claude Code 提供了内置的记忆命令:# 后面写要记忆的内容
三级记忆层级
| 层级 | 范围 | 例子 |
|---|---|---|
| User Memory | 所有项目通用 | 返回类型规范 |
| Folder Memory | 当前文件夹 | 某个服务的配置 |
| Project Memory | 整个仓库 | 项目结构、编码规范 |
使用方法
# Always use Python 3.13 syntax, avoid 3.12 syntax
输入后会弹出选项:
- User Memory:跨所有仓库的通用规则
- Folder Memory:当前文件夹专用
- Project Memory:整个项目的记忆
不同 Agent 的记忆文件
| Agent | 记忆文件 |
|---|---|
| Claude Code | CLAUDE.md |
| Warp | WARP.md |
| Cursor | .cursorrules |
| 通用推荐 | agents.md |
建议:优先用通用的
agents.md,因为工具会更新换代,今天 Claude Code 最好,明天可能是别的,但 agents.md 始终是你的
与 AGI 的关系
真正的持续学习(Continuous Learning)被认为是实现 AGI 的最后障碍之一。
| 当前状态 | 理想状态 |
|---|---|
| 把信息存到文件里,读取后继续 | 像人类学习本能一样,实时更新模型权重 |
| 模拟"记忆",本质还是查表 | 模型真正"学会"了新知识 |
目前 LLM 通过文件存储模拟持续学习,但这不是真正的持续学习——理想状态是模型能像人类一样,将新知识直接融入本能反应中。
实践建议
- 每次犯错都要记录:告诉 Agent “把这个纠正存到 agents.md”
- 线程结束要总结:用总结提示词让 Agent 自动提炼有价值的信息
- 不必担心膨胀:大胆记录,LLM 会自动压缩
- 跨 Agent 兼容:用 agents.md 而非专用格式
“Constantly strive to achieve heavy utilization of the agents.md file — it’s essential to becoming a good engineer with AI”
RAG and Dynamic Filters
从 RAG 到 Context Engineering
RAG(Retrieval-Augmented Generation) 曾在 2023 年火遍全球——你把私有数据用向量数据库存起来,查询时检索相关片段喂给 LLM,完美解决了"context window 不够用"的问题。
但很快 RAG 的局限就暴露了:
| 问题 | 描述 |
|---|---|
| Context Poisoning | 检索到无关甚至错误的信息,反而让答案更差 |
| Context Distraction | 太多 context 淹没模型,反而影响准确率 |
| Context Rot | 研究发现超过一定 context 大小后,准确率反而下降 |
| 规模挑战 | 100 篇文章能搞定,100 万篇呢? |
于是 RAG 进化了,有了新名字:Context Engineering。
“RAG was never the end goal, just the starting point.”
— Steve Hedden
Context Engineering 四大策略
“The art and science of filling the context window with just the right information at each step of an agent’s trajectory.” — Lance Martin
类比一下:LLM 是 CPU,context window 是 RAM。那 Context Engineering 就是操作系统决定哪些程序加载到内存的艺术。
| 策略 | 含义 | 生活类比 |
|---|---|---|
| Write | 把信息写到 context 外持久化 | 写笔记存档 |
| Select | 把相关信息选入 context | 按需查阅 |
| Compress | 只保留需要的 token | 做摘要而非复印全文 |
| Isolate | 分隔到不同子 Agent | 分工合作而非所有人挤一间办公室 |
Write(写入)
把信息写到 context window 外部存储,帮助 Agent 执行任务。
Scratchpad(草稿本):Anthropic 的 multi-agent researcher 在超过 200k token 时会截断,所以先把计划存到 Memory:
“The LeadResearcher begins by thinking through the approach and saving its plan to Memory to persist the context”
Memory(记忆):跨 session 记住东西。Reflexion 在每次 turn 后反思并重用自生成记忆。Generative Agents 定期从过去反馈合成记忆。
Select(选择)
把相关信息选入 context window。
工具太多怎么办?——用 RAG 从工具描述中检索最相关的工具。研究显示可以提高 3 倍工具选择准确率。
代码 Agent 的挑战(Windsurf 的 Varun):
“Indexing code ≠ context retrieval … we must rely on a combination of techniques like grep/file search, knowledge graph based retrieval, and … a re-ranking step”
Compress(压缩)
只保留完成任务所需的 token。
Claude Code 的 auto-compact:超过 95% context window 时,会总结整个用户-Agent 交互轨迹。
两种方式:
- Summarization(摘要):用 LLM 提炼关键信息
- Trimming(剪枝):用硬编码规则删除不重要的 context(比如移除旧消息)
Isolate(隔离)
把 context 分隔到不同地方。
多 Agent:
“Subagents operate in parallel with their own context windows, exploring different aspects of the question simultaneously.” — Anthropic
代价:可能比普通 chat 多用 15 倍 token。
沙盒隔离:HuggingFace 的 deep researcher 把代码放沙盒里跑,token-heavy 对象(图片、音频)存在沙盒中,不进入 LLM context。
动态过滤器:RAG 的精确化
传统 RAG 的问题是不够"精准"——向量相似度匹配可能找到语义相关但不实用的信息。
动态过滤器就是在检索后加一层精细筛选:
Re-rankers(重排序)
流程:
- 先用向量检索找到 100 个候选
- 用 Re-ranker 重新排序,决定最终用的 5-10 个
主流工具:Cohere Rerank、Voyage AI Rerank、Jina Reranker、BGE Reranker
过滤维度
| 维度 | 含义 |
|---|---|
| Relevance(相关性) | 和问题有多相关 |
| Groundedness(根基性) | 答案是否被 context 支持 |
| Provenance(来源) | 引用的来源是否可靠 |
| Coverage(覆盖率) | 是否检索充分 |
| Recency(时效性) | 信息是否最新 |
知识图谱:结构化 Context
知识图谱(Knowledge Graph) 用实体和关系而非扁平文本存储信息,让检索更精准、可解释。
为什么知识图谱更好?
| 传统 RAG | 知识图谱 RAG |
|---|---|
| 匹配文本片段 | 理解实体和关系 |
| 语义可能模糊 | 结构化推理 |
| 难以解释 | 可追踪推理路径 |
市场信号
2023-2025 年知识图谱领域大量收购:
- Samsung 收购 Oxford Semantic Technologies(RDFox 图数据库)
- Graphwise 成立(Ontotext + Semantic Web Company 合并)
- ServiceNow 收购 data.world
“Knowledge graphs will play a key role as a metadata layer between relational and unstructured data”
Semantic Layer(语义层)
“A way of attaching metadata to all data in a form that is both human and machine readable”
语义层让 AI 能理解、检索、推理各种数据——关系数据、文档、图片、音频、工具、记忆。
作用
| 数据类型 | 检索方式 |
|---|---|
| 关系数据 | SQL、主键查找、索引查找 |
| 非结构化文档 | 全文搜索、向量检索 |
| 图数据 | 知识图谱查询 |
| 工具 | MCP 注册表 |
| 记忆 | 长期记忆存储 |
Context Engineering 工具链
LangGraph
LangChain 的 LangGraph 为四种策略都提供了支持:
| 策略 | LangGraph 支持 |
|---|---|
| Write | thread-scoped memory + long-term memory |
| Select | embedding-based retrieval、state fetch |
| Compress | 摘要/剪枝 message list、tool call 后处理 |
| Isolate | state schema、沙盒、多 Agent 架构 |
评估工具
LangSmith、Ragas、Databricks Mosaic AI Agent Evaluation、TruLens 都提供 RAG 评估框架。
RAG 的未来
不是 RAG 死了,是 RAG 进化了。
| 过去 | 未来 |
|---|---|
| 一次性检索 | 迭代式推理循环的一部分 |
| 纯文本检索 | 多模态检索(关系、图像、音频、视频) |
| 只检索文档 | 检索工具、记忆、元数据 |
| 准确率优先 | context-aware + policy-aware + semantically grounded |
“The future of RAG is not retrieval alone, but retrieval that’s context-aware, policy-aware, and semantically grounded.”
Context Compaction
什么是 Context Compaction?
当对话越来越长时:
- 性能下降:模型要在海量历史里找重点
- 成本暴涨:每次请求的 token 都在燃烧
- 模型跑偏:太多上下文干扰,推理质量下降
Context Compaction(上下文压缩) 就是用 LLM 把对话历史总结成精简形式,用摘要替代完整历史,让对话可以"无损"继续。
四大 Coding Assistant 实现对比
Claude Code
| 特性 | 实现 |
|---|---|
| Manual | /compact 命令 |
| Auto | ~95% context 时触发 |
| 可自定义 | /compact [instructions] 比如"只总结 TODO" |
压缩 Prompt:
“Create a detailed summary of the conversation so far, preserving critical information including: what was accomplished, current work in progress, files involved, next steps, key user requests or constraints.”
已知问题:
- 多次压缩会累积信息丢失
- Mid-task 自动压缩可能导致模型"跑偏"
- 95% 阈值可能太晚(用户反馈)
OpenAI Codex CLI
| 特性 | 实现 |
|---|---|
| Manual | /compact slash command |
| Auto | token 超过阈值触发 |
| 阈值 | 180k-244k token(因模型而异) |
| 策略 | 保留最近 ~20k token + 摘要 |
| 安全边际 | 95% effective context window |
| 重试机制 | 指数退避重试 |
Codex 的 Compaction Prompt:
You are performing a CONTEXT CHECKPOINT COMPACTION.
Create a handoff summary for another LLM that will resume the task.
Include:
- Current progress and key decisions made
- Important context, constraints, or user preferences
- What remains to be done (clear next steps)
- Any critical data, examples, or references needed to continue
Be concise, structured, and focused on helping the next LLM seamlessly continue the work.
OpenCode (SST)
| 特性 | 实现 |
|---|---|
| Manual | /compact 命令 |
| Auto | isOverflow() 检测 |
| Prune 机制 | 保护最近 40k token tool 输出 |
| 禁用选项 | OPENCODE_DISABLE_AUTOCOMPACT 环境变量 |
| 摘要分类 | UI 用(2句)vs 压缩用(详细) |
OpenCode 的特点是先 Prune 再 Compaction:
- 扫描 tool calls
- 保护最近 40k token
- 超过阈值的若 >20k 可裁剪
Amp (Sourcegraph)
| 特性 | 实现 |
|---|---|
| 策略 | 纯手动,无自动压缩 |
| Handoff | 指定目标,提取相关信息到新线程 |
| Fork | 在特定点复制 context |
| Edit/Restore | 编辑或恢复历史消息 |
| Thread References | 引用其他线程提取信息 |
Amp 的哲学:“保持对话短而专注效果最好”——everything in the context window has an influence on the output.
对比总结
| Assistant | Auto | 阈值 | 保留策略 | 特殊机制 |
|---|---|---|---|---|
| Claude Code | ✅ 95% | percentage | 完整摘要 | 自定义指令 |
| Codex | ✅ | token-based | 最近 20k + 摘要 | 重试机制 |
| OpenCode | ✅ | overflow | 40k 受保护 + prune | prune 先于 compaction |
| Amp | ❌ | - | - | Handoff / Fork |
设计建议(来自研究)
推荐阈值:85-90%
95% 太晚了!Claude Code 用户反馈 auto-compact 往往在模型已经开始"跑偏"时才触发。
Compaction Prompt 模板
Create a detailed summary for continuing this coding session. Include:
1. **Completed work**: What tasks were finished
2. **Current state**: Files modified, their current status
3. **In progress**: What is being worked on now
4. **Next steps**: Clear actions to take
5. **Constraints**: User preferences, project requirements, key decisions
6. **Critical context**: Essential information for continuing
Be concise but preserve enough detail that work can continue seamlessly.
六个关键设计决策
- 阈值:85-90%(不是 95%)
- Pruning:考虑在压缩前先裁剪旧 tool 输出(OpenCode 方式)
- Warning:通知用户压缩发生了(Codex 方式)
- 禁用选项:允许用户关闭自动压缩(OpenCode 方式)
- 自定义指令:
/compact [instructions]支持定向摘要 - 会话连续性:新会话应无缝继续
已知问题与解决
| 问题 | 原因 | 解决 |
|---|---|---|
| 多次压缩质量下降 | 累积信息丢失 | 控制压缩次数,或保留原始历史 |
| Mid-task 跑偏 | 关键上下文被忽略 | 用户手动 /compact,或提高阈值 |
| Tool 输出膨胀 | 大量代码执行结果 | 先 prune 再 compaction |
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)