AIsaAIsaStudio English 打开 AIsa Studio

AWS 解析生产级 AI Agent 的四层上下文工程,Deep Insight 开源实现单工具省 token 约 95%

原标题:Four layers of context engineering for production AI agents: How Deep Insight applies them in working code

AWS 团队在 Deep Insight 开源多智能体方案中实践四层上下文工程:多智能体架构隔离、Prompt 限制输出、文件系统外置重内容、验证智能体与兜底机制,方案基于 Strands Agents SDK 与 Amazon Bedrock AgentCore。单一 write_and_execute_tool 使每个脚本写入上下文的 token 减少约 95%,按需加载 Skills 让系统提示词缩小约 97%,并给出各 Agent 的输出 token 预算、验证阈值与选择性 prompt caching 配置。

为什么值得看

文章把上下文工程整理为四层可落地的实践,并给出开源实现中约 95% 与 97% 的具体省 token 数据,可直接迁移到自己的 Agent 项目。

阅读原文 ↗11月5日 AI 日报

本页的摘要、推荐理由与解读出自 AIsa Studio 的 AI 风向智能体,原文版权归原作者所有。

深度解读

发生了什么

AWS Machine Learning 发布系列文章第二部分,以开源多智能体数据分析方案 Deep Insight 为参考实现,详解生产级 AI Agent 的四层上下文工程实践。文章基于 Strands Agents SDK 与 Amazon Bedrock AgentCore 构建,梳理自 Anthropic 的多篇工程博客,并提供可直接落地的代码。

文中给出的量化效果明确:单一 write_and_execute_tool 使每个脚本写入上下文的 token 减少约 95%,按需加载 Skills 使系统提示词缩减约 97%。

关键细节

文章将上下文工程定义为「优化 LLM 有限上下文窗口内信息」的学科,并指出即便有 200K token 窗口,一个「分析销售数据并生成 DOCX 报告」的任务也会在 15 分钟内消耗超过 150K token。四层实践层层递进、互相补位:

  • 架构层:Coordinator、Planner、Plan Reviewer、Supervisor 及 Coder/Validator/Reporter/Tracker/Auditor 等工具 Agent 各自持有独立上下文,仅通过共享的 shared_state(messages、clues、full_plan、history 四项)传递压缩结果,Coder 全程保持在 25K token 以内。
  • 提示词层:为每个 Agent 设定输出 token 预算(如 Coder 1,000–1,500、Validator 800)、统一响应格式、「变量不跨脚本持久化」的自包含代码原则,以及 Supervisor 的清单完成规则。
  • 工具层:合并文件写入与执行为单个工具,代码不作为消息进入上下文,只返回约三行摘要;公共逻辑抽为 coder_analysis_utils.py 模块复用;文件系统充当 Agent 间通信总线(all_results.txt、calculation_metadata.json、citations.json 等);Skills 启动时仅加载约 500 token 的目录,需要时再读取约 3K 的完整 SKILL.md。
  • 验证层:Validator 独立重算并按计算量分级验证(阈值 50/20),比对容差 0.01;Auditor 只读审计最终 DOCX 并可触发最多两次定向重试;SummarizingConversationManager 作为最后防线,溢出时总结最旧 50% 消息并保留最近 10 条;此外按 Agent 调用频率选择性开启 prompt 缓存,重复调用最高可降低 90% 输入成本,而 Coordinator、Planner、Validator、Tracker 等低复用 Agent 不开启。

为什么重要

文章引用 Anthropic 的「Context rot」观察——上下文越长,模型对信息的准确回忆能力越差。这意味着上下文管理不只是省钱问题,也直接影响任务中途失败、精度下降和整条流水线重跑的成本。单上下文跑长任务的三个具体痛点:窗口中途溢出、陈旧上下文劣化性能、出错需整体重跑。

方法论的另一层价值在于工程化门槛的降低。文章强调这些技术大多已内置于 Strands Agents SDK(SummarizingConversationManager、prompt 缓存、agents-as-tools 模式),开发者无需从零搭建。Deep Insight 已开源,附带 Workshop,可直接查阅代码并迁移到自己的业务领域。

对谁有影响

需要构建或维护生产级多智能体系统的工程团队是核心受众,尤其是数据分析、报告生成等长时程、重 I/O 场景的开发者。按 token 计费的团队可从分层省 token 与选择性缓存中直接获益。对关注 Agent 架构设计的人,这篇文章示范了如何把散见于 Anthropic 各篇博客的建议整合为可运行的参考实现。

全文翻译

