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?"在应用人工智能领域,虽然“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.“上下文”指的是在从大型语言模型中提取样本时所包含的所有标记。当前的技术问题在于如何在这些标记的基础上,考虑到大型语言模型本身的局限性,从而始终达到预期的效果。实际上,处理大型语言模型时,通常需要从上下文的角度来思考——也就是说,要考虑到大型语言模型在任何给定时刻所处的整体状态,以及这种状态可能带来的各种潜在行为。
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 推理过程中,为维持最佳信息集而采取的一系列策略,这包括那些除了提示之外可能出现的其他信息。
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).在大型语言模型工程发展的初期阶段,提示设计是人工智能工程工作中最重要的部分。因为大多数应用场景都需要针对一次性分类或文本生成任务而优化的提示。正如其名称所示,提示设计的主要目标是如何编写有效的提示,尤其是针对系统的提示。然而,随着我们逐渐开发出能够处理多轮推理和更长时间跨度的智能体,我们就需要找到方法来管理整个上下文状态——包括系统指令、工具、外部数据、消息历史等。
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-haystackstyle 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.尽管大语言模型具有极高的处理速度,并且能够处理越来越庞大的数据量,但我们观察到,就像人类一样,这些模型在某种情况下也会失去注意力或陷入混乱。关于“大海捞针”型基准测试的研究揭示了“上下文老化”现象:当上下文窗口中的标记数量增加时,模型从该上下文中准确回忆信息的能力就会下降。
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.虽然某些模型比其他模型表现出更温和的退化现象,但这一特性在所有模型中都存在。因此,上下文必须被视为一种有限的资源,其边际价值会逐渐下降。就像人类拥有有限的工作记忆容量一样,大型语言模型也有一个“注意力预算”,在处理大量上下文信息时,这个预算会不断被消耗。每一个新的标记都会使这个预算减少一部分,这就需要我们更加谨慎地选择哪些标记可供大型语言模型使用。
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.这种注意力稀缺现象源于大语言模型的架构限制。大语言模型基于变换器架构设计,这使得每个标记能够在整个上下文中与每个其他标记建立联系。因此,对于 n 个标记来说,就存在 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.像位置编码插值这样的技术可以让模型能够处理更长的序列,通过适应原本训练时使用的小型上下文来应对这些序列。不过,这样做会一定程度上影响模型对令牌位置的理解能力。这些因素导致性能存在渐进式提升,而非出现明显的断层:模型在处理更长的上下文时仍然表现出强大的能力,但在信息检索和长程推理方面,其精度可能会低于处理较短上下文时的表现。
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 smallestpossible 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.由于大语言模型受到有限注意力资源限制,因此优秀的上下文设计意味着要找到一组最小化的高价值标记,以最大化实现特定目标的可能性。虽然说实施这种策略很容易,但实际上却很难做到。在接下来的部分中,我们将阐述这一指导原则在实际应用中的意义,以及它如何适用于上下文的各个组成部分。
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.系统提示应该非常清晰明了,使用简单直接的语言来表达信息,从而让 AI 能够理解并做出相应的行为。合适的提示层次范围应介于两种极端情况之间——要么过于具体,以至于需要工程师手动植入复杂的逻辑来精确控制 AI 的行为;要么则过于模糊,无法为 AI 提供明确的操作指示,或者错误地假设了某种共同的行为模式。最佳的做法是在这两者之间找到平衡:既足够具体,以便有效引导 AI 的行为,又足够灵活,能够为模型提供强有力的指导原则。
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.这些工具使得代理能够更好地应对周围环境,并在处理事务时获取新的相关信息。因为工具定义了代理与其信息/操作空间之间的关联,所以非常重要的是,这些工具要能够提升效率,不仅要提供高效的信息,还要促使代理采取更高效的行为方式。
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 代理来说,我们需要构建那些能够被大语言模型很好地理解、且在功能上几乎没有重叠的工具。就像一个设计良好的代码库一样,这些工具应该具有独立性、能够承受错误,并且对于其用途来说非常清晰明了。输入参数也应该具有描述性、明确无误,并且能够充分发挥模型的固有优势。
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.我们常见的一种失败模式是工具集过于庞大,包含了过多的功能,或者导致在选择使用哪种工具时出现模糊不清的决策问题。如果人类工程师无法明确指示在某种情况下应该使用哪种工具,那么人工智能代理也难以表现得更好。正如我们稍后会讨论的,为代理提供一套最小化的工具集,可以使得在长期交互过程中更可靠地维护和修剪上下文信息。
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.提供示例,也就是所谓的“少量样本提示”,是一种被广泛认可的最佳实践,我们始终强烈建议采用这种方法。然而,团队常常会在提示中列出一系列边缘情况,试图详细说明大语言模型在特定任务中应遵循的所有规则。我们并不推荐这种做法。相反,我们建议努力收集一系列多样化的、具有代表性的示例,以有效展现智能体的预期行为。对于大语言模型来说,示例就是至关重要的“图片”,它们能传达出千言万语的信息。
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.在我们所考虑的上下文各个组成部分中(系统提示、工具、示例、消息历史等),我们的总体指导原则 adalah 要谨慎处理,确保上下文信息既具有实用性,又保持简洁明了。现在,让我们来探讨如何在运行时动态获取上下文信息吧。
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.在构建高效的人工智能代理方面,我们强调了基于大语言模型的工作流程与代理之间的区别。自那篇帖子发布以来,我们逐渐形成了对代理的简单定义:大语言模型能够自主地使用各种工具,并形成一个循环。
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.我们现在看到,工程师在设计智能体上下文方面的思维方式正在发生转变。如今,许多基于人工智能的应用程序采用某种形式的嵌入式预推理时间检索机制,以提取出重要的上下文信息,供智能体进行推理。随着这一领域逐渐转向更加以智能体为中心的方法,我们越来越多地看到团队通过“即时”上下文策略来补充这些检索系统。
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.当然,这之间存在权衡:运行时探索的速度比直接获取预计算数据要慢。不仅如此,还需要精心设计的工程手段来确保大型语言模型拥有足够的工具和启发式方法来有效处理海量的信息。如果没有适当的指导,智能体可能会因误用工具、陷入死胡同或未能识别关键信息而浪费大量时间。
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.长期任务要求代理在一系列行动中保持一致性、上下文的连贯性以及目标导向的行为表现。当操作次数超过 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 中,我们通过将消息历史记录传递给模型来实现这一功能。这样,模型能够总结并压缩最重要的信息。同时,模型还保留了架构决策、未解决的漏洞以及实现细节,而排除了冗余的工具输出或消息。用户因此可以继续利用这个压缩后的上下文信息,再加上最近访问过的五份文件。这样,用户就能获得连贯的体验,而无需担心上下文窗口的限制。
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.克劳德玩《宝可梦》游戏的过程,展示了记忆如何改变智能体在非编码领域中的能力。该智能体能够在数千个游戏步骤中保持精确的数量统计——比如“在过去的 1,234 个步骤中,我在第一路线训练我的宝可梦,皮卡丘的等级提升了 8 级,距离目标 10 级仅剩 1 级”。无需任何关于记忆结构的提示,智能体就能构建出探索区域的地图,记住自己解锁了哪些关键成就,并保留关于战斗策略的笔记,从而学会如何针对不同的对手选择最有效的攻击方式。
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).子代理架构提供了一种解决上下文限制的方法。与其让一个代理负责维护整个项目的状态,不如使用专门的子代理来处理特定的任务,这些子代理可以在相对清晰的上下文环境下完成工作。主代理负责制定总体计划,而子代理则负责进行深入的技术处理或利用工具来查找相关信息。每个子代理可以进行广泛的探索,可以使用数万甚至更多的标记,但最终只会返回一份简洁的摘要(通常包含 1,000 到 2,000 个标记)。
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.上下文工程代表了我们利用大语言模型进行构建方式的一次重大变革。随着模型能力的提升,挑战不再仅仅是如何设计出完美的提示语,而是如何精心选择那些能够在每一步中进入模型有限注意力预算中的信息。无论你是为长期任务实现压缩处理,还是设计高效的令牌使用工具,或是让智能体能够实时探索周围环境,基本原则始终保持不变:找到一组最能提升期望结果的信号性令牌,从而最大化实现目标的可能性。
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.我们所介绍的这些技术会随着模型的不断改进而不断发展。我们已经注意到,更智能的模型需要更少的规范性设计,这样才能让智能体拥有更大的自主权。不过,即使能力得到提升,将上下文视为一种宝贵的、有限的资源,仍然是构建可靠、高效的智能体的关键。
夜雨聆风