Skip to content

Context Engineering:超越Prompt Engineering

什么是Context Engineering?

Context engineering是简单prompt engineering的进化。正如Andrej Karpathy所定义的,它是**"在context window中填入恰当信息的精妙艺术与科学"**。

核心定义:

来自Manus团队:

Context engineering让我们能够在几小时而不是几周内发布改进,保持我们的产品与底层模型正交:如果模型进步是涨潮,我们希望成为船,而不是固定在海床上的柱子。

来自LangChain:

Context engineering是构建动态系统,以正确的格式提供正确的信息和工具,使LLM能够合理地完成任务。

来自Tobi Lutke(Shopify CEO):

为任务提供所有context的艺术,使LLM能够合理地解决问题。

Context Engineering vs Prompt Engineering

Prompt Engineering  │  Context Engineering
       ↓            │            ↓                      
   "你说什么"        │    "模型看到的其他一切"
  (单一指令)         │   (示例、记忆、检索、
                    │    工具、状态、控制流)

Context Engineering的核心组件

1. 系统架构设计

  • 从多个来源动态组装context
  • 来自开发者、用户、之前交互、工具调用、外部数据的context
  • 基于任务需求的实时context适配

2. 信息管理

  • 正确的信息:确保LLM拥有必要的context(垃圾进,垃圾出)
  • 正确的工具:提供适当的工具进行信息查找和执行操作
  • 正确的格式:优化信息呈现给LLM的方式

3. Context优化原则

  • Token预算管理:优化每个token的成本和性能
  • KV-Cache优化:最大化缓存命中率以获得更好的延迟和成本
  • Context修剪:移除无关信息同时保留必要context

Context Engineering模板和模式

模板1:KV-Cache优化模式

yaml
# 稳定前缀模板
system_prompt:
  role: "你是一个专家助手"
  guidelines: |
    - 保持一致的格式
    - 避免在前缀中使用时间戳
    - 使用确定性序列化
  
context_management:
  - append_only: true
  - stable_prefix: true
  - cache_breakpoints: ["system_end", "tools_end"]

模板2:工具掩码模式

python
# 不是移除工具,而是掩码它们
class ContextAwareAgent:
    def __init__(self):
        self.all_tools = ["browser_search", "browser_click", "shell_run", "file_write"]
        self.state_machine = StateMachine()
    
    def get_available_tools(self, context_state):
        if context_state == "user_input":
            return []  # 必须回复,不使用工具
        elif context_state == "web_research":
            return [tool for tool in self.all_tools if tool.startswith("browser_")]
        elif context_state == "file_operations":
            return [tool for tool in self.all_tools if tool.startswith("file_")]

模板3:文件系统作为Context模式

yaml
# 将文件系统视为无限context
context_strategy:
  primary_context: "working_memory"  # 有限的context window
  extended_context: "file_system"   # 无限持久存储
  
compression_rules:
  - web_content: "drop_content_keep_url"
  - documents: "drop_content_keep_path"
  - observations: "summarize_and_store"
  
restoration_strategy:
  - restorable: true
  - on_demand_loading: true

模板4:注意力操控模式

markdown
# Todo列表背诵模式
## 当前任务:[任务名称]

### 进度跟踪器 (todo.md)
- [x] 步骤1:初始分析完成
- [x] 步骤2:数据收集完成  
- [ ] 步骤3:处理数据(进行中)
- [ ] 步骤4:生成报告
- [ ] 步骤5:审查和最终确定

### 关键目标(背诵)
1. 主要目标:[主要目标]
2. 成功标准:[标准]
3. 当前重点:[当前步骤]

模板5:错误保留模式

python
# 在context中保留错误以供学习
class ErrorAwareContext:
    def __init__(self):
        self.preserve_errors = True
        self.error_history = []
    
    def handle_action_result(self, action, result):
        if result.is_error:
            # 不清理 - 保留用于学习
            error_context = {
                "action": action,
                "error": result.error,
                "timestamp": result.timestamp,
                "context_state": self.get_current_state()
            }
            self.error_history.append(error_context)
            return f"操作失败:{result.error}\n之前的context已保留用于学习。"
        return result.success_message

模板6:Cognitive Tools模式

