OpenClaw Agent 自我纠正机制

让 AI Agent 具备自我检测和自动修正能力

功能介绍

自我纠正(Self-Correction)是 AI Agent 的高级能力之一。OpenClaw 通过内置的输出验证、错误检测、自动修正和迭代优化机制,让 Agent 能够在执行过程中自主发现问题并纠正,显著提升输出质量和任务完成率。

为什么需要自我纠正?
即使是最先进的 LLM 也会产生幻觉、格式错误、逻辑漏洞。自我纠正机制让 Agent 成为"自己的质检员",在输出交付前进行多轮自检自改。

自我纠正的四个阶段

1. 输出验证(Validation)

Agent 在生成输出后立即进行格式和结构验证:

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;
  }
}

最佳实践

  1. 定义清晰的验证规则:验证规则越具体,纠正效果越好
  2. 设置合理的迭代上限:避免无限循环,通常 2-3 轮足够
  3. 记录纠正模式:分析常见错误类型,针对性优化提示词
  4. 平衡效率和质量:对低风险输出可跳过部分检查
  5. 人工审核关键修正:高影响输出的修正应人工确认

自我纠正效果对比

指标 无自我纠正 有自我纠正
格式正确率82%98%
事实准确率76%93%
完整性71%96%
平均延迟1.2s2.8s
成本考虑
自我纠正会增加 Token 消耗和延迟。建议仅在高价值输出场景启用完整的自我纠正流程。

相关链接