以下翻译只覆盖原文的前一部分,其余内容请看下方原文。

当生产环境中的 AI 智能体处理数据分析与报告生成等任务时,上下文管理可能成为主要的瓶颈。200K token 的窗口听起来很慷慨,直到现实世界的任务在几分钟内就消耗掉大部分窗口。数据分析和报告生成会导致智能体在执行中途失败、精度下降或成本上升。虽然已有大量已发表的指南解决了这一问题,但单独的技术往往容易阅读却难以应用。将它们结合使用时,能产生可衡量的差异:在本帖 walkthrough 的参考实现中,一个“写入并执行”工具将每个脚本添加到上下文的 token 数量减少了约 95%,而按需加载技能则使系统提示词缩小了约 97%。

本系列将这些指南整理为可直接应用的实践。Anthropic 的工程文章与 Strands Agents SDK 中内置的功能相结合,聚焦于上下文工程的四个层面:在架构层面隔离上下文、通过提示词控制上下文、将其外部化到文件系统,以及使用独立智能体和护栏进行验证。在本帖(第 2 部分)中,您将了解每个层面是如何工作的,以及在运行代码中呈现的样子。我们在 Deep Insight 中应用了这些技术,这是一个基于 Strands Agents SDK 和 Amazon Bedrock AgentCore 构建的开源多智能体数据分析解决方案,它作为贯穿全文的参考实现。

帖子系列

第一篇帖子定义了生产环境多智能体系统必须解决的五个核心挑战。它介绍了 Strands Agents SDK、Amazon Bedrock 和 Bedrock AgentCore,以及 AWS Fargate 如何分别解决该问题的不同层面,并提供了代码示例。这篇第二篇帖子展示了建立在该架构之上的上下文工程实践的四个层面,并展示了每个层面的具体实现。第三篇帖子将指导您在 Amazon Virtual Private Cloud (Amazon VPC) 的安全私有网络中部署和操作智能体,涵盖实际运营所需的一切内容。

什么是上下文工程?

上下文工程是一门优化大型语言模型 (LLM) 有限上下文窗口中信息的学科,以使智能体发挥最佳性能。Anthropic Claude Sonnet 4.5 在 Amazon Bedrock 上可用,提供 200K 上下文窗口,但复杂的生产任务会迅速超出该限制。例如,一个看似简单的请求如“分析销售数据并创建 DOCX 报告”会经历几个阶段:数据加载与探索(5 分钟)、基于类别的销售分析(3 分钟)、生成用于时间序列分析的五个图表(10 分钟)、统计验证(3 分钟)以及最终报告生成(5 分钟)。它们在 15 分钟内共消耗超过 150K token。

在单个上下文中处理此类任务会导致问题:窗口在任务中途溢出,过时的上下文会降低性能,错误需要重新运行整个管道。随着上下文的增长,对重要信息的注意力下降,且低效率会在按 token 计费的定价模式下推高成本。

“随着上下文窗口中 token 数量的增加,模型准确回忆该上下文中信息的能力会下降(上下文腐烂)。”

— Anthropic, “Effective Context Engineering for AI Agents” (2025.09)

上下文工程正是为了解决这些问题,而且它不仅仅是一组技术的集合。它涵盖架构设计、提示词编写、工具实现和验证,是一个分层学科,每一层都弥补前一层遗漏的内容。本帖详细介绍了您可以应用的四层方法,以高效管理上下文。

如何处理超出上下文窗口的任务

Anthropic 发布了多种处理长周期任务的技术。Deep Insight 将这些技术分为四个层面,每个层面解决其他层面的局限性。下表列出了这四个层面。

层面

实践

核心原则

局限性

层面 1:架构

通过多智能体架构隔离上下文

每个智能体在独立的上下文中运行

当仅靠隔离不足以解决问题时

层面 2:提示词

输出控制与行为规则

通过提示词限制上下文摄入

当仅靠提示词不足以解决问题时

层面 3:工具

基于文件的上下文外部化

将重型内容保留在上下文之外的文件中

当问题仍然存在时

层面 4:验证智能体与护栏

独立验证与护栏

捕获错误并防止上下文溢出

最后一道防线

接下来的章节按顺序介绍每个层面,说明该层面规定了什么、为什么仅靠前面的层面是不够的,以及该实践在 Deep Insight 中是如何实现的。

1. 通过多智能体架构隔离上下文

为每个专用智能体提供其自己的上下文窗口,并将压缩后的结果传递给协调器。Deep Insight 通过协调员、规划员、计划审查员、主管和工具智能体(编码员、验证员、报告员、跟踪员、审计员)的层次结构来实现这一点。

