为 AI 智能体(agent)进行有效的上下文工程(context engineering)
Effective context engineering for AI agents
段落导航
After a few years of prompt engineering being the focus of attention in applied AI, a new term has come to prominence: context engineering.
在提示词工程(prompt engineering)成为应用 AI 关注焦点几年之后,一个新术语开始崭露头角:上下文工程。
Building with language models is becoming less about finding the right words and phrases for your prompts, and more about answering the broader question of “what configuration of context is most likely to generate our model’s desired behavior?"
使用语言模型构建应用,正越来越不在于为你的提示词找到正确的词句,而更在于回答一个更广泛的问题:“什么样的上下文配置最有可能生成我们的模型所期望的行为?”
Context refers to the set of tokens included when sampling from a large-language model (LLM).
上下文(context)指的是从大语言模型(LLM)采样时包含的那组 token。
The engineering problem at hand is optimizing the utility of those tokens against the inherent constraints of LLMs in order to consistently achieve a desired outcome.
眼前的工程问题是在 LLM 的固有约束下优化这些 token 的效用,以稳定地达到期望结果。
Effectively wrangling LLMs often requires thinking in context — in other words: considering the holistic state available to the LLM at any given time and what potential behaviors that state might yield.
有效地驾驭 LLM 往往需要从上下文出发思考——换句话说:考虑 LLM 在任意给定时刻可用的整体状态,以及该状态可能产生哪些潜在行为。
In this post, we’ll explore the emerging art of context engineering and offer a refined mental model for building steerable, effective agents.
在这篇文章中,我们将探讨正在兴起的上下文工程艺术,并为构建可控、有效的智能体提供一个更精细的心智模型。
At Anthropic, we view context engineering as the natural progression of prompt engineering.
在 Anthropic,我们将上下文工程视为提示词工程的自然演进。
Prompt engineering refers to methods for writing and organizing LLM instructions for optimal outcomes (see our docs for an overview and useful prompt engineering strategies).
提示词工程指的是为获得最佳结果而编写和组织 LLM 指令的方法(概述和有用的提示词工程策略见我们的文档)。
Context engineering refers to the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference, including all the other information that may land there outside of the prompts.
上下文工程指的是一组策略,用于在 LLM 推理期间精心筛选和维护最优的 token(信息)集合,包括提示词之外可能落入其中的所有其他信息。
In the early days of engineering with LLMs, prompting was the biggest component of AI engineering work, as the majority of use cases outside of everyday chat interactions required prompts optimized for one-shot classification or text generation tasks.
在 LLM 工程的早期,提示(prompting)是 AI 工程工作中最大的组成部分,因为日常聊天交互之外的大多数用例都需要针对单次分类(one-shot classification)或文本生成任务优化的提示词。
As the term implies, the primary focus of prompt engineering is how to write effective prompts, particularly system prompts.
正如这个术语所暗示的,提示词工程的主要关注点是如何编写有效的提示词,尤其是系统提示词。
However, as we move towards engineering more capable agents that operate over multiple turns of inference and longer time horizons, we need strategies for managing the entire context state (system instructions, tools, Model Context Protocol (MCP), external data, message history, etc).
然而,随着我们转向构建能力更强的智能体,这些智能体要在多轮推理和更长的时间跨度上运行,我们需要管理整个上下文状态的策略(系统指令、工具、Model Context Protocol (MCP)、外部数据、消息历史等)。
An agent running in a loop generates more and more data that could be relevant for the next turn of inference, and this information must be cyclically refined.
在循环中运行的智能体会生成越来越多可能与下一轮推理相关的数据,而这些信息必须被循环地提炼。
Context engineering is the art and science of curating what will go into the limited context window from that constantly evolving universe of possible information.
上下文工程是一门艺术和科学,负责从不断演化的可能信息宇宙中筛选出将进入有限上下文窗口(context window)的内容。

