Engineering at Anthropic

Effective context engineering for AI agents面向 AI 智能体的有效上下文工程

After a few years of prompt engineering being the focus of attention in applied AI, a new term has come to prominence: context engineering. 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?"经过几年在应用 AI 领域对提示词工程(prompt engineering)的关注后,一个新术语开始崭露头角:上下文工程(context engineering)。基于语言模型进行开发,重点已不再仅仅是为提示词寻找合适的措辞,而是转向回答一个更宏大的问题:“什么样的上下文配置最有可能产生我们模型所需的行为?”

Context refers to the set of tokens included when sampling from a large-language model (LLM). 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. 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)采样时所包含的一组 token。当前的工程难题在于,如何在 LLM 的固有约束下优化这些 token 的效用,以持续达成预期结果。有效驾驭 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.在这篇文章中,我们将探索这一新兴的上下文工程艺术,并提供一个精炼的思维模型,用于构建可控且高效的智能体。

Context engineering vs. prompt engineering上下文工程与提示词工程

At Anthropic, we view context engineering as the natural progression of prompt engineering. 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). 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.在 Anthropic,我们将上下文工程视为提示词工程的自然演进。提示词工程是指编写和组织 LLM 指令以获得最佳结果的方法(请参阅我们的文档以获取概述和实用的提示词工程策略)。上下文工程则指在 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. 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).在 LLM 工程的早期,提示词是 AI 工程工作中最重要的部分,因为在日常聊天交互之外,大多数用例都需要针对单次分类或文本生成任务进行优化的提示词。正如其名,提示词工程的主要重点是如何编写有效的提示词,特别是系统提示词。然而,随着我们转向构建在多轮推理和更长的时间跨度上运行的更强大的智能体,我们需要管理整个上下文状态(系统指令、工具、模型上下文协议 (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.在循环中运行的智能体会生成越来越多的数据,这些数据可能与下一轮推理相关,因此必须对其进行周期性的提炼。上下文工程是一门从不断演变的可能信息宇宙中,策划出哪些内容进入有限上下文窗口的艺术与科学。

Prompt engineering vs. context engineering
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.与编写提示词这一离散的任务不同,上下文工程是一个迭代的过程,策划阶段发生在我们决定向模型传递什么内容的每一次决策中。

Why context engineering is important to building capable agents为什么上下文工程对构建强大的智能体至关重要

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. 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.尽管 LLM 速度快且能处理越来越大的数据量,但我们观察到,它们像人类一样,在一定程度上会失去焦点或感到困惑。针对“大海捞针”式基准测试的研究揭示了“上下文腐烂”(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. Every new token introduced depletes this budget by some amount, increasing the need to carefully curate the tokens available to the LLM.虽然某些模型的退化过程比其他模型更平缓,但这一特征在所有模型中都会出现。因此,必须将上下文视为一种边际收益递减的有限资源。就像人类的工作记忆容量有限一样,LLM 在解析大量上下文时也受限于“注意力预算”。每引入一个新的 token 都会消耗一部分预算,从而增加了仔细策划可供 LLM 使用的 token 的必要性。

This attention scarcity stems from architectural constraints of LLMs. LLMs are based on the transformer architecture, which enables every token to attend to every other token across the entire context. This results in n² pairwise relationships for n tokens.这种注意力稀缺源于 LLM 的架构约束。LLM 基于 Transformer 架构,该架构使每个 token 都能关注整个上下文中的所有其他 token。这导致 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. 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.位置编码插值等技术允许模型通过将长序列调整为原始训练的较短上下文来处理它们,尽管这会牺牲一定的 token 位置理解能力。这些因素导致了性能梯度而非断崖式下跌:模型在更长的上下文中依然表现出色,但在信息检索和长程推理方面的精度可能比在较短上下文中有所下降。

These realities mean that thoughtful context engineering is essential for building capable agents.这些现实意味着,深思熟虑的上下文工程对于构建强大的智能体至关重要。

The anatomy of effective context有效上下文的解剖

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. 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.鉴于 LLM 受限于有限的注意力预算,优秀的上下文工程意味着找出尽可能少的高信号 token 集,以最大化达成预期结果的可能性。实施这一实践说起来容易做起来难,但在接下来的部分中,我们将概述这一指导原则在上下文不同组件中的实际含义。

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. 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. 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.系统提示词应极其清晰,并使用简单直接的语言,以适合智能体的维度呈现观点。合适的维度是介于两种常见失败模式之间的“金发姑娘区”(Goldilocks zone)。在一种极端情况下,工程师会在提示词中硬编码复杂且脆弱的逻辑,以诱导特定的智能体行为。这种方法会产生脆弱性,并随着时间的推移增加维护复杂性。在另一种极端情况下,工程师有时会提供模糊的高级指导,无法为 LLM 提供预期的具体信号,或者错误地假设了共享上下文。最佳维度在两者之间取得了平衡:既具体到足以有效引导行为,又灵活到足以提供强大的启发式规则来指导模型。

Calibrating the system prompt in the process of context engineering.
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. 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.在《为 AI 智能体编写工具——与 AI 智能体协作》(Writing tools for AI agents – with AI agents)一文中,我们讨论了构建 LLM 易于理解且功能重叠极少的工具。类似于设计良好的代码库中的函数,工具应该是自包含的、对错误具有鲁棒性的,并且对其预期用途极其明确。输入参数也应具有描述性、无歧义,并发挥模型固有的优势。

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. 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. 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.我们看到的最常见失败模式之一是臃肿的工具集,它们涵盖了过多的功能,或导致在选择使用哪个工具时出现模糊的决策点。如果人类工程师无法明确指出在特定情况下应该使用哪个工具,那么就不应指望 AI 智能体能做得更好。正如我们稍后将讨论的,为智能体策划一个最小可行工具集,也能在长期的交互中实现更可靠的维护和上下文修剪。

Providing examples, otherwise known as few-shot prompting, is a well known best practice that we continue to strongly advise. 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. 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 在特定任务中应遵循的每一条规则。我们不建议这样做。相反,我们建议致力于策划一组多样化的、规范的示例,以有效展现智能体的预期行为。对于 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.我们对上下文各个组件(系统提示词、工具、示例、消息历史记录等)的总体指导是:深思熟虑,保持上下文信息丰富且紧凑。现在,让我们深入探讨在运行时动态检索上下文。

Context retrieval and agentic search上下文检索与智能体搜索

In Building effective AI agents, we highlighted the differences between LLM-based workflows and agents. Since we wrote that post, we’ve gravitated towards a simple definition for agents: LLMs autonomously using tools in a loop.在《构建有效的 AI 智能体》(Building effective AI agents)一文中,我们强调了基于 LLM 的工作流与智能体之间的区别。自那篇文章发布以来,我们倾向于对智能体下一个简单的定义:在循环中自主使用工具的 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. As the field transitions to more agentic approaches, we increasingly see teams augmenting these retrieval systems with “just in time” context strategies.我们现在看到工程师在设计智能体上下文时的思维方式发生了转变。如今,许多 AI 原生应用采用某种形式的基于嵌入的预推理检索来呈现重要上下文,供智能体进行推理。随着该领域向更具智能体特性的方法过渡,我们越来越多地看到团队通过“即时”(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. 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. 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.采用“即时”方法的智能体不会预先处理所有相关数据,而是维护轻量级标识符(文件路径、存储的查询、网页链接等),并使用这些引用通过工具在运行时动态加载数据到上下文中。Anthropic 的智能体编码解决方案 Claude Code 使用这种方法对大型数据库执行复杂的数据分析。模型可以编写有针对性的查询,存储结果,并利用 head 和 tail 等 Bash 命令分析海量数据,而无需将完整的数据对象加载到上下文中。这种方法反映了人类的认知:我们通常不会记住所有的信息全集,而是引入外部组织和索引系统(如文件系统、收件箱和书签)来按需检索相关信息。

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. 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. 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. Without proper guidance, an agent can waste context by misusing tools, chasing dead-ends, or failing to identify key information.当然,这也有权衡:运行时探索比检索预计算的数据要慢。不仅如此,还需要有主见且深思熟虑的工程设计,以确保 LLM 拥有正确工具和启发式规则来有效导航其信息景观。如果没有适当的指导,智能体可能会因误用工具、陷入死胡同或无法识别关键信息而浪费上下文。

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 构建智能体的团队的最佳建议。

Context engineering for long-horizon tasks长程任务的上下文工程

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. 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.长程任务要求智能体在 token 计数超过 LLM 上下文窗口的动作序列中保持连贯性、上下文和目标导向行为。对于跨越数十分钟到数小时连续工作的任务,如大型代码库迁移或综合研究项目,智能体需要专门的技术来解决上下文窗口大小的限制。

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. The model preserves architectural decisions, unresolved bugs, and implementation details while discarding redundant tool outputs or messages. 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.例如在 Claude Code 中,我们通过将消息历史记录传递给模型来总结和压缩最关键的细节。模型保留架构决策、未解决的错误和实现细节,同时丢弃冗余的工具输出或消息。然后,智能体可以使用这种压缩后的上下文加上最近访问的五个文件继续工作。用户获得了连续性,而无需担心上下文窗口的限制。

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. 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.一个低垂的果实是清除多余内容,即清理工具调用和结果——一旦工具在消息历史记录的深处被调用,智能体为什么还需要再次看到原始结果呢?最安全、最轻量级的压缩形式之一是工具结果清除,这是最近在 Claude 开发者平台上推出的功能。

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. 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. 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." 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.Claude 玩《宝可梦》展示了记忆如何在非编码领域改变智能体的能力。智能体在数千个游戏步骤中保持精确的统计——跟踪目标,例如“在过去的 1,234 步中,我一直在 1 号道路训练我的宝可梦,皮卡丘已经提升了 8 级,目标是 10 级。”在没有任何关于记忆结构提示的情况下,它绘制了已探索区域的地图,记住了已解锁的关键成就,并维护了战斗策略的战略笔记,帮助它了解哪些攻击对不同的对手最有效。

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. This allows agents to build up knowledge bases over time, maintain project state across sessions, and reference previous work without keeping everything in context.作为 Sonnet 4.5 发布的一部分,我们在 Claude 开发者平台上发布了一个处于公共测试阶段的记忆工具,通过文件系统使在上下文窗口之外存储和查询信息变得更加容易。这允许智能体随着时间的推移构建知识库,跨会话维护项目状态,并在不将所有内容保留在上下文中的情况下引用以前的工作。

Sub-agent architectures子智能体架构

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.即使模型不断改进,在扩展交互中保持连贯性的挑战对于构建更有效的智能体来说,仍将处于核心地位。

Conclusion结论

Context engineering represents a fundamental shift in how we build with LLMs. 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.上下文工程代表了我们使用 LLM 构建方式的根本性转变。随着模型变得更加强大,挑战不仅仅在于精心设计完美的提示词——而在于在每一步深思熟虑地策划哪些信息进入模型有限的注意力预算。无论你是在为长程任务实施压缩、设计 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. 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 开发者平台上开始上下文工程,并通过我们的记忆和上下文管理手册获取有用的提示和最佳实践。

Acknowledgements致谢

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. Special thanks to Molly Vorwerck, Stuart Ritchie, and Maggie Vo for their support.由 Anthropic 应用 AI 团队撰写:Prithvi Rajasekaran、Ethan Dixon、Carly Ryan 和 Jeremy Hadfield,团队成员 Rafi Ayub、Hannah Moran、Cal Rueb 和 Connor Jennings 亦有贡献。特别感谢 Molly Vorwerck、Stuart Ritchie 和 Maggie Vo 的支持。


Get the developer newsletter订阅开发者通讯

Product updates, how-tos, community spotlights, and more. Delivered monthly to your inbox.产品更新、操作指南、社区精选等。每月发送到你的收件箱。