← 领域专题
Anthropic · Engineering

有效的上下文工程 Effective Context Engineering for AI Agents

摘要 · Summary

一句话:构建 AI 智能体的关键已从提示工程转向“上下文工程”,即系统性地管理进入模型有限注意力预算的信息,以最小的、高信号的 token 集最大化期望行为。

文章概述了上下文工程为何成为构建可控、高效智能体的核心技艺。作者指出,LLM 如同人类,存在注意力有限的约束:随着上下文窗口内 token 数量增加,模型准确调用信息的能力会下降,这一现象被称为“上下文腐化”,源于 Transformer 架构中 n² 级别的成对关系计算和训练数据中长序列较少分布的客观特性。因此,上下文必须被当作具有边际收益递减的“有限资源”来对待,每一枚新 token 都会消耗模型的“注意力预算”。

在有效上下文的构建方法上,作者团队为不同组件提出了明确指导。系统提示应达到“恰到好处的区间”:避免过于僵硬的硬编码逻辑,也避免过于模糊的高层指导,要使用简单、直接的语言,并以 XML 标签或 Markdown 标题等结构清晰分区。工具设计应追求 token 高效、功能清晰、互不重叠,最忌讳功能过度臃肿的工具集令智能体陷入选择歧义。提供示例(少样本提示)时,不应堆砌穷举所有边缘情况的清单,而应精选一组多样化、典型的范例来描绘期望行为。

文章进一步将上下文工程扩展至动态运行时和长期任务。面对数据,更高效的方法是“即时”上下文策略:智能体在上下文中仅保留文件路径、查询语句等轻量级标识符,在运行时通过工具动态加载数据,这与人类使用索引、书签的认知模式类似。对于长周期任务,文章介绍了三种实用技术:压缩(将趋近上限的对话历史总结提炼,开启新上下文窗口)、结构化笔记(让智能体持续向外部记忆写入并读取笔记,以在多次上下文重置后仍保持连贯性)和子智能体架构(将聚焦的、消耗大量 token 的探索任务交给独立子智能体,最终仅向主智能体返回千 token 级别的浓缩结果),并指出选择何种方法取决于具体任务特性。

作者 · Author
Anthropic Applied AI 团队Prithvi Rajasekaran、Ethan Dixon、Carly Ryan、Jeremy Hadfield

Anthropic 的应用 AI 团队,直接面向客户落地 Claude 的工程实践。本文把他们在 Claude Developer Platform 与 Claude Code 上的一手经验整理成方法论:为什么上下文要当成有限资源、system prompt 该找什么"高度"、工具集为何不能臃肿,以及长任务的三种续航技术(压缩、结构化记事、子 agent)。文中 Claude Code 的压缩策略与 Pokémon agent 跨数千步维持笔记的例子,都是他们自己产品里的实测。

正文 · Full Text

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?"

在应用型人工智能领域,提示工程曾占据焦点多年之后,一个新术语走到了聚光灯下:上下文工程。用语言模型进行构建这件事,重点正在从为提示找到合适的词语和句式,转向回答一个更宏观的问题:“哪一种上下文配置最有可能让我们的模型产生我们所期望的行为?”

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。摆在我们面前的工程问题,是优化这些 token 相对于 LLM 固有约束的效用,以期持续达成某个期望的结果。要有效地驾驭 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

上下文工程 vs. 提示工程

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.

一个在循环中运行的智能体会生成越来越多的、可能与下一轮推理相关的数据,而这些信息必须被循环地精炼。上下文工程,就是从那个不断演进的、充满可能信息的世界中,策划出将要进入有限上下文窗口的内容的技艺与科学。

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 速度很快,能够处理体量越来越大的数据,但我们观察到,LLM 和人一样,到了某个节点就会注意力涣散或陷入混乱。关于大海捞针式基准测试的研究揭示了上下文腐化这一概念:随着上下文窗口中的 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.

系统提示应当极其清晰,使用简单、直接的语言,以恰好合适的海拔高度向智能体呈现理念。这个合适的海拔,是介于两种常见失效模式之间的“金发姑娘区”。一个极端是,我们看到工程师在他们的提示中硬编码了复杂而脆弱的逻辑,以求催生精确的智能体行为。这种做法会制造脆弱性,并随时间增加维护的复杂性。另一个极端是,工程师有时会提供模糊、高层的指导,既未能给 LLM 提供达成期望输出的具体信号,又或错误地假定了共享的上下文。最佳的海拔高度要在二者间取得平衡:足够具体以有效引导行为,同时又足够灵活,能为模型提供强有力的启发式规则来引导行为。

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 智能体编写工具》一文中,我们讨论了构建能被 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 智能体》中,我们着重指出了基于 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

压缩

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 中,我们通过把消息历史传给模型,让模型对最关键的信息进行总结和浓缩来实现这一点。模型会保留架构决策、未解决的 bug 和实现细节,同时丢弃冗余的工具输出或消息。然后,智能体就可以拿着这份压缩后的上下文,外加最近访问的五个文件继续工作。用户不必为上下文窗口的限制操心,即能获得连贯的体验。

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.

这种方法实现了清晰的关注点分离——详细的搜索上下文被隔离在各个子代理内部,而主导代理则专注于综合和分析结果。这种模式在我们构建多代理研究系统的方式一文中有所讨论,它在复杂研究任务上展现出了相比单代理系统的显著改进。

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.

上下文工程代表了我们使用大语言模型构建方式的一次根本性转变。随着模型能力越来越强,挑战不仅仅在于设计完美的提示——更在于审慎地筛选每一步中哪些信息可以进入模型有限的注意力预算。无论你是在为长周期任务实施压缩、设计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的支持。

我划的重点 · Highlights