In contrast to the discrete task of writing a prompt, context engineering is iterative and the curation phase happens each time we decide what to pass to the model.
与撰写提示词(prompt)这种离散任务不同,上下文工程是迭代的,而且每当我们决定向模型传递什么时,策展阶段都会发生。
Despite their speed and ability to manage larger and larger volumes of data, we’ve observed that LLMs, like humans, lose focus or experience confusion at a certain point.
尽管 LLM 速度快,并且能够管理越来越大量级的数据,但我们观察到,LLM 像人类一样,会在某个节点失去专注或陷入困惑。
Studies on needle-in-a-haystack style benchmarking have uncovered the concept of context rot: as the number of tokens in the context window increases, the model’s ability to accurately recall information from that context decreases.
针对大海捞针(needle-in-a-haystack)式基准测试的研究揭示了上下文腐坏(context rot)这一概念:随着上下文窗口中的 token 数量增加,模型从该上下文中准确召回信息的能力会下降。
While some models exhibit more gentle degradation than others, this characteristic emerges across all models.
尽管有些模型相比其他模型表现出更平缓的退化,但这一特征会在所有模型中出现。
Context, therefore, must be treated as a finite resource with diminishing marginal returns.
因此,上下文必须被视为一种具有边际收益递减的有限资源。
Like humans, who have limited working memory capacity, LLMs have an “attention budget” that they draw on when parsing large volumes of context.
就像工作记忆容量有限的人类一样,LLM 拥有一种“注意力预算”(attention budget),在解析大量上下文时加以动用。
Every new token introduced depletes this budget by some amount, increasing the need to carefully curate the tokens available to the LLM.
每引入一个新 token 都会消耗这项预算的一定数量,从而增加了仔细策展可供 LLM 使用的 token 的需求。
This attention scarcity stems from architectural constraints of LLMs.
这种注意力稀缺(attention scarcity)源于 LLM 的架构约束。
LLMs are based on the transformer architecture, which enables every token to attend to every other token across the entire context.
LLM 基于 transformer 架构,这使得每个 token 都能关注整个上下文中的其他所有 token。
This results in n² pairwise relationships for n tokens.
对于 n 个 token,这会产生 n² 个成对关系。
As its context length increases, a model's ability to capture these pairwise relationships gets stretched thin, creating a natural tension between context size and attention focus.
随着其上下文长度增加,模型捕捉这些成对关系的能力会被拉扯到极限,从而在上下文大小与注意力焦点之间形成一种天然张力。
Additionally, models develop their attention patterns from training data distributions where shorter sequences are typically more common than longer ones.
此外,模型从训练数据分布中形成其注意力模式,而在这些分布中,较短的序列通常比更长的序列更常见。
This means models have less experience with, and fewer specialized parameters for, context-wide dependencies.
这意味着模型对全上下文依赖关系的经验更少,且为此类依赖关系拥有的专用参数也更少。
Techniques like position encoding interpolation allow models to handle longer sequences by adapting them to the originally trained smaller context, though with some degradation in token position understanding.
位置编码插值(position encoding interpolation)等技术让模型能够通过将更长序列适配到最初训练时更小的上下文,来处理这些更长序列,尽管在 token 位置理解上会有一些退化。
These factors create a performance gradient rather than a hard cliff: models remain highly capable at longer contexts but may show reduced precision for information retrieval and long-range reasoning compared to their performance on shorter contexts.
这些因素造成的是一种性能梯度,而非硬性断崖:模型在更长上下文中仍保持很强能力,但与在较短上下文中的表现相比,可能在信息检索和长程推理上表现出精度下降。
These realities mean that thoughtful context engineering is essential for building capable agents.
这些现实意味着,深思熟虑的上下文工程对于构建有能力的智能体至关重要。
Given that LLMs are constrained by a finite attention budget, good context engineering means finding the smallest possible set of high-signal tokens that maximize the likelihood of some desired outcome.
鉴于 LLM 受限于有限的注意力预算,良好的上下文工程意味着找到尽可能小的高信号 token 集合,以最大化某个期望结果的可能性。
Implementing this practice is much easier said than done, but in the following section, we outline what this guiding principle means in practice across the different components of context.
实施这一实践说起来容易做起来难,但在下一节中,我们将概述这一指导原则在上下文的不同组成部分中实际意味着什么。
System prompts should be extremely clear and use simple, direct language that presents ideas at the right altitude for the agent.
系统提示词应该极其清晰,并使用简单、直接的语言,以适合智能体的恰当高度来呈现想法。
The right altitude is the Goldilocks zone between two common failure modes.
恰当的高度是两种常见失败模式之间的金发姑娘区(Goldilocks zone)。
At one extreme, we see engineers hardcoding complex, brittle logic in their prompts to elicit exact agentic behavior.
在一个极端,我们看到工程师在提示词中硬编码复杂、脆弱的逻辑,以引发精确的智能体行为。
This approach creates fragility and increases maintenance complexity over time.
这种方法会造成脆弱性,并随着时间推移增加维护复杂性。
At the other extreme, engineers sometimes provide vague, high-level guidance that fails to give the LLM concrete signals for desired outputs or falsely assumes shared context.
在另一个极端,工程师有时会提供模糊的高层指导,无法为 LLM 提供关于期望输出的具体信号,或者错误地假设存在共享上下文。
The optimal altitude strikes a balance: specific enough to guide behavior effectively, yet flexible enough to provide the model with strong heuristics to guide behavior.
最优高度取得平衡:足够具体以有效引导行为,又足够灵活,能为模型提供强有力的启发式方法来引导行为。