对于单个智能体而言,所有信息——从用户请求到数据探索、分析、图表生成、验证和报告——都会积累在一个上下文中,很容易超出窗口限制。让每个智能体拥有自己的上下文,即使是最常用的编码员,其总 token 数也保持在 25K 以下。每个智能体只接收其所需的信息,并通过完成通知和简短摘要向其他智能体发出信号。

隔离的关键在于最小化共享信息。Deep Insight 使用一个 Python 字典 shared_state,仅存储四样东西:

  • messages:上一个智能体的最后一条消息(而非完整的对话历史)。
  • clues:从每个智能体收集的压缩摘要。
  • full_plan:由规划员生成并由跟踪员更新的清单。
  • history:智能体名称和消息的简短日志。

线索使用固定的 CLUES_FORMAT:不是传递每个智能体的完整对话(数万 token),而是只传递压缩的核心结果。

# coder_agent_tool.py -- context passing format
CLUES_FORMAT = "Here is clues from {}:\n\n<clues>\n{}\n</clues>\n\n"
RESPONSE_FORMAT = "Response from {}:\n\n<response>\n{}\n</response>\n\n*Please execute the next step.*"

# After Coder completes: add only compressed result to clues
clues += CLUES_FORMAT.format("coder", response["text"])

这种模式是 Anthropic 的 “How We Built Our Multi-Agent Research System” 文章中推荐的做法,该文章描述了一种编排者-工作者模式,其中主智能体委托给专用的子智能体,每个智能体仅在其自己的上下文中工作。您不需要自己构建它:Strands Agents SDK 中的 agents-as-tools 模式在框架层面提供了这种隔离。

2. 通过提示词控制上下文流入

仅靠层面 1 的隔离是不够的:即使拥有独立的上下文,生成冗长响应的智能体也会膨胀主管的上下文。层面 2 通过提示词限制每个智能体的输出。

对于 Deep Insight,我们使用提示词来限制每个智能体返回给主管的信息量。三条规则完成了大部分工作,正如 Deep Insight 的提示词所示。

“从最强的模型和简单的提示词开始。然后根据实际观察到的故障案例逐步添加具体的指令。”

— Anthropic, “Effective Context Engineering for AI Agents” (2025.09)

实现细节 2-1:明确的每智能体输出 token 预算

每个智能体的提示词指定了最大响应 token 数,防止污染主管上下文的冗长响应。

智能体

输出 Token 预算

原因

编码员

1,000–1,500 tokens

分析代码保存到文件中,因此智能体仅返回状态、已完成任务和见解的摘要

验证员

800 tokens

验证结果保存到 citations.json。智能体仅返回摘要

报告员

1,000 tokens

智能体将报告生成为 DOCX 文件,并仅返回结果的摘要

Anthropic 的 “Writing Effective Tools for Agents” 文章建议为工具提供 CONCISE(简洁)或 DETAILED(详细)的响应选项以提高上下文效率。将同样的思路向上应用一级,在每个智能体的系统提示词中。在 Deep Insight 中,所有智能体共享一种标准化格式:

## Status
[SUCCESS | PARTIAL_SUCCESS | ERROR]
## Completed Tasks
- [Task 1 from FULL_PLAN -- use exact wording so Tracker can match]
- [Task 2 -- be specific, not generic]
## Key Insights
- [Key finding 1 with numbers and ratios]
- [Key finding 2 with business implications]
## Generated Files
- ./artifacts/chart.png -- brief description
- ./artifacts/calculation_metadata.json -- N calculations

实现细节 2-2:自包含代码理念

编码员智能体的提示词明确指出“变量在脚本之间不持久存在”。每个脚本都必须包含所有必要的导入并直接加载数据。提示词提供了错误和正确的示例:

# WRONG -- Attempting to use a variable from Turn 1 in Turn 2
# Turn 1:
df = pd.read_csv('data.csv')
total = df['Amount'].sum()

# Turn 2:
print(f"Total: {total}")  # NameError: name 'total' is not defined

# CORRECT -- Every script is self-contained
import pandas as pd
df = pd.read_csv('./artifacts/cache/df_main.csv')  # Load from cache
total = df['Amount'].sum()
print(f"Total: {total}")

这条规则与上下文工程相关的原因是,引用之前脚本中的变量要求智能体“记住”之前的对话,这意味着过去的代码必须保留在上下文中。自包含原则意味着过去的代码可以安全地从上下文中移除。

实现细节 2-3:主管的部分完成规则

