提示词工程演进:从 Prompt 到 Context 到 Harness Engineering
"2026 年,AI 项目失败的 40% 原因不是提示词写得不好,而是上下文管理不当。"
1. 演进概览
1.1 三个阶段的本质区别
| 阶段 | 核心关注 | 类比 | 适用场景 |
|---|---|---|---|
| Prompt Engineering | 如何问问题 | 给马下口令 | ChatGPT 对话、简单任务 |
| Context Engineering | 提供什么信息 | 给马看地图和路标 | Agent 系统、RAG 应用 |
| Harness Engineering | 如何约束和引导 | 设计马具、缰绳和护栏 | 企业级 AI、多 Agent 协作 |
1.2 为什么需要演进?
javascript
// ❌ Prompt Engineering 时代
const result = await llm.chat("帮我分析这段代码的性能问题");
// 问题:没有代码上下文、项目背景、性能基线、输出格式不可控
// ✅ Context Engineering 时代
const result = await llm.chat({
systemPrompt: "你是性能优化专家...",
context: {
code: readFile('component.tsx'),
dependencies: readFile('package.json'),
metrics: getPerformanceMetrics()
},
tools: [analyzeBundle, profileRuntime]
});
// ✅ Harness Engineering 时代
const result = await agent.run({
task: "分析性能问题",
harness: {
context: contextManager,
memory: memorySystem,
tools: toolRegistry,
guardrails: securityPolicy,
governance: auditLogger
}
});2. Prompt Engineering (2022-2024)
2.1 核心技术
关注点: 如何写出好的提示词
markdown
1. Role Prompting: "你是一个资深前端工程师..."
2. Few-shot Learning: 提供 2-3 个示例
3. Chain-of-Thought: "让我们一步步思考..."
4. Structured Output: "以 JSON 格式输出..."2.2 局限性
javascript
// 问题 1: 上下文丢失
const chat1 = await llm.chat("分析这个组件");
const chat2 = await llm.chat("优化它"); // "它"是什么?
// 问题 2: 无法扩展
const prompt = `分析以下 100 个文件...`; // 超出上下文窗口
// 问题 3: 不可复用
// 每次都要重写提示词3. Context Engineering (2024-2025)
3.1 核心思想
从"写好提示词"到"设计信息环境"
typescript
interface ContextManager {
// 1. 上下文收集
collect(): Context;
// 2. 上下文过滤
filter(context: Context, query: string): Context;
// 3. 上下文注入
inject(context: Context): string;
// 4. 上下文更新
update(newInfo: any): void;
}3.2 实现示例
typescript
class CodebaseContext {
async buildContext(query: string) {
// 1. 收集相关文件
const relevantFiles = await this.searchFiles(query);
// 2. 提取依赖关系
const dependencies = await this.analyzeDependencies(relevantFiles);
// 3. 获取最近修改
const recentChanges = await this.getGitHistory(relevantFiles);
// 4. 构建上下文
return {
files: relevantFiles.map(f => ({
path: f.path,
content: f.content,
summary: this.summarize(f.content)
})),
dependencies,
recentChanges
};
}
async searchFiles(query: string) {
// 语义搜索
const embedding = await getEmbedding(query);
return await this.vectorDB.search(embedding, 5);
}
}3.3 上下文优化技术
1. 分层上下文
typescript
const context = {
// Layer 1: 始终包含
core: {
projectInfo: readFile('package.json'),
userPreferences: loadUserSettings()
},
// Layer 2: 按需加载
relevant: await searchRelevantFiles(query),
// Layer 3: 动态生成
runtime: {
currentFile: editor.activeFile,
selection: editor.selection
}
};2. 上下文压缩
typescript
async function compressContext(context: string) {
// 方法 1: 摘要
const summary = await llm.summarize(context);
// 方法 2: 提取关键信息
const keyInfo = extractKeyInfo(context);
// 方法 3: 向量化存储
const embedding = await getEmbedding(context);
await vectorDB.store(embedding, context);
return summary;
}3. 上下文缓存
typescript
class ContextCache {
private cache = new Map<string, { context: Context; timestamp: number }>();
async get(key: string) {
const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < 5 * 60 * 1000) {
return cached.context;
}
return null;
}
set(key: string, context: Context) {
this.cache.set(key, { context, timestamp: Date.now() });
}
}4. Harness Engineering (2025-2026)
4.1 核心概念
Harness = 上下文管理 + 工具治理 + 安全护栏 + 可观测性
typescript
interface AgentHarness {
// 1. 上下文管理
contextManager: ContextManager;
// 2. 工具治理
toolRegistry: ToolRegistry;
toolPolicy: ToolPolicy;
// 3. 安全护栏
guardrails: Guardrails;
validator: InputValidator;
// 4. 可观测性
logger: Logger;
metrics: MetricsCollector;
// 5. 记忆系统
memory: MemorySystem;
}4.2 实现 Harness
typescript
class ProductionAgentHarness {
constructor(
private contextManager: ContextManager,
private toolRegistry: ToolRegistry,
private guardrails: Guardrails,
private logger: Logger
) {}
async execute(task: string) {
// 1. 收集上下文
const context = await this.contextManager.buildContext(task);
// 2. 验证输入
await this.guardrails.validateInput(task);
// 3. 执行任务
const result = await this.runAgent(task, context);
// 4. 验证输出
await this.guardrails.validateOutput(result);
// 5. 记录日志
await this.logger.log({ task, context, result });
return result;
}
private async runAgent(task: string, context: Context) {
const response = await this.llm.chat({
messages: [
{ role: 'system', content: this.buildSystemPrompt(context) },
{ role: 'user', content: task }
],
tools: await this.toolRegistry.getRelevantTools(task)
});
return response;
}
}4.3 安全护栏
typescript
class Guardrails {
async validateInput(input: string) {
// 1. 内容审核
if (await this.containsMalicious(input)) {
throw new Error('Malicious input detected');
}
// 2. 长度限制
if (input.length > 10000) {
throw new Error('Input too long');
}
// 3. 敏感信息检测
if (this.containsPII(input)) {
throw new Error('PII detected in input');
}
}
async validateOutput(output: string) {
// 1. 敏感信息过滤
output = this.redactPII(output);
// 2. 有害内容检测
if (await this.containsHarmful(output)) {
throw new Error('Harmful content in output');
}
return output;
}
private containsPII(text: string): boolean {
const patterns = [
/\b\d{3}-\d{2}-\d{4}\b/, // SSN
/\b\d{16}\b/, // Credit card
/\b[\w.-]+@[\w.-]+\.\w+\b/ // Email
];
return patterns.some(p => p.test(text));
}
}4.4 工具治理
typescript
class ToolGovernance {
private allowedTools: Set<string>;
private toolUsageLog: ToolUsageLog[];
async validateToolCall(toolName: string, args: any) {
// 1. 权限检查
if (!this.allowedTools.has(toolName)) {
throw new Error(`Tool ${toolName} not allowed`);
}
// 2. 参数验证
await this.validateArgs(toolName, args);
// 3. 速率限制
if (await this.exceedsRateLimit(toolName)) {
throw new Error('Rate limit exceeded');
}
// 4. 记录使用
this.toolUsageLog.push({
tool: toolName,
args,
timestamp: Date.now()
});
}
}5. 实战案例
5.1 代码审查 Agent
typescript
class CodeReviewAgent {
private harness: ProductionAgentHarness;
async review(pr: PullRequest) {
return await this.harness.execute({
task: `Review PR #${pr.number}`,
context: {
files: pr.changedFiles,
diff: pr.diff,
description: pr.description,
guidelines: loadCodingGuidelines()
},
tools: ['read_file', 'run_linter', 'run_tests'],
guardrails: {
maxFilesPerReview: 20,
requireTests: true,
blockSecurityIssues: true
}
});
}
}5.2 多 Agent 协作
typescript
class MultiAgentSystem {
async collaborate(task: string) {
const sharedContext = new SharedContextManager();
const scheduler = new TaskScheduler();
const governance = new CentralizedGovernance();
const agents = [
new ResearchAgent(sharedContext),
new CodingAgent(sharedContext),
new ReviewAgent(sharedContext)
];
return await scheduler.orchestrate(agents, task, governance);
}
}6. 关键要点
- Prompt Engineering 是基础,适合简单对话和原型
- Context Engineering 是核心,适合大多数 AI 应用
- Harness Engineering 是保障,适合企业级和生产环境
- 三者不是替代关系,而是层层递进
- 根据项目需求渐进式采用,不要过度设计