功能介绍
自我纠正(Self-Correction)是 AI Agent 的高级能力之一。OpenClaw 通过内置的输出验证、错误检测、自动修正和迭代优化机制,让 Agent 能够在执行过程中自主发现问题并纠正,显著提升输出质量和任务完成率。
为什么需要自我纠正?
即使是最先进的 LLM 也会产生幻觉、格式错误、逻辑漏洞。自我纠正机制让 Agent 成为"自己的质检员",在输出交付前进行多轮自检自改。
即使是最先进的 LLM 也会产生幻觉、格式错误、逻辑漏洞。自我纠正机制让 Agent 成为"自己的质检员",在输出交付前进行多轮自检自改。
自我纠正的四个阶段
1. 输出验证(Validation)
Agent 在生成输出后立即进行格式和结构验证:
- 格式检查:JSON/XML/Markdown 等格式是否正确
- 完整性检查:必填字段是否齐全
- 约束检查:是否满足预定义的业务规则
- 类型检查:数据类型是否符合预期
2. 错误检测(Error Detection)
深度分析输出质量,检测潜在问题:
- 事实核查:交叉验证关键信息点
- 逻辑一致性:检查输出内容的逻辑连贯性
- 幻觉检测:识别不存在的引用或虚假数据
- 偏见检测:检测输出中的潜在偏见
3. 自动修正(Auto-Correction)
针对检测到的问题执行自动修正:
- 格式修正:修复格式错误,调整结构
- 内容补充:补充缺失的信息
- 逻辑修正:修复逻辑漏洞和不一致
- 重新生成:对严重错误的部分重新生成
4. 迭代优化(Iterative Refinement)
通过多轮迭代持续改进输出质量:
- 质量评分:对每轮输出进行量化评分
- 差异比较:比较前后版本的改进
- 收敛判断:当质量达到阈值时停止迭代
- 经验积累:记录纠正模式用于未来改进
使用方法
配置自我纠正
// OpenClaw 自我纠正配置
module.exports = {
selfCorrection: {
// 启用自我纠正
enabled: true,
// 验证阶段配置
validation: {
schemaFile: './schemas/output-schema.json',
strictMode: false, // 严格模式:任一规则失败则拒绝
rules: ['format', 'completeness', 'constraints', 'types']
},
// 检测阶段配置
detection: {
factCheck: true,
logicCheck: true,
hallucinationCheck: true,
biasCheck: false // 可选开启
},
// 修正阶段配置
correction: {
maxRounds: 3, // 最多修正3轮
autoFix: true, // 自动修正
requireApproval: false, // 是否需要人工确认
improvementThreshold: 0.15 // 改进幅度阈值
}
}
};
实现自我纠正管理器
// OpenClaw 自我纠正管理器
class SelfCorrectionManager {
constructor(config) {
this.config = config;
this.correctionHistory = [];
this.qualityMetrics = {
totalOutputs: 0,
correctedOutputs: 0,
avgCorrections: 0
};
}
// 执行自我纠正流程
async selfCorrect(initialOutput, validationSchema) {
let currentOutput = initialOutput;
let qualityScore = 0;
for (let round = 0; round < this.config.correction.maxRounds; round++) {
// 阶段1:验证
const validation = await this.validate(currentOutput, validationSchema);
if (validation.passed) {
return {
output: currentOutput,
corrected: round > 0,
rounds: round,
qualityScore: validation.score
};
}
// 阶段2:检测问题
const issues = await this.detectIssues(currentOutput, validation);
if (issues.length === 0) break;
// 阶段3:自动修正
const newOutput = await this.correct(currentOutput, issues);
// 阶段4:评估改进
const newScore = await this.scoreQuality(newOutput);
// 检查是否有实质性改进
if (newScore - qualityScore < this.config.correction.improvementThreshold) {
break;
}
qualityScore = newScore;
currentOutput = newOutput;
}
// 记录统计
this.recordMetrics(initialOutput !== currentOutput);
return {
output: currentOutput,
corrected: true,
rounds: this.config.correction.maxRounds,
qualityScore
};
}
// 验证输出
async validate(output, schema) {
const errors = [];
// 格式验证
if (schema.format) {
try {
JSON.parse(JSON.stringify(output));
} catch (e) {
errors.push({ type: 'format', message: 'Invalid JSON structure' });
}
}
// 完整性验证
for (const field of schema.required || []) {
if (!output[field]) {
errors.push({ type: 'completeness', message: `Missing field: ${field}` });
}
}
// 约束验证
for (const [field, rule] of Object.entries(schema.constraints || {})) {
if (output[field] !== undefined && !rule.validate(output[field])) {
errors.push({ type: 'constraint', message: `Constraint failed for ${field}` });
}
}
return {
passed: errors.length === 0,
errors,
score: Math.max(0, 1 - errors.length * 0.2)
};
}
// 检测问题
async detectIssues(output, validation) {
const issues = [...validation.errors];
// 幻觉检测
for (const claim of extractClaims(output)) {
const verified = await factCheck(claim);
if (!verified.confirmed) {
issues.push({
type: 'hallucination',
message: `Unverified claim: ${claim.text}`,
details: verified
});
}
}
// 逻辑一致性检测
const logicIssues = await checkLogicConsistency(output);
issues.push(...logicIssues);
return issues;
}
}
最佳实践
- 定义清晰的验证规则:验证规则越具体,纠正效果越好
- 设置合理的迭代上限:避免无限循环,通常 2-3 轮足够
- 记录纠正模式:分析常见错误类型,针对性优化提示词
- 平衡效率和质量:对低风险输出可跳过部分检查
- 人工审核关键修正:高影响输出的修正应人工确认
自我纠正效果对比
| 指标 | 无自我纠正 | 有自我纠正 |
|---|---|---|
| 格式正确率 | 82% | 98% |
| 事实准确率 | 76% | 93% |
| 完整性 | 71% | 96% |
| 平均延迟 | 1.2s | 2.8s |
成本考虑
自我纠正会增加 Token 消耗和延迟。建议仅在高价值输出场景启用完整的自我纠正流程。
自我纠正会增加 Token 消耗和延迟。建议仅在高价值输出场景启用完整的自我纠正流程。