主管的提示词中包含规则“在当前智能体部分的所有清单项目标记为 [x] 之前,不要移动到下一个智能体。”我们将此规则表达在提示词中,因为判断编码员的工作是否完成需要主管使用跟踪员的更新信息来解释计划。这种判断很难仅用代码来表达。

3. “上下文中只有指针,实际数据在文件中”

层面 1 隔离了智能体之间的上下文,层面 2 限制了智能体内部的输出。但是当编码员智能体生成 100 行 Python 代码时,这些代码本身就会进入上下文。即使有“简要回复”的提示词指令,有些代码也无法写得简略。层面 3 使用工具设计将重型内容移出上下文,放入文件系统。以下实现细节显示了四种带来大部分收益的技术。

实现细节 3-1:使用写入并执行工具将代码移出上下文

编码员读取分析计划,编写 Python 代码并执行它以生成可视化效果。但是当代码变长时,传统方法(分离的文件写入和执行工具)会将 100 行代码直接添加到上下文中,每个脚本累积超过 1,000 行。

解决方法是将这两个步骤合并为一个工具,这样代码就不会作为消息进入上下文。Deep Insight 的编码员智能体为此使用了一个 write_and_execute_tool。

以下是 w

查看原文

When production AI agents handle tasks such as data analysis and report generation, context management can become a major bottleneck. A 200K-token window sounds generous until a real-world task burns through most of it in minutes. Data analysis and report generation leave the agent failing mid-execution, losing accuracy, or driving up costs. A body of published guidance already addresses this, but the individual techniques are easier to read about than to apply. Applied together, they make a measurable difference: in the reference implementation this post walks through, a single write-and-execute tool cuts the tokens each script adds to context by about 95 percent, and loading skills on demand shrinks the system prompt by about 97 percent.

This series organizes that guidance into practices you can apply directly. Anthropic’s engineering posts, together with features built into the Strands Agents SDK, converge on four layers of context engineering: isolate context at the architecture level, control it through prompts, externalize it to the filesystem, and verify it with independent agents and safeguards. In this post (Part 2), you will learn how each layer works and what it looks like in working code. We applied these techniques in Deep Insight, an open source multi-agent data analysis solution built on the Strands Agents SDK and Amazon Bedrock AgentCore, which serves as the reference implementation throughout.

Post series

The first post defined five core challenges that production multi-agent systems must solve. It introduced how Strands Agents SDK, Amazon Bedrock and Bedrock AgentCore, and AWS Fargate each address different layers of the problem, with code examples. This second post takes the four layers of context engineering practice that sit on top of that architecture and shows each one implemented. The third post guides you through deploying and operating agents in a secure private network on Amazon Virtual Private Cloud (Amazon VPC), covering everything needed for real-world operations.

What is context engineering?

Context engineering is the discipline of optimizing the information in a large language model (LLM)’s limited context window so agents perform at their best. Anthropic Claude Sonnet 4.5, available on Amazon Bedrock, offers a 200K context window, but complex production tasks quickly exceed it. For example, a seemingly straightforward request like “Analyze sales data and create a DOCX report” runs through several stages: data loading and exploration (5 min), category-based sales analysis (3 min), generating five charts for time-series analysis (10 min), statistical validation (3 min), and final report generation (5 min). Together they consume over 150K tokens across 15 minutes.

Processing such tasks in a single context causes problems: the window overflows mid-task, stale context degrades performance, and errors require re-running the whole pipeline. As context grows, attention to important information drops, and inefficiency raises cost under per-token pricing.

“As the number of tokens in the context window increases, the model’s ability to accurately recall information from that context decreases (Context rot).”

— Anthropic, “Effective Context Engineering for AI Agents” (2025.09)

Context engineering solves exactly these problems, and it is not only a collection of techniques. Spanning architecture design, prompt writing, tool implementation, and verification, it’s a layered discipline where each layer compensates for what the previous ones miss. This post details the four-layer approach you can apply to manage context efficiently.

How to handle tasks that exceed the context window

Anthropic has published several techniques for handling long-horizon tasks. Deep Insight groups these techniques into four layers, with each layer addressing the limitations of the others. The following table sets out the four layers.

Layer

Practice

Core Principle

Limitations

Layer 1: Architecture

Isolating Context Through Multi-Agent Architecture

Each agent operates in an independent context

When isolation alone is not enough

Layer 2: Prompt

Output Control and Behavioral Rules

Limiting context intake through prompts

When prompts alone are not enough

Layer 3: Tools

File-based Context Externalization

Keeping heavy content in files outside the context

