06
6 / 50

Context Fundamentals

⏱️ 30分钟

Context Engineering 管理模型在每一次 inference 中真正能看到什么。它不等于“写更长的 Prompt”,而是从所有候选信息中选择、组装、验证并维护一组获授权、高信号、可追溯的输入。

从 Prompt 到 Context

Candidate sources
  ├─ instructions
  ├─ user input
  ├─ identity + permissions
  ├─ runtime state + history
  ├─ retrieved knowledge
  ├─ examples
  ├─ tool definitions + results
  └─ memory references
          ↓ selection policy
          ↓ assembly + token budget
          ↓ validation + trust boundary
       Model context
          ↓ output + trace
          ↓ refresh / compact / evict

Prompt Engineering 主要设计 instructions 和 task contract;Context Engineering 还负责信息来源、权限、新鲜度、选择规则、顺序、预算和生命周期。

1. Context Inventory

先登记候选来源,而不是先把所有内容塞进窗口:

SourceOwnerTrustFreshnessPermissionPurpose
System instructionsAI Platformtrusted/configversionedapplication定义行为边界
Current user inputuseruntrustedcurrentrequest scope提供任务
Resident/shift stateapplication DBtrusted after authruntimetenant + role提供业务状态
Policy documentscompliance ownersource-dependenteffective dateapproved corpus提供政策依据
Tool resulttool owneruntrusted until validatedruntimetool scope提供环境反馈
Long-term memoryuser/systemmixedmutablesubject + purpose跨请求偏好/事实

trusted 不等于 relevantrelevant 不等于 permitted。三个条件必须分别判断。

2. Selection Policy

每种 task type 都需要明确 include、exclude、priority 和 missing-data 行为:

task: draft_progress_note
include:
    - confirmed_transcript
    - resident_id
    - shift_id
exclude:
    - unconfirmed_transcript
    - unrelated_resident_history
rules:
    permission: same_tenant_and_assigned_role
    freshness: current_shift
    conflict: stop_and_request_review
    missing_required: invalid_input

Selection 的结果应能解释“为什么选了这条,为什么排除那条”,不能只有最终拼接字符串。

3. Authority、Trust 与 Prompt Injection

用户输入、retrieved document、网页内容和 tool output 都可能包含看起来像指令的文字。它们是 data,不会因为出现在 Context 里自动获得 system authority。

System / developer policy
        ↓
Application task contract
        ↓
Authorized runtime facts
        ↓
Untrusted user/docs/tool content

真实系统还要在应用层做权限、schema 和 side-effect 校验。Prompt 中写“忽略恶意指令”不是完整防御。

4. Assembly Plan

Assembly 决定 selected context 怎样进入请求:

  • 将稳定规则、动态任务和外部资料分区;
  • 保留 source IDs、effective dates 与 provenance;
  • 对重复、矛盾和过期内容做显式处理;
  • 为输出、tool calls 和 provider overhead 预留预算;
  • 把完整 schema 交给 Structured Outputs,而不是重复写进自然语言;
  • 保持可缓存的稳定前缀与动态内容边界清楚。

Token Budget 示例

BucketBudget policyOverflow action
Instructions必需、版本化冲突则 fail
Current task必需缺字段则 ask/fail
Retrieved evidence按 relevance/authority减少 top-k 或重新检索
History只保留任务相关状态summarize/compact
Tool definitions只加载可用工具progressive disclosure
Output reserve预留缩减输入,不挤掉输出

预算不是固定百分比。它取决于 task、model、tool surface 和 output contract,必须用实际 usage 与 evals 调整。

5. Progressive Disclosure

Progressive disclosure 的目标是“需要时再加载”:

  1. 首先只暴露目录、摘要、IDs 或 tool names。
  2. 模型/应用根据任务选择相关对象。
  3. 再加载必要正文、记录或 tool schema。
  4. 使用后保留结构化结果,清理大体积原始输出。

它适合大型代码库、政策资料、工具目录和长任务,但也会增加检索/工具轮次。是否采用要比较质量、延迟和失败率。

6. Context Lifecycle

Context 不是一次拼完就永久正确:

discover → select → assemble → validate → use
    ↑                                      ↓
 refresh ← invalidate ← compact ← observe

Refresh

政策 effective date、用户权限、任务状态变化后重新读取,不沿用旧 snapshot。

Compaction

把已完成动作、关键决策、IDs、失败结果和下一目标压缩成结构化摘要。触发条件来自实际窗口压力、任务阶段和质量回归,不设通用固定百分比。

Eviction

清除已完成步骤的冗长 tool output、重复日志和无关对话,但保留审计所需的外部 trace/source ID。

