Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Agent Self-Correction

БесплатноБез исполняемых скриптовНе проверен

AI agent self-correction mechanisms: error detection, validation loops, recovery strategies, confidence scoring, and iterative refinement

diegosouzapwот diegosouzapw★ 68 звёзд на GitHub

Об этом скилле

Agent Self-Correction

Overview

AI agent self-correction mechanisms enable agents to detect errors, validate outputs, and automatically recover from failures. This includes validation loops, confidence scoring, iterative refinement, and recovery strategies to improve reliability.

Why This Matters

  • Reliability: Agents แก้ error ได้เองโดยไม่ต้อง human intervention
  • Quality: Output มีคุณภาพสูงขึ้น
  • Trust: Users มั่นใจในผลลัพธ์ที่ได้
  • Efficiency: ลด retry loops ที่ไม่จำเป็น

Core Concepts

1. Error Detection

interface ErrorDetection {
  type: 'syntax' | 'semantic' | 'logic' | 'format'
  severity: 'low' | 'medium' | 'high' | 'critical'
  message: string
  location?: string
}

class ErrorDetector {
  detectErrors(output: string, context: any): ErrorDetection[] {
    const errors: ErrorDetection[] = []

    // Syntax errors
    errors.push(...this.detectSyntaxErrors(output))

    // Semantic errors
    errors.push(...this.detectSemanticErrors(output, context))

    // Logic errors
    errors.push(...this.detectLogicErrors(output, context))

    // Format errors
    errors.push(...this.detectFormatErrors(output, context))

    return errors
  }

  private detectSyntaxErrors(output: string): ErrorDetection[] {
    const errors: ErrorDetection[] = []

    // Check for unclosed brackets
    const openBrackets = (output.match(/\(/g) || []).length
    const closeBrackets = (output.match(/\)/g) || []).length
    if (openBrackets !== closeBrackets) {
      errors.push({
        type: 'syntax',
        severity: 'high',
        message: 'Unclosed brackets detected',
      })
    }

    // Check for unclosed quotes
    const quotes = output.match(/"/g)
    if (quotes && quotes.length % 2 !== 0) {
      errors.push({
        type: 'syntax',
        severity: 'high',
        message: 'Unclosed quotes detected',
      })
    }

    return errors
  }

  private detectSemanticErrors(output: string, context: any): ErrorDetection[] {
    const errors: ErrorDetection[] = []

    // Check for hallucinations (if context provided)
    if (context.facts) {
      const outputFacts = this.extractFacts(output)
      for (const fact of outputFacts) {
        if (!context.facts.includes(fact)) {
          errors.push({
            type: 'semantic',
            severity: 'medium',
            message: `Potential hallucination: "${fact}" not in context`,
          })
        }
      }
    }

    return errors
  }

  private detectLogicErrors(output: string, context: any): ErrorDetection[] {
    const errors: ErrorDetection[] = []

    // Check for contradictions
    const statements = this.extractStatements(output)
    for (let i = 0; i < statements.length; i++) {
      for (let j = i + 1; j < statements.length; j++) {
        if (this.areContradictory(statements[i], statements[j])) {
          errors.push({
            type: 'logic',
            severity: 'high',
            message: 'Contradictory statements detected',
          })
        }
      }
    }

    return errors
  }

  private detectFormatErrors(output: string, context: any): ErrorDetection[] {
    const errors: ErrorDetection[] = []

    // Check if JSON is valid when expected
    if (context.expectedFormat === 'json') {
      try {
        JSON.parse(output)
      } catch (e) {
        errors.push({
          type: 'format',
          severity: 'critical',
          message: 'Invalid JSON output',
        })
      }
    }

    return errors
  }

  private extractFacts(text: string): string[] {
    // Extract factual statements
    return []
  }

  private extractStatements(text: string): string[] {
    // Extract logical statements
    return []
  }

  private areContradictory(a: string, b: string): boolean {
    // Check if two statements contradict
    return false
  }
}

2. Validation Loops

interface ValidationResult {
  isValid: boolean
  errors: string[]
  warnings: string[]
  confidence: number
}

class ValidationLoop {
  private maxIterations: number = 3
  private confidenceThreshold: number = 0.8

  async executeWithValidation<T>(
    task: () => Promise<T>,
    validator: (result: T) => ValidationResult,
    corrector: (result: T, errors: string[]) => Promise<T>
  ): Promise<T> {
    let result = await task()
    let iteration = 0

    while (iteration < this.maxIterations) {
      const validation = validator(result)

      if (validation.isValid && validation.confidence >= this.confidenceThreshold) {
        return result
      }

      console.log(`Iteration ${iteration + 1}: Validation failed`)
      console.log('Errors:', validation.errors)
      console.log('Warnings:', validation.warnings)
      console.log('Confidence:', validation.confidence)

      // Correct the result
      result = await corrector(result, validation.errors)
      iteration++
    }

    throw new Error(`Validation failed after ${this.maxIterations} iterations`)
  }
}

// Usage
const loop = new ValidationLoop()
Полный SKILL.md на GitHub

Установить Agent Self-Correction в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

metadata.json

FAQ

Что делает скилл Agent Self-Correction?

AI agent self-correction mechanisms: error detection, validation loops, recovery strategies, confidence scoring, and iterative refinement

Как установить скилл Agent Self-Correction?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Agent Self-Correction запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Agent Self-Correction с