When issues still arise

Layer 4: Verification Agents and Safeguards

Independent Verification and Safeguards

Catching errors and preventing context overflow

Final line of defense

The sections that follow take each layer in order, stating what the layer prescribes, why the preceding layers alone are insufficient, and how the practice is implemented in Deep Insight.

1. Isolating context through multi-agent architecture

Give each specialized agent its own context window and pass only compressed results to the orchestrator. Deep Insight does this with a hierarchy of Coordinator, Planner, Plan Reviewer, Supervisor, and Tool Agents (Coder, Validator, Reporter, Tracker, Auditor).

With a single agent, all information, from user requests through data exploration, analysis, chart generation, validation, and reporting, accumulates in one context and easily exceeds the window. Giving each agent its own context keeps even the Coder, which uses the most, under 25K tokens total. Each agent receives only what it needs and signals others with a completion notice and brief summary.

The key to isolation is minimizing shared information. Deep Insight uses a Python dictionary, shared_state, that stores only four things:

  • messages: The previous agent’s final message (not the full conversation history).
  • clues: Compressed summaries collected from each agent.
  • full_plan: A checklist generated by Planner and updated by Tracker.
  • history: A brief log of agent names and messages.

The clues use a fixed CLUES_FORMAT: instead of each agent’s full conversation (tens of thousands of tokens), only compressed core results are passed.

# coder_agent_tool.py -- context passing format
CLUES_FORMAT = "Here is clues from {}:\n\n<clues>\n{}\n</clues>\n\n"
RESPONSE_FORMAT = "Response from {}:\n\n<response>\n{}\n</response>\n\n*Please execute the next step.*"

# After Coder completes: add only compressed result to clues
clues += CLUES_FORMAT.format("coder", response["text"])

This pattern is the one recommended in Anthropic’s “How We Built Our Multi-Agent Research System” post, which describes an orchestrator-worker pattern in which a lead agent delegates to specialized subagents, with each agent working only within its own context. You do not need to build it yourself: the agents-as-tools pattern in the Strands Agents SDK provides this isolation at the framework level.

2. Controlling context inflow through prompts

Layer 1 isolation alone is not sufficient: even with independent contexts, an agent that generates long responses inflates the Supervisor’s context. Layer 2 limits each agent’s output through prompts.

For Deep Insight, we use prompts to limit how much information each agent returns to the Supervisor. Three rules do most of the work, as Deep Insight’s prompts show.

“Start with the strongest model and a simple prompt. Then incrementally add specific instructions based on actually observed failure cases.”

— Anthropic, “Effective Context Engineering for AI Agents” (2025.09)

Implementation detail 2-1: Explicit per-agent output token budgets

Each agent’s prompt specifies a maximum response token count, preventing long responses that pollute the Supervisor’s context.

Agent

Output Token Budget

Reason

Coder

1,000–1,500 tokens

Analysis code is saved to files, so the agent returns only a summary of state, completed tasks, and insights

Validator

800 tokens

Validation results are saved to citations.json. The agent returns only a summary

Reporter

1,000 tokens

The agent generates the report as a DOCX file and returns only a summary of the result

Anthropic’s ” Writing Effective Tools for Agents” post suggests giving tools a CONCISE or DETAILED response option for context efficiency. Apply the same idea one level up, in each agent’s system prompt. In Deep Insight, all agents share one standardized format:

## Status
[SUCCESS | PARTIAL_SUCCESS | ERROR]
## Completed Tasks
- [Task 1 from FULL_PLAN -- use exact wording so Tracker can match]
- [Task 2 -- be specific, not generic]
## Key Insights
- [Key finding 1 with numbers and ratios]
- [Key finding 2 with business implications]
## Generated Files
- ./artifacts/chart.png -- brief description
- ./artifacts/calculation_metadata.json -- N calculations

Implementation detail 2-2: Self-contained code philosophy

The Coder agent’s prompt explicitly states “variables do not persist between scripts.” Every script must include all necessary imports and load data directly. The prompt provides both incorrect and correct examples:

# WRONG -- Attempting to use a variable from Turn 1 in Turn 2
# Turn 1:
df = pd.read_csv('data.csv')
total = df['Amount'].sum()

# Turn 2:
print(f"Total: {total}")  # NameError: name 'total' is not defined

# CORRECT -- Every script is self-contained
import pandas as pd
df = pd.read_csv('./artifacts/cache/df_main.csv')  # Load from cache
total = df['Amount'].sum()
print(f"Total: {total}")