At one end of the spectrum, we see brittle if-else hardcoded prompts, and at the other end we see prompts that are overly general or falsely assume shared context.
在光谱的一端,我们看到脆弱的 if-else 硬编码提示词,而在另一端,我们看到过于泛化或错误假设存在共享上下文的提示词。
We recommend organizing prompts into distinct sections (like <background_information>, <instructions>, ## Tool guidance, ## Output description, etc) and using techniques like XML tagging or Markdown headers to delineate these sections, although the exact formatting of prompts is likely becoming less important as models become more capable.
我们建议将提示词组织成不同的部分(如 <background_information>、<instructions>、## Tool guidance、## Output description 等),并使用 XML 标签或 Markdown 标题等技术来划分这些部分,尽管随着模型能力增强,提示词的确切格式可能正变得不那么重要。
Regardless of how you decide to structure your system prompt, you should be striving for the minimal set of information that fully outlines your expected behavior.
无论你决定如何构建系统提示词,你都应该力求提供能完整勾勒出期望行为的最小信息集。
(Note that minimal does not necessarily mean short; you still need to give the agent sufficient information up front to ensure it adheres to the desired behavior.)
(注意,最小并不一定意味着简短;你仍然需要预先给智能体足够的信息,以确保它遵循期望的行为。)
It’s best to start by testing a minimal prompt with the best model available to see how it performs on your task, and then add clear instructions and examples to improve performance based on failure modes found during initial testing.
最好先用可用的最佳模型测试一个最小提示词,看看它在你的任务上表现如何,然后根据初始测试中发现的失败模式,添加清晰的指令和示例来提升性能。
Tools allow agents to operate with their environment and pull in new, additional context as they work.
工具让智能体能够在其环境中操作,并在工作过程中引入新的、额外的上下文。
Because tools define the contract between agents and their information/action space, it’s extremely important that tools promote efficiency, both by returning information that is token efficient and by encouraging efficient agent behaviors.
由于工具定义了智能体与其信息/行动空间之间的契约,因此工具必须促进效率,这既包括返回 token 高效的信息,也包括鼓励高效的智能体行为,这一点极其重要。
In Writing tools for AI agents – with AI agents, we discussed building tools that are well understood by LLMs and have minimal overlap in functionality.
在 Writing tools for AI agents – with AI agents 一文中,我们讨论了如何构建能被 LLM 很好理解、且功能重叠最少的工具。
Similar to the functions of a well-designed codebase, tools should be self-contained, robust to error, and extremely clear with respect to their intended use.
与设计良好的代码库中的函数类似,工具应当自包含、对错误健壮,并且对其预期用途极其清晰。
Input parameters should similarly be descriptive, unambiguous, and play to the inherent strengths of the model.
输入参数同样应当具有描述性、无歧义,并发挥模型的固有优势。
One of the most common failure modes we see is bloated tool sets that cover too much functionality or lead to ambiguous decision points about which tool to use.
我们看到的最常见失败模式(failure mode)之一,是工具集臃肿,覆盖了过多功能,或导致关于该使用哪个工具的模糊决策点。
If a human engineer can’t definitively say which tool should be used in a given situation, an AI agent can’t be expected to do better.
如果人类工程师都无法明确说出在给定情境下应该使用哪个工具,就不能指望 AI 智能体做得更好。
As we’ll discuss later, curating a minimal viable set of tools for the agent can also lead to more reliable maintenance and pruning of context over long interactions.
正如我们稍后将讨论的,为智能体精心维护一套最小可行工具集,也能在长时间交互中带来更可靠的上下文维护与修剪。
Providing examples, otherwise known as few-shot prompting, is a well known best practice that we continue to strongly advise.
提供示例,也称为少样本提示(few-shot prompting),是一项众所周知的最佳实践,我们仍然强烈建议这样做。
However, teams will often stuff a laundry list of edge cases into a prompt in an attempt to articulate every possible rule the LLM should follow for a particular task.
然而,团队常常会把一长串边缘情况塞进提示词中,试图阐明 LLM 在特定任务中应遵循的每一条可能规则。
We do not recommend this.
我们不推荐这种做法。
Instead, we recommend working to curate a set of diverse, canonical examples that effectively portray the expected behavior of the agent.
相反,我们建议精心挑选一组多样、规范的示例,以有效展现智能体的预期行为。
For an LLM, examples are the “pictures” worth a thousand words.
对 LLM 而言,示例就是“一图胜千言”的“图”。
Our overall guidance across the different components of context (system prompts, tools, examples, message history, etc) is to be thoughtful and keep your context informative, yet tight.
我们对上下文不同组成部分(系统提示词、工具、示例、消息历史等)的总体指导原则是:深思熟虑,并让上下文既有信息量又紧凑。
Now let's dive into dynamically retrieving context at runtime.
现在,让我们深入探讨如何在运行时动态检索上下文。
In Building effective AI agents, we highlighted the differences between LLM-based workflows and agents.
在 Building effective AI agents 一文中,我们强调了基于 LLM 的工作流与智能体之间的差异。
Since we wrote that post, we’ve gravitated towards a simple definition for agents: LLMs autonomously using tools in a loop.
自那篇文章以来,我们逐渐倾向于一个简单的智能体定义:LLM 在循环中自主使用工具。
Working alongside our customers, we’ve seen the field converging on this simple paradigm.
在与客户并肩工作的过程中,我们看到该领域正逐渐汇聚到这一简单范式上。
As the underlying models become more capable, the level of autonomy of agents can scale: smarter models allow agents to independently navigate nuanced problem spaces and recover from errors.
随着底层模型能力越来越强,智能体的自主程度也可以随之扩展:更聪明的模型让智能体能够独立穿行于细微复杂的问题空间,并从错误中恢复。
We’re now seeing a shift in how engineers think about designing context for agents.
我们现在看到,工程师在为智能体设计上下文时的思路正在发生转变。
Today, many AI-native applications employ some form of embedding-based pre-inference time retrieval to surface important context for the agent to reason over.
如今,许多 AI 原生应用采用某种基于嵌入(embedding)的推理前检索,来浮现重要上下文供智能体推理。
As the field transitions to more agentic approaches, we increasingly see teams augmenting these retrieval systems with “just in time” context strategies.
随着该领域转向更具智能体特征(agentic)的方法,我们越来越常看到团队用“即时(just in time)”上下文策略来增强这些检索系统。
Rather than pre-processing all relevant data up front, agents built with the “just in time” approach maintain lightweight identifiers (file paths, stored queries, web links, etc.) and use these references to dynamically load data into context at runtime using tools.
采用“即时”方法的智能体不是预先处理所有相关数据,而是维护轻量级标识符(文件路径、已存储的查询、网页链接等),并使用这些引用在运行时借助工具将数据动态加载到上下文中。
Anthropic’s agentic coding solution Claude Code uses this approach to perform complex data analysis over large databases.
Anthropic 的智能体编码解决方案 Claude Code 就使用这种方法,在大型数据库上执行复杂数据分析。
The model can write targeted queries, store results, and leverage Bash commands like head and tail to analyze large volumes of data without ever loading the full data objects into context.
模型可以编写有针对性的查询、存储结果,并利用像 head 和 tail 这样的 Bash 命令来分析大量数据,而无需将完整数据对象加载到上下文中。
This approach mirrors human cognition: we generally don’t memorize entire corpuses of information, but rather introduce external organization and indexing systems like file systems, inboxes, and bookmarks to retrieve relevant information on demand.
这种方法映射了人类认知:我们通常不会记住全部信息语料,而是引入文件系统、收件箱和书签等外部组织和索引系统,以便按需检索相关信息。
Beyond storage efficiency, the metadata of these references provides a mechanism to efficiently refine behavior, whether explicitly provided or intuitive.
除了存储效率之外,这些引用的元数据还提供了一种机制,可以高效地优化行为,无论这些元数据是显式提供的还是直觉性的。
To an agent operating in a file system, the presence of a file named test_utils.py in a tests folder implies a different purpose than a file with the same name located in src/core_logic/ Folder hierarchies, naming conventions, and timestamps all provide important signals that help both humans and agents understand how and when to utilize information.
对于在文件系统中运行的智能体来说,tests 文件夹中名为 test_utils.py 的文件,与位于 src/core_logic/ 中的同名文件所暗示的用途不同;文件夹层级、命名约定和时间戳都提供了重要信号,帮助人类和智能体理解如何以及何时利用信息。
Letting agents navigate and retrieve data autonomously also enables progressive disclosure—in other words, allows agents to incrementally discover relevant context through exploration.
让智能体自主导航和检索数据,也实现了渐进式披露(progressive disclosure)——换言之,允许智能体通过探索逐步发现相关上下文。
Each interaction yields context that informs the next decision: file sizes suggest complexity; naming conventions hint at purpose; timestamps can be a proxy for relevance.
每次交互都会产生上下文,为下一个决策提供信息:文件大小暗示复杂度;命名约定提示用途;时间戳可以作为相关性的代理指标。
Agents can assemble understanding layer by layer, maintaining only what's necessary in working memory and leveraging note-taking strategies for additional persistence.
智能体可以逐层组装理解,只在工作记忆(working memory)中保留必要内容,并利用笔记策略实现额外持久化。
This self-managed context window keeps the agent focused on relevant subsets rather than drowning in exhaustive but potentially irrelevant information.
这种自我管理的上下文窗口让智能体专注于相关子集,而不是淹没在详尽但可能无关的信息中。
Of course, there's a trade-off: runtime exploration is slower than retrieving pre-computed data.
当然,这存在权衡:运行时探索比检索预计算数据更慢。
Not only that, but opinionated and thoughtful engineering is required to ensure that an LLM has the right tools and heuristics for effectively navigating its information landscape.
不仅如此,还需要有主见且深思熟虑的工程,才能确保 LLM 拥有合适的工具和启发式方法,以有效穿行于其信息景观。
Without proper guidance, an agent can waste context by misusing tools, chasing dead-ends, or failing to identify key information.
如果没有适当的引导,智能体会因误用工具、追逐死胡同或未能识别关键信息而浪费上下文。
In certain settings, the most effective agents might employ a hybrid strategy, retrieving some data up front for speed, and pursuing further autonomous exploration at its discretion.
在某些场景中,最有效的智能体可能采用混合策略:预先检索一部分数据以换取速度,同时自行决定是否继续自主探索。
The decision boundary for the ‘right’ level of autonomy depends on the task.
‘正确’的自主程度这一决策边界取决于任务本身。
Claude Code is an agent that employs this hybrid model: CLAUDE.md files are naively dropped into context up front, while primitives like glob and grep allow it to navigate its environment and retrieve files just-in-time, effectively bypassing the issues of stale indexing and complex syntax trees.
Claude Code 就是一个采用这种混合模式的智能体:CLAUDE.md 文件会被直接预先放入上下文,而 glob 和 grep 这类原语让它能够自行导航环境并即时检索文件,从而有效绕开索引陈旧和语法树复杂的问题。
The hybrid strategy might be better suited for contexts with less dynamic content, such as legal or finance work.
混合策略可能更适合内容动态性较低的领域,例如法律或金融工作。
As model capabilities improve, agentic design will trend towards letting intelligent models act intelligently, with progressively less human curation.
随着模型能力的提升,智能体设计将趋向于让智能模型自主地智能行动,人工整理的部分会逐步减少。
Given the rapid pace of progress in the field, "do the simplest thing that works" will likely remain our best advice for teams building agents on top of Claude.
鉴于该领域进展迅速,“做最简单且可行的事”很可能仍是我们给基于 Claude 构建智能体的团队的最佳建议。
Long-horizon tasks require agents to maintain coherence, context, and goal-directed behavior over sequences of actions where the token count exceeds the LLM’s context window.
长时程(long-horizon)任务要求智能体在一系列动作中保持连贯性、上下文和面向目标的行为,而这些动作的 token 数量会超出 LLM 的上下文窗口。
For tasks that span tens of minutes to multiple hours of continuous work, like large codebase migrations or comprehensive research projects, agents require specialized techniques to work around the context window size limitation.
对于持续数十分钟到数小时连续工作的任务,例如大型代码库迁移或全面的研究项目,智能体需要专门技术来绕开上下文窗口大小的限制。
Waiting for larger context windows might seem like an obvious tactic.
等待更大的上下文窗口看似是一个显而易见的选择。
But it's likely that for the foreseeable future, context windows of all sizes will be subject to context pollution and information relevance concerns—at least for situations where the strongest agent performance is desired.
但在可预见的未来,各种规模的上下文窗口很可能都会受到上下文污染和信息相关性问题的影响——至少在我们希望智能体达到最强性能的场景中是如此。
To enable agents to work effectively across extended time horizons, we've developed a few techniques that address these context pollution constraints directly: compaction, structured note-taking, and multi-agent architectures.
为了让智能体能够在更长的时间跨度上有效工作,我们开发了几项直接应对这些上下文污染约束的技术:压缩(compaction)、结构化笔记(structured note-taking)和多智能体架构(multi-agent architectures)。
Compaction
压缩
Compaction is the practice of taking a conversation nearing the context window limit, summarizing its contents, and reinitiating a new context window with the summary.
压缩是指把一段即将达到上下文窗口上限的对话取出,对其内容进行总结,然后用这份总结重新开启一个新的上下文窗口。
Compaction typically serves as the first lever in context engineering to drive better long-term coherence.
压缩通常是上下文工程中用来提升长期连贯性的第一个杠杆。
At its core, compaction distills the contents of a context window in a high-fidelity manner, enabling the agent to continue with minimal performance degradation.
其核心在于,压缩以高保真的方式提炼上下文窗口的内容,使智能体能够以最小的性能损失继续工作。
In Claude Code, for example, we implement this by passing the message history to the model to summarize and compress the most critical details.
例如,在 Claude Code 中,我们通过将消息历史传给模型,让其总结并压缩最关键细节来实现这一点。
The model preserves architectural decisions, unresolved bugs, and implementation details while discarding redundant tool outputs or messages.
模型会保留架构决策、未解决的 bug 以及实现细节,同时丢弃冗余的工具输出或消息。
The agent can then continue with this compressed context plus the five most recently accessed files.
然后,智能体可以带着这个压缩后的上下文以及最近访问的五个文件继续工作。
Users get continuity without worrying about context window limitations.
用户无需担心上下文窗口限制,即可获得连续性。
The art of compaction lies in the selection of what to keep versus what to discard, as overly aggressive compaction can result in the loss of subtle but critical context whose importance only becomes apparent later.
压缩的艺术在于选择保留什么、丢弃什么,因为过于激进的压缩可能导致丢失微妙但关键的上下文,而这些上下文的重要性只有在之后才会显现。
For engineers implementing compaction systems, we recommend carefully tuning your prompt on complex agent traces.
对于实现压缩系统的工程师,我们建议在复杂的智能体轨迹(agent traces)上仔细调优提示词。
Start by maximizing recall to ensure your compaction prompt captures every relevant piece of information from the trace, then iterate to improve precision by eliminating superfluous content.
从最大化召回率开始,确保你的压缩提示词能捕获轨迹中的每一条相关信息,然后通过消除多余内容来迭代提升精确率。
An example of low-hanging superfluous content is clearing tool calls and results – once a tool has been called deep in the message history, why would the agent need to see the raw result again?
一个显而易见的冗余内容示例是清理工具调用和结果——一旦某个工具已在消息历史深处被调用过,智能体为什么还需要再次看到原始结果?
One of the safest lightest touch forms of compaction is tool result clearing, most recently launched as a feature on the Claude Developer Platform.
最安全、最轻量的压缩形式之一是工具结果清理(tool result clearing),它最近作为 Claude Developer Platform 上的一项功能推出。
Structured note-taking
结构化笔记
Structured note-taking, or agentic memory, is a technique where the agent regularly writes notes persisted to memory outside of the context window.
结构化笔记,或称智能体记忆(agentic memory),是一种让智能体定期将笔记持久化到上下文窗口之外的记忆中的技术。
These notes get pulled back into the context window at later times.
这些笔记会在之后被重新拉回上下文窗口。
This strategy provides persistent memory with minimal overhead.
这种策略以最小的开销提供持久记忆。
Like Claude Code creating a to-do list, or your custom agent maintaining a NOTES.md file, this simple pattern allows the agent to track progress across complex tasks, maintaining critical context and dependencies that would otherwise be lost across dozens of tool calls.
就像 Claude Code 创建待办事项列表,或者你的自定义智能体维护一个 NOTES.md 文件一样,这种简单模式让智能体能够在复杂任务中跟踪进度,维持关键上下文和依赖关系,否则这些会在数十次工具调用中丢失。
Claude playing Pokémon demonstrates how memory transforms agent capabilities in non-coding domains.
Claude 玩 Pokémon 展示了记忆(memory)如何改变智能体在非编程领域的能力。
The agent maintains precise tallies across thousands of game steps—tracking objectives like "for the last 1,234 steps I've been training my Pokémon in Route 1, Pikachu has gained 8 levels toward the target of 10."
智能体在数千个游戏步骤中保持精确计数——跟踪诸如“在过去 1,234 步中,我一直在 Route 1 训练我的 Pokémon,Pikachu 已提升 8 级,目标是 10 级”这样的目标。
Without any prompting about memory structure, it develops maps of explored regions, remembers which key achievements it has unlocked, and maintains strategic notes of combat strategies that help it learn which attacks work best against different opponents.
在没有任何关于记忆结构的提示的情况下,它会绘制已探索区域的地图,记住自己解锁了哪些关键成就,并维护战斗策略的战略笔记,帮助它学习哪些攻击对不同对手最有效。
After context resets, the agent reads its own notes and continues multi-hour training sequences or dungeon explorations.
在上下文重置后,智能体会读取自己的笔记,并继续数小时的训练序列或地牢探索。
This coherence across summarization steps enables long-horizon strategies that would be impossible when keeping all the information in the LLM’s context window alone.
这种跨摘要步骤的一致性使长时程策略成为可能,而如果仅将所有信息保留在 LLM 的上下文窗口中,这些策略本不可能实现。
As part of our Sonnet 4.5 launch, we released a memory tool in public beta on the Claude Developer Platform that makes it easier to store and consult information outside the context window through a file-based system.
作为 Sonnet 4.5 发布的一部分,我们在 Claude Developer Platform 上以公开测试版发布了一个记忆工具,它通过基于文件的系统,让在上下文窗口之外存储和查阅信息变得更容易。
This allows agents to build up knowledge bases over time, maintain project state across sessions, and reference previous work without keeping everything in context.
这使智能体能够随着时间积累知识库、跨会话维护项目状态,并引用先前的工作,而无需将所有内容都保留在上下文中。
Sub-agent architectures
子智能体(sub-agent)架构
Sub-agent architectures provide another way around context limitations.
子智能体架构提供了另一种绕过上下文限制的方法。
Rather than one agent attempting to maintain state across an entire project, specialized sub-agents can handle focused tasks with clean context windows.
不是让一个智能体试图在整个项目中维护状态,而是由专门的子智能体以干净的上下文窗口处理聚焦的任务。
The main agent coordinates with a high-level plan while subagents perform deep technical work or use tools to find relevant information.
主智能体用高层计划进行协调,而子智能体则执行深入的技术工作或使用工具查找相关信息。
Each subagent might explore extensively, using tens of thousands of tokens or more, but returns only a condensed, distilled summary of its work (often 1,000-2,000 tokens).
每个子智能体可能会进行广泛探索,使用数万或更多 token,但只返回其工作的浓缩、提炼后的摘要(通常是 1,000-2,000 token)。
This approach achieves a clear separation of concerns—the detailed search context remains isolated within sub-agents, while the lead agent focuses on synthesizing and analyzing the results.
这种方法实现了清晰的关注点分离——详细的搜索上下文保持隔离在子智能体内部,而主导智能体专注于综合和分析结果。
This pattern, discussed in How we built our multi-agent research system, showed a substantial improvement over single-agent systems on complex research tasks.
这种模式在 How we built our multi-agent research system 中讨论过,在复杂研究任务上相比单智能体系统表现出显著改进。
The choice between these approaches depends on task characteristics.
这些方法之间的选择取决于任务特征。
For example:
例如:
Compaction maintains conversational flow for tasks requiring extensive back-and-forth;
压缩能为需要大量往返交互的任务维持对话流;
Note-taking excels for iterative development with clear milestones;
笔记记录擅长于具有明确里程碑的迭代开发;
Multi-agent architectures handle complex research and analysis where parallel exploration pays dividends.
多智能体架构能处理复杂的研究和分析,在这些场景中并行探索能带来收益。
Even as models continue to improve, the challenge of maintaining coherence across extended interactions will remain central to building more effective agents.
即使模型持续改进,在扩展交互中保持连贯性这一挑战,仍将是构建更高效智能体的核心。
Context engineering represents a fundamental shift in how we build with LLMs.
上下文工程代表了我们在使用 LLM 构建方式上的一次根本性转变。
As models become more capable, the challenge isn't just crafting the perfect prompt—it's thoughtfully curating what information enters the model's limited attention budget at each step.
随着模型能力越来越强,挑战不仅在于精心设计完美的提示词——还在于审慎地筛选每一步中哪些信息进入模型有限的注意力预算。
Whether you're implementing compaction for long-horizon tasks, designing token-efficient tools, or enabling agents to explore their environment just-in-time, the guiding principle remains the same: find the smallest set of high-signal tokens that maximize the likelihood of your desired outcome.
无论你是在为长时程任务实现压缩、设计 token 高效的工具,还是让智能体即时探索其环境,指导原则始终如一:找到最小的一组高信号 token,以最大化你期望结果的可能性。
The techniques we've outlined will continue evolving as models improve.
我们概述的这些技术将随着模型改进而持续演进。
We're already seeing that smarter models require less prescriptive engineering, allowing agents to operate with more autonomy.
我们已经看到,更聪明的模型需要更少的规定性工程(prescriptive engineering),让智能体能够以更高的自主性运行。
But even as capabilities scale, treating context as a precious, finite resource will remain central to building reliable, effective agents.
但即便能力不断扩展,将上下文视为宝贵且有限的资源,仍将是构建可靠、有效智能体的核心。
Get started with context engineering in the Claude Developer Platform today, and access helpful tips and best practices via our memory and context management cookbook.
立即在 Claude Developer Platform 中开始使用上下文工程,并通过我们的记忆与上下文管理 cookbook 获取有用的技巧和最佳实践。
Written by Anthropic's Applied AI team: Prithvi Rajasekaran, Ethan Dixon, Carly Ryan, and Jeremy Hadfield, with contributions from team members Rafi Ayub, Hannah Moran, Cal Rueb, and Connor Jennings.
由 Anthropic 应用 AI 团队撰写:Prithvi Rajasekaran、Ethan Dixon、Carly Ryan 和 Jeremy Hadfield,团队成员 Rafi Ayub、Hannah Moran、Cal Rueb 和 Connor Jennings 亦有贡献。
Special thanks to Molly Vorwerck, Stuart Ritchie, and Maggie Vo for their support.
特别感谢 Molly Vorwerck、Stuart Ritchie 和 Maggie Vo 的支持。