yaml
# 结构化推理工具作为函数调用
cognitive_tools:
  understanding:
    name: "understand_problem"
    description: "分解和理解核心问题"
    template: |
      1. 识别主要概念
      2. 提取相关信息
      3. 突出关键约束
      4. 映射到已知模式
  
  reasoning:
    name: "apply_reasoning"
    description: "应用逻辑推理步骤"
    template: |
      1. 生成假设
      2. 针对约束进行测试
      3. 排除无效选项
      4. 验证解决路径
  
  verification:
    name: "verify_solution"
    description: "检查和验证解决方案"
    template: |
      1. 审查解决步骤
      2. 对照原始问题检查
      3. 识别潜在问题
      4. 确认正确性

模板7:多Agent Context编排

yaml
# 多agent系统的context engineering
agent_context_template:
  search_planner:
    system_prompt: |
      你是搜索规划专家。
      生成全面的搜索策略。
    
    context_components:
      - current_datetime: "{{current_time}}"
      - user_query: "{{delimited_query}}"
      - output_format: "structured_json"
      - examples: "{{few_shot_examples}}"
      
  researcher:
    system_prompt: |
      你是研究执行专家。
      执行搜索计划并收集信息。
    
    context_components:
      - search_plan: "{{from_planner}}"
      - available_tools: ["web_search", "document_retrieval"]
      - output_format: "structured_findings"

模板8:动态Context组装

python
# 动态context engineering系统
class ContextEngineer:
    def __init__(self):
        self.context_sources = {
            "system": self.get_system_context,
            "user": self.get_user_context,
            "memory": self.get_memory_context,
            "tools": self.get_tool_context,
            "retrieval": self.get_retrieval_context
        }
    
    def engineer_context(self, task, user_input, state):
        context_parts = []
        
        # 始终包含系统context
        context_parts.append(self.context_sources["system"](task))
        
        # 添加格式正确的用户context
        context_parts.append(f"<user_input>\n{user_input}\n</user_input>")
        
        # 根据任务需求有条件地添加其他context
        if task.requires_memory:
            context_parts.append(self.context_sources["memory"](state))
        
        if task.requires_tools:
            context_parts.append(self.context_sources["tools"](task.tool_requirements))
        
        if task.requires_knowledge:
            context_parts.append(self.context_sources["retrieval"](user_input))
        
        return "\n\n".join(context_parts)

Context Engineering最佳实践

1. 围绕KV-Cache设计

  • 保持prompt前缀稳定
  • 使context只追加
  • 明确标记缓存断点
  • 使用一致的序列化

2. 信息架构

  • 提供完整的context(LLM无法读心)
  • 清晰简洁地格式化信息
  • 一致地构建输入和输出
  • 使用分隔符和清晰的格式

3. 工具和内存管理

  • 掩码工具而不是移除它们
  • 使用文件系统作为扩展context
  • 实施可恢复的压缩策略
  • 在交互中维护context持久性

4. 错误和学习集成

  • 保留错误用于学习
  • 避免过度清理context轨迹
  • 在context中包含失败示例
  • 启用错误恢复模式

5. 注意力和焦点管理

  • 使用背诵来维持焦点
  • 实施todo列表模式
  • 避免统一的context(增加多样性)
  • 打破重复模式

评估和优化

关键指标:

  • KV-cache命中率:生产agent最重要的指标
  • Token效率:每次成功任务完成的成本
  • Context相关性:信息效用评分
  • 任务成功率:整体系统有效性
  • 延迟:首个token时间和总响应时间

优化过程:

  1. 测量基线性能跨所有指标
  2. 识别瓶颈在context组装和处理中
  3. 应用针对性优化使用上述模板
  4. A/B测试变更使用适当的评估框架
  5. 基于数据迭代而不是直觉

未来方向

Context engineering正在向以下方向发展:

  • 自动化context优化使用ML技术
  • Context压缩不丢失信息
  • 多模态context engineering用于视觉和音频
  • Context安全性和安全考虑
  • 实时context适配基于性能反馈

该领域代表了从简单提示到AI系统复杂信息架构的转变,需要技术技能和创造性问题解决能力。

基于 MIT 许可证发布