The reason this rule relates to context engineering is that referencing variables from previous scripts requires the agent to “remember” prior conversations, which means past code must remain in context. The self-contained principle means past code can be safely removed from context.

Implementation detail 2-3: Supervisor’s section completion rule

The Supervisor’s prompt includes the rule “Do not move to the next agent until all checklist items in the current agent’s section are marked [x].” We express this rule in the prompt because deciding whether the Coder’s work is complete requires the Supervisor to interpret the plan using information from the Tracker’s updates. This judgment is difficult to express in code alone.

3. “Only pointers in context, actual data in files”

Layer 1 isolates context between agents, and Layer 2 limits output within agents. But when the Coder agent generates 100 lines of Python code, that code itself enters the context. Even with “respond briefly” prompt instructions, some code can’t be written briefly. Layer 3 uses tool design to move heavy content outside the context, into the filesystem. Four techniques carry most of the benefit, as the following implementation details show.

Implementation detail 3-1: Moving code outside context with Write and Execute Tool

The Coder reads the analysis plan, writes Python, and executes it to generate visualizations. But when the code gets long, the conventional approach (separate file-write and execute tools) adds 100 lines directly to context per script, accumulating over 1,000 lines.

The fix is to collapse the two steps into a single tool, so the code never enters context as a message. Deep Insight’s Coder agent uses one write_and_execute_tool for this.

Here’s part of the write_and_execute_tool. After writing and executing the file, it returns only a summary: “Wrote 105 lines, execution successful, completed analysis of five categories.” The code stays in the file and about three lines of summary remain in context. Based on this example, that saves about 95 percent of the tokens.

# write_and_execute_tool.py
def _handle_write_and_execute_tool(file_path, content, timeout=300):
    """Write a Python script and immediately execute it."""
    # Step 1: Write file
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    # Step 2: Execute immediately
    result = subprocess.run(
        f"python {file_path}",
        shell=True,
        capture_output=True,
        timeout=timeout
    )
    # Return only summary
    return f"Written {len(content.split(chr(10)))} lines to {file_path}\n" \
        f"Execution successful\n" \
        f"Output: {result.stdout[:500]}"  # Only first 500 chars

“Server-side filtering: filtering data at the execution layer before it reaches context, 98.7% token reduction (150K to 2K).”

— Anthropic, “Code Execution with MCP” (2025.11)

Implementation detail 3-2: Reusing common logic as modules in the Coder agent

Common modules get reused across analyses. Rather than regenerating them each time, define frequently-used functions as a module once and import them, which prevents token waste and context duplication.

Without this, defining functions like to_python_type() or track_calculation() in every analysis produces 200–300 lines of duplicate code across 10 analyses. Deep Insight generates a module called coder_analysis_utils.py before the first task. It includes functions for converting numpy types, tracking calculation metadata, and saving to JSON. Subsequent analyses import it, replacing 20–30 regenerated lines with two import lines, which saves tokens and improves consistency and debugging.

# coder_analysis_utils.py -- common module generated before first task
import numpy as np
import json
from datetime import datetime

_calculations = []

def to_python_type(value):
    """Convert numpy/pandas types to Python native types"""
    if isinstance(value, (np.integer, np.int64)): return int(value)
    elif isinstance(value, (np.floating, np.float64)): return float(value)
    elif isinstance(value, np.ndarray): return value.tolist()
    return value

def track_calculation(calc_id, value, description, formula,
                      source_file, source_columns, importance):
    """Track calculation metadata -- Validator independently verifies later"""
    _calculations.append({
        "id": calc_id, "value": to_python_type(value),
        "description": description, "formula": formula,
        "source_file": source_file, "source_columns": source_columns,
        "importance": importance
    })

def save_calculation_metadata(path="./artifacts/calculation_metadata.json"):
    """Save all tracked calculations to JSON"""
    with open(path, 'w', encoding='utf-8') as f:
        json.dump({"generated_at": datetime.now().isoformat(),
                   "calculations": _calculations}, f, ensure_ascii=False, indent=2)

Implementation detail 3-3: Saving and sharing analysis results through structured note-taking

We use structured note-taking to share detailed analysis results without passing them through each agent’s context. Deep Insight stores these results in a file called all_results.txt, which is then read by agents as needed.

For example, the Coder agent appends results to all_results.txt after each analysis task:

with open('./artifacts/all_results.txt', 'a', encoding='utf-8') as f:
    f.write(f"""
## Category Sales Analysis (completed at: 14:32)
- Top revenue category: Fruit (417,166,008 KRW, 45% of total)
- Top 3 categories: Fruit, Vegetables, Meat (78% of total)
- Generated file: ./artifacts/category_sales_chart.png
""")