Invalidation

当权限撤销、文档更新或状态改变时,让旧 Context 失效;prompt cache 命中不能绕过 freshness 检查。

7. Context、RAG、Memory 与 Cache 的区别

机制作用关键风险
Context Engineering决定本次调用看到什么选错、冲突、越权、过期
RAG从知识源检索证据retrieval miss、错误 citation
Memory跨请求保留可复用状态/事实poisoning、错误归属、无法更正
Prompt Cache复用重复前缀计算stale prefix、数据隔离
KV Cache复用模型生成内部状态显存与并发压力

RAG、Memory 和工具都只是 Context 的候选来源或机制,不等于 Context Engineering 本身。

8. Context Trace

每次 assembly 至少记录:

{
	"context_version": "ctx-2026-09-08-03",
	"task_type": "draft_progress_note",
	"selected_sources": ["transcript:T-17", "shift:S-09"],
	"excluded_sources": [{ "id": "note:N-02", "reason": "unconfirmed" }],
	"permission_decision": "allow",
	"freshness_checked_at": "runtime",
	"input_tokens": null,
	"validation": "pending"
}

实际 token 和状态由运行时填写;未知数据不能写成 0,生产模板使用 null 或未设置字段。

9. 三个诊断案例

条件被忽略

先检查条件是否真的被选入、是否冲突、是否被长历史淹没,再考虑重写 Prompt。

答案引用过期政策

检查 effective date、corpus version、retrieval filter 与 context trace;扩大 context window 不能修复数据新鲜度。

Agent 调错工具

检查 tool inventory、description 重叠、权限和动态加载策略;不要只在 system prompt 里再加一句“谨慎选择”。

10. 实践:Context Architecture Blueprint

为 Structured Documentation、Policy RAG 和 Agent Tool Use 三个场景各完成:

  1. Context Inventory;
  2. source owner / trust / permission / freshness;
  3. include/exclude/priority/conflict rules;
  4. assembly order 与 token budget;
  5. validation、trace、refresh、compaction、eviction;
  6. 一条正常 case、一条冲突 case、一条 prompt-injection case。

完成标准

  • Blueprint 不只是 Prompt 文本,而是 source → policy → assembly → validation → lifecycle。
  • 每个 source 都有 owner、trust、freshness、permission 和 purpose。
  • selected 与 excluded 都留下原因。
  • Context 缺失、冲突、过期或越权时有明确行为。
  • Token budget 为 output 留空间,并通过真实 usage 验证。
  • 能区分 Context、RAG、Memory、Prompt Cache 和 KV Cache。
  • 三个场景共享同一方法,但拥有不同 selection policy。

官方参考

📚 相关资源

常见问题

点击问题,查看本章对应的实践答案。

Context 和 Prompt 是一个东西吗?

不是。Context 是模型推理时能看到的完整输入状态:system instructions、tool definitions、retrieved documents、message history、tool outputs 五块。Prompt 只是其中一小块。Context Engineering 调的是这 5 块怎么组装、谁放头谁放尾、按需加载多少,不只是 user 那一行字。

为什么 context 越长效果反而越差?

Attention budget 有限——transformer 注意力是 n² 量级,context 越长每个 token 分到的注意力越薄。模型训练时短序列见得多,超长 context 下远距离依赖建模能力会下降,叫 attention budget depletion。Prefix caching 也消除不了长输入成本。目标是「最小高信号 token 集合」,不是「最大长度」。

tool outputs 真的会吃掉这么多 context 吗?

会。研究数据显示 tool outputs 可占 context tokens 的 83.9%,远超 system prompt 和 user message。无论相关与否,模型都得 attend。这就是为什么需要 observation masking(用紧凑 reference 替换冗长 output)、compaction(达 70-80% 时压缩)、selective retention(只留关键字段)。

progressive disclosure 是什么?怎么用?

按需加载:启动只加载 skill names + descriptions,任务真正需要时再加载全文。filesystem-based 的 agent 天然适合——把资料放文件系统里,文件大小、命名、时间戳本身就是 relevance 信号。生产里通常 hybrid:少量稳定 context(如 CLAUDE.md / 项目规则)预加载 + 其它按需探索。

system prompt 放哪?要拆几块?

拆成 4 块:BACKGROUND(项目上下文)、INSTRUCTIONS(行为规则)、TOOL_GUIDANCE(工具用法)、OUTPUT_DESCRIPTION(输出格式)。用 XML 标签或 Markdown headers 分区。「高度」要平衡:太硬编码脆弱难维护,太抽象缺执行信号。模型越强,格式影响越小,但结构清晰仍能防漂移。