📌 定义
Agent Self-Correction(智能体自我修正)是指AI Agent在执行任务过程中,能够自动检测错误、分析原因、调整策略并重新执行的能力。它通过内部反思机制或外部反馈机制,实现从"失败→分析→修正→成功"的闭环迭代,显著提升任务完成率和输出质量。
🎭 为什么自我修正如此重要?
没有自我修正的Agent vs 有自我修正的Agent
| 场景 | 无修正 | 有修正 |
|---|---|---|
| 代码生成语法错误 | 报错停止 | 读取错误→修改→重试 |
| 搜索结果不相关 | 返回错误内容 | 分析→改关键词→重搜 |
| JSON解析失败 | 任务中断 | 修复JSON→继续 |
| API超时 | 直接报错 | 切换策略→降级处理 |
| 任务成功率 | ~60% | ~90% |
🛠️ 自我修正的三层机制
第一层:错误检测(Error Detection)
// 错误检测模块
function detectError(result, expectedFormat) {
// 类型检查
if (expectedFormat.type && typeof result !== expectedFormat.type) {
return { error: 'TYPE_MISMATCH', expected: expectedFormat.type, actual: typeof result };
}
// 格式检查(如JSON)
if (expectedFormat.isJSON) {
try { JSON.parse(result); }
catch(e) { return { error: 'JSON_PARSE_ERROR', message: e.message }; }
}
// 内容检查
if (expectedFormat.requiredFields) {
const missing = expectedFormat.requiredFields.filter(f => !result[f]);
if (missing.length) return { error: 'MISSING_FIELDS', fields: missing };
}
return null; // 无错误
}
第二层:错误分析(Error Analysis)
// 使用LLM分析错误原因
async function analyzeError(error, context) {
const analysisPrompt = `
分析以下执行失败的原因,并提出修正建议:
错误信息:${error.message}
执行上下文:${JSON.stringify(context)}
请输出:
1. 错误原因(一句话)
2. 修正策略(具体可执行)
3. 需要调整的参数或输入
`;
const analysis = await llm.complete(analysisPrompt);
return parseAnalysis(analysis);
}
第三层:策略调整(Strategy Adjustment)
// 根据错误类型选择修正策略
const correctionStrategies = {
'JSON_PARSE_ERROR': async (input) => {
// 策略1: 尝试修复JSON
const fixed = attemptJSONFix(input);
if (fixed) return fixed;
// 策略2: 请求LLM重新生成
return await llm.complete(`修复以下JSON:${input}`);
},
'RATE_LIMIT': async (context) => {
// 策略: 等待后重试或切换模型
await sleep(60000); // 等待1分钟
return { retry: true, model: 'backup-model' };
},
'TOOL_NOT_FOUND': async (toolName) => {
// 策略: 搜索替代工具
const alternatives = findAlternativeTools(toolName);
return alternatives[0];
}
};
async function applyCorrection(error, context) {
const strategy = correctionStrategies[error.type];
if (strategy) return await strategy(context);
// 默认策略:重新执行
return { retry: true };
}
🔄 Self-Correction Loop完整实现
// 自我修正循环
class SelfCorrectingAgent {
private maxRetries = 3;
async executeWithCorrection(task, validator) {
let attempts = 0;
let result;
let error;
while (attempts < this.maxRetries) {
attempts++;
// 执行任务
result = await this.execute(task);
// 验证结果
error = validator(result);
if (!error) {
console.log(`任务成功,尝试次数:${attempts}`);
return result;
}
// 分析错误
const analysis = await this.analyzeError(error, { task, result, attempts });
// 调整策略
task = this.adjustTask(task, analysis);
console.log(`第${attempts}次尝试失败,原因:${analysis.reason}`);
console.log(`修正策略:${analysis.strategy}`);
}
throw new Error(`任务失败,已尝试${attempts}次`);
}
adjustTask(originalTask, analysis) {
return {
...originalTask,
correctionHint: analysis.strategy,
previousError: analysis.reason
};
}
}
🔧 OpenClaw实战配置
OpenClaw在Agent配置中内置了自我修正参数,启用后Agent会自动进行错误检测和修正尝试。
# openclaw-agent.yaml
agent:
name: "self-correcting-agent"
# 自我修正配置
self_correction:
enabled: true
max_retries: 3
retry_delay: 2000 # 毫秒
# 验证规则
validators:
- type: "json_schema"
schema: "./schemas/output.json"
- type: "content_length"
min: 100
max: 5000
- type: "required_keywords"
keywords: ["summary", "conclusion"]
# 修正策略
strategies:
json_error: "regenerate"
timeout: "switch_model"
rate_limit: "wait_retry"
tool_error: "find_alternative"
# 学习记录
learning:
enabled: true
memory_file: "./corrections-memory.md"
📊 自我修正效果统计
| 错误类型 | 首次成功率 | 修正后成功率 | 提升幅度 |
|---|---|---|---|
| JSON格式错误 | 65% | 92% | +27% |
| API超时 | 70% | 95% | +25% |
| 工具调用失败 | 75% | 88% | +13% |
| 内容质量不达标 | 60% | 85% | +25% |
| 综合成功率 | ~68% | ~90% | +22% |
⚠️ 常见踩坑与最佳实践
踩坑一:修正变成无限循环
Agent尝试修正→修正失败→再次修正→又失败...循环往复。必须设置最大重试次数(建议3-5次)和超时限制。
Agent尝试修正→修正失败→再次修正→又失败...循环往复。必须设置最大重试次数(建议3-5次)和超时限制。
踩坑二:修正消耗大量Token
每次修正都需要调用LLM分析,3次修正可能消耗首次执行2-3倍的Token。建议预算中预留修正Token开销,或使用轻量模型做错误分析。
每次修正都需要调用LLM分析,3次修正可能消耗首次执行2-3倍的Token。建议预算中预留修正Token开销,或使用轻量模型做错误分析。
踩坑三:修正策略不对症
JSON错误用重试解决、超时用重新生成解决——策略选择错误会让修正效率低下。建议根据错误类型建立策略映射表。
JSON错误用重试解决、超时用重新生成解决——策略选择错误会让修正效率低下。建议根据错误类型建立策略映射表。
最佳实践:
- 区分"可修正错误"和"不可修正错误",后者应直接上报
- 修正时携带错误历史,帮助LLM理解上下文
- 建立修正日志,分析高频错误类型优化系统
- 关键任务启用HITL,修正后人工确认
- 修正成功后记录经验到长期记忆