The Coder records detailed results in this file after each analysis, and the Reporter reads it when writing the final report. Other agents collaborate through all_results.txt the same way.

Without note-taking, the Coder passes detailed results to the Supervisor after every task, accumulating in its context. With note-taking, only an approximately 30-token message like “Category sales analysis complete, 3 key insights found, detailed results saved to all_results.txt” is passed, and the Reporter reads the file when needed.

The pattern generalizes beyond a single file. The filesystem itself can serve as the inter-agent communication bus, as it does in Deep Insight:

File name

Producer

Consumer

Role

all_results.txt

Coder

Reporter

Cumulative log of analysis results

calculation_metadata.json

Coder

Validator

Record of numeric calculations: sources, formulas, and values (for verification)

citations.json

Validator

Reporter

Verified citation data (inserted as [1], [2] in the report)

audit_findings.json

Auditor

Reporter

Citation defects found in the final report (drives targeted Reporter retries)

coder_analysis_utils.py

Coder

All scripts

Shared utility functions (write once, import repeatedly)

full_plan (shared_state)

Planner/Tracker

Supervisor

Checklist status (updating [x])

“The”just in time” approach, dynamically loading data into context at runtime rather than pre-processing all relevant data up front, keeps context fresh, relevant, and adaptive to the evolving state of the task.”

— Anthropic, “Effective Context Engineering for AI Agents” (2025.09)

Implementation detail 3-4: Loading only needed knowledge with Skills

Rather than putting all specialized knowledge into the system prompt, this approach loads it only when needed. Including every skill guide (data structure checking, README generation, skill creation, system prompt writing, tool creation) would add over 20K tokens, load unnecessary information into the Coder agent on every call, and force a redeploy to add a skill.

Deep Insight’s Skills system loads only a skill catalog of about 500 tokens at startup, with the skill list holding only names and brief descriptions. When a user requests “Create a README file,” the agent decides “I need the readme-generator skill” and calls skill_tool(skill_name="readme-generator"). The SkillLoader reads readme-generator/SKILL.md and returns a detailed guide of about 3K tokens.

# 1. Skill Discovery (at initialization)
from src.utils.skills.skill_utils import initialize_skills
available_skills, skill_prompt = initialize_skills(
    skill_dirs=["./skills"],
    verbose=True
)

# 2. Add to System Prompt (~500-token catalog)
system_prompt = base_prompt + skill_prompt

# 3. Runtime -- Agent loads skill when needed
# Agent decides: "This is README generation, I need the readme-generator skill"
# -> skill_tool(skill_name="readme-generator")
# -> Returns full SKILL.md content (~3K tokens)

Each skill is defined as a SKILL.md file composed of YAML frontmatter and detailed markdown guide. It includes metadata like name, description, license, and allowed-tools, along with Overview, When to Use This Skill, detailed instructions, and Best Practices. To add a new skill, create a new directory under skills/ and write a SKILL.md file, and it is automatically discovered.

At startup, the agent loads a skill catalog of about 500 tokens instead of wasting over 20,000 tokens on full guides (about 97 percent less). When needed, it can load an additional few thousand tokens’ worth of detailed instructions for skills.

4. Verifying quality with verification agents and safeguards

Even with Layers 1–3, one risk remains: isolated agents can’t see each other’s work, so if the Coder miscalculates, the Reporter carries that error into the report. Layer 4 is the final line of defense.

“Provide testing tools so the agent can self-verify features and fix bugs that aren’t obvious from the code alone. Have the model commit its progress to git with descriptive commit messages and write progress summaries in a progress file.”

— Anthropic, “Effective Harnesses for Long-Running Agents” (2025.11)

Implementation detail 4-1: Tracker, Validator, and Auditor agents: progress tracking and quality assurance

Tracker updates the plan’s checklist in real time. When the Coder completes data loading, the Supervisor calls Tracker, which updates the plan item from [ ] to [x] based on information like “Data load complete (1,000 rows, 5 columns).” This helps both users and the system know exactly where progress stands.

Validator independently re-executes the Coder’s calculations to verify accuracy. It reads calculation_metadata.json, re-performs each calculation from source data, and compares: matches within 0.01 pass, mismatches are flagged. Verified calculations go to citations.json for the Reporter to cite. After the Reporter finishes, the Auditor checks the final DOCX against citations.json and calculation_metadata.json without modifying them. It records citation defects in audit_findings.json and can request up to two targeted retries from the Reporter.

Implementation detail 4-2: Prioritizing calculations for verification

Verifying every calculation is inefficient, so scope the verification by importance. Deep Insight’s OptimizedValidator applies the following thresholds:

  • Over 50 calculations: aggressive filtering, verify all high plus only 10 medium.
  • Over 20 calculations: moderate filtering, verify all high plus 15 medium.
  • 20 or fewer calculations: verify most, all high plus all medium plus 5 low.

It also applies type-safe comparison: to avoid numpy-versus-Python type issues, all values are converted to float() and checked for an absolute difference under 0.01:

# validator.md -- type-safe numerical comparison
try:
    match = abs(float(expected) - float(actual)) < 0.01
except:
    match = str(expected) == str(actual)

Implementation detail 4-3: SummarizingConversationManager: the last safety net

Context can still overflow in exceptional cases, so keep a safety net under the other layers. Deep Insight uses the SummarizingConversationManager in the Strands Agents SDK for this.

# strands_sdk_utils.py -- safety net configuration at agent creation
agent = Agent(
    model=llm,
    system_prompt=system_prompts,
    tools=tools,
    conversation_manager=SummarizingConversationManager(
        summary_ratio=0.5,  # summarize oldest 50% on overflow
        preserve_recent_messages=10,  # always preserve 10 most recent messages
        summarization_system_prompt=apply_prompt_template("summarization", {})
    )
)

On overflow, the LLM summarizes the oldest 50 percent of messages into one, while always preserving the 10 most recent to keep the current task’s context. The summarization prompt (summarization.md) requires clues, plans, and tracking status to be preserved verbatim.

Implementation detail 4-4: Selective prompt caching for cost optimization

Context engineering covers cost optimization, not only token savings. Enable prompt caching per agent, based on how often each is called with the same prompt. Deep Insight’s per-agent settings:

Agent

Prompt Cache

Tool Cache

Reason

Supervisor

Yes

Yes

High frequency of repeated calls, with a large system prompt and tool definitions

Coder

Yes

Yes

Running multiple analysis scripts sequentially, with the same prompt each time

Reporter

Yes

Yes

Generating a report incrementally section by section, with high prompt-reuse frequency

Auditor

Yes

Yes

Inspects the DOCX and JSON files over many turns with the same prompt and tools, and reruns after each Reporter retry

Coordinator

No

No

A single one-off call, no caching benefit

Planner

No

No

Called once per request, and again only when the user requests a plan revision

Validator

No

No

Called with different data each time, low cache hit rate

Tracker

No

No

Lightweight task, no tools, caching unnecessary

Agents with caching enabled insert cache points into system prompts and tool definitions, reducing input token costs by up to 90 percent on repeated calls. This is a feature natively supported by the Strands Agents SDK. Plan Reviewer does not appear in the table because it’s a human-in-the-loop step that collects user approval or feedback rather than calling a model.

Conclusion

This post has detailed the four-layer engineering approach you can use to efficiently manage context for complex tasks that exceed the context window.

  • Layer 1 (architecture-level isolation): Each agent works in an independent context through multi-agent architecture, passing only compressed summaries.
  • Layer 2 (prompt-based control): Output token budgets, standardized response formats, and self-contained code philosophy actively limit context inflow.
  • Layer 3 (filesystem use): write_and_execute_tool keeps code outside context, the filesystem serves as an inter-agent communication bus, and knowledge is lazy-loaded only when needed.
  • Layer 4 (verification and safeguards): Validator’s independent calculation re-verification, Auditor’s read-only citation audit of the final report, Tracker’s progress tracking, SummarizingConversationManager’s overflow prevention, and selective prompt caching manage both quality and cost.

Each layer forms a defense system that compensates for what the preceding layers miss. When architecture isolation is insufficient, prompts limit output. When prompts are insufficient, tools keep content external. And when problems still arise, verification catches them.

Each of these layers is documented in Anthropic’s engineering posts, “Effective Context Engineering for AI Agents”, “Code Execution with MCP”, and “How We Built Our Multi-Agent Research System”. Much of what they recommend already ships in the Strands Agents SDK rather than being something you build: SummarizingConversationManager, prompt caching, and the agents-as-tools pattern.

When building production agents, the LLM’s context window alone is rarely enough. Apply these context engineering techniques to manage context efficiently and scale your agents for production workloads.

Deep Insight, the reference implementation used here, is open source. Review the code and extend it for your domain.


About the authors

原文版权归 AWS Machine Learning 及原作者所有,本站转载仅供阅读。如需删除,请联系 support@aisa.one。