verification-loops

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Verification Loops

Verification Loops

Description

描述

Verification Loops are systematic evaluation pipelines that validate agent outputs at every stage of execution. The fundamental challenge of autonomous agents is trust — how do you know the agent did the right thing? Verification Loops solve this by embedding checkpoint evaluations, continuous assertions, and multi-stage review gates throughout the agent's execution pipeline. This skill draws from the evaluation methodology used in production at googleadsagent.ai™, where Buddy™ verifies every Google Ads recommendation against historical data, budget constraints, and domain rules before surfacing it to users.
The distinction between checkpoint and continuous verification is critical. Checkpoint verification evaluates outputs at defined stage boundaries (pre-commit, post-analysis, before-deploy). Continuous verification runs assertions in real-time during generation, catching drift and hallucination before they propagate. Both approaches are complemented by pass@k metrics — generating multiple candidate outputs and selecting the best one based on grader consensus.
Production verification systems employ typed graders: deterministic graders for schema and constraint validation, LLM-as-judge graders for semantic quality assessment, and human-in-the-loop graders for high-stakes decisions. The combination creates a layered verification net that catches errors at the earliest and cheapest point in the pipeline.
Verification Loops 是系统化的评估流水线,用于在 Agent 执行的每个阶段验证输出结果。自主 Agent 的核心挑战在于信任——你如何知道 Agent 做对了事情?Verification Loops 通过在 Agent 的执行流水线中嵌入检查点评估、持续断言和多阶段审查门控来解决这一问题。本 skill 借鉴了 googleadsagent.ai™ 生产环境中采用的评估方法,其中 Buddy™ 会在向用户展示每条 Google Ads 建议之前,使用历史数据、预算约束和领域规则对其进行验证。
检查点验证与持续验证的区别至关重要。检查点验证在明确的阶段边界(提交前、分析后、部署前)评估输出结果。持续验证在生成期间实时运行断言,在偏移和幻觉扩散之前将其捕获。两种方式都辅以 pass@k 指标——生成多个候选输出,并根据评分器共识选出最佳输出。
生产级验证系统采用类型化评分器:用于 schema 和约束验证的确定性评分器、用于语义质量评估的 LLM-as-judge 评分器,以及用于高风险决策的 human-in-the-loop 评分器。这种组合构成一张分层验证网,在流水线中最早且成本最低的环节捕获错误。

Use When

使用场景

  • Agent outputs directly influence business decisions or user-facing content
  • Regulatory or compliance requirements demand audit trails for AI-generated content
  • Multi-step workflows need quality gates between stages
  • You need to measure and improve agent accuracy over time (pass@k benchmarking)
  • Generated code must pass tests before being committed or deployed
  • Analysis results must be validated against ground truth or business rules
  • Agent 输出直接影响业务决策或面向用户的内容
  • 监管或合规要求需要为 AI 生成内容提供审计轨迹
  • 多步骤工作流需要在各阶段之间设置质量门控
  • 需要持续衡量并提升 Agent 准确率(pass@k 基准测试)
  • 生成的代码必须通过测试,才能提交或部署
  • 分析结果必须根据 ground truth 或业务规则进行验证

How It Works

工作原理

mermaid
graph TD
    A[Agent Output] --> B[Stage 1: Deterministic Grader]
    B -->|Pass| C[Stage 2: LLM-as-Judge]
    B -->|Fail| D[Reject + Feedback Loop]
    C -->|Pass| E[Stage 3: Confidence Scoring]
    C -->|Fail| D
    E -->|High Confidence| F[Accept Output]
    E -->|Low Confidence| G{pass@k Available?}
    G -->|Yes| H[Generate k Candidates]
    H --> I[Rank by Grader Consensus]
    I --> F
    G -->|No| J[Human-in-the-Loop Review]
    J --> F
    D --> K[Error Context Injection]
    K --> L[Re-generation with Feedback]
    L --> B
The verification pipeline processes every agent output through three stages. Stage 1 applies deterministic graders — schema validation, constraint checking, type verification — that are fast and cheap. Stage 2 invokes an LLM-as-judge that evaluates semantic correctness, completeness, and coherence. Stage 3 computes a confidence score from the combined grader signals. Low-confidence outputs trigger pass@k generation, where multiple candidates are produced and ranked by grader consensus. Rejected outputs receive specific error feedback that is injected into the re-generation prompt.
mermaid
graph TD
    A[Agent Output] --> B[Stage 1: Deterministic Grader]
    B -->|Pass| C[Stage 2: LLM-as-Judge]
    B -->|Fail| D[Reject + Feedback Loop]
    C -->|Pass| E[Stage 3: Confidence Scoring]
    C -->|Fail| D
    E -->|High Confidence| F[Accept Output]
    E -->|Low Confidence| G{pass@k Available?}
    G -->|Yes| H[Generate k Candidates]
    H --> I[Rank by Grader Consensus]
    I --> F
    G -->|No| J[Human-in-the-Loop Review]
    J --> F
    D --> K[Error Context Injection]
    K --> L[Re-generation with Feedback]
    L --> B
验证流水线会将每个 Agent 输出依次处理三个阶段。第 1 阶段应用确定性评分器——schema 验证、约束检查和类型验证——这些评分器速度快、成本低。第 2 阶段调用 LLM-as-judge,评估语义正确性、完整性和连贯性。第 3 阶段根据组合后的评分器信号计算置信度分数。低置信度输出会触发 pass@k 生成,即产生多个候选输出并按评分器共识排序。被拒绝的输出会收到具体的错误反馈,该反馈随后注入重新生成提示词。

Implementation

实现

Multi-Stage Verification Pipeline:
typescript
interface Grader {
  name: string;
  type: "deterministic" | "llm_judge" | "human";
  evaluate(output: string, context: VerificationContext): Promise<GradeResult>;
}

interface GradeResult {
  pass: boolean;
  score: number;
  feedback: string;
}

class VerificationPipeline {
  private stages: Grader[][] = [];

  addStage(graders: Grader[]): void {
    this.stages.push(graders);
  }

  async verify(output: string, context: VerificationContext): Promise<VerificationResult> {
    const stageResults: StageResult[] = [];

    for (const [idx, graders] of this.stages.entries()) {
      const grades = await Promise.all(
        graders.map(g => g.evaluate(output, context))
      );
      const stagePassed = grades.every(g => g.pass);
      const stageScore = grades.reduce((sum, g) => sum + g.score, 0) / grades.length;

      stageResults.push({ stage: idx, grades, passed: stagePassed, score: stageScore });

      if (!stagePassed) {
        return {
          accepted: false,
          stageResults,
          feedback: grades.filter(g => !g.pass).map(g => g.feedback).join("\n"),
        };
      }
    }

    const confidence = stageResults.reduce((sum, s) => sum + s.score, 0) / stageResults.length;
    return { accepted: true, stageResults, confidence };
  }
}
Pass@k Candidate Selection:
python
async def pass_at_k(task, generator, verifier, k=5):
    """Generate k candidates and select the best by verification score."""
    candidates = await asyncio.gather(*[
        generator.generate(task) for _ in range(k)
    ])

    scored = []
    for candidate in candidates:
        result = await verifier.verify(candidate, task.context)
        scored.append({
            "output": candidate,
            "accepted": result.accepted,
            "confidence": result.confidence,
            "feedback": result.feedback,
        })

    accepted = [s for s in scored if s["accepted"]]
    if accepted:
        return max(accepted, key=lambda s: s["confidence"])

    return max(scored, key=lambda s: s["confidence"])
LLM-as-Judge Grader:
python
class LLMJudgeGrader:
    JUDGE_PROMPT = """You are an expert evaluator. Assess the following agent output
against the given task requirements.

Task: {task}
Output: {output}
Criteria: {criteria}

Respond with JSON:
{{"pass": true/false, "score": 0.0-1.0, "feedback": "specific feedback"}}"""

    def __init__(self, judge_model, criteria):
        self.judge_model = judge_model
        self.criteria = criteria

    async def evaluate(self, output, context):
        prompt = self.JUDGE_PROMPT.format(
            task=context.task_description,
            output=output,
            criteria=self.criteria,
        )
        response = await self.judge_model.generate(prompt, temperature=0.0)
        return json.loads(response)
Deterministic Schema Grader:
python
class SchemaGrader:
    def __init__(self, schema: dict):
        self.schema = schema

    async def evaluate(self, output, context):
        try:
            parsed = json.loads(output)
            jsonschema.validate(parsed, self.schema)
            return {"pass": True, "score": 1.0, "feedback": "Schema valid"}
        except jsonschema.ValidationError as e:
            return {"pass": False, "score": 0.0, "feedback": f"Schema violation: {e.message}"}
        except json.JSONDecodeError:
            return {"pass": False, "score": 0.0, "feedback": "Invalid JSON"}
多阶段验证流水线:
typescript
interface Grader {
  name: string;
  type: "deterministic" | "llm_judge" | "human";
  evaluate(output: string, context: VerificationContext): Promise<GradeResult>;
}

interface GradeResult {
  pass: boolean;
  score: number;
  feedback: string;
}

class VerificationPipeline {
  private stages: Grader[][] = [];

  addStage(graders: Grader[]): void {
    this.stages.push(graders);
  }

  async verify(output: string, context: VerificationContext): Promise<VerificationResult> {
    const stageResults: StageResult[] = [];

    for (const [idx, graders] of this.stages.entries()) {
      const grades = await Promise.all(
        graders.map(g => g.evaluate(output, context))
      );
      const stagePassed = grades.every(g => g.pass);
      const stageScore = grades.reduce((sum, g) => sum + g.score, 0) / grades.length;

      stageResults.push({ stage: idx, grades, passed: stagePassed, score: stageScore });

      if (!stagePassed) {
        return {
          accepted: false,
          stageResults,
          feedback: grades.filter(g => !g.pass).map(g => g.feedback).join("\n"),
        };
      }
    }

    const confidence = stageResults.reduce((sum, s) => sum + s.score, 0) / stageResults.length;
    return { accepted: true, stageResults, confidence };
  }
}
Pass@k 候选选择:
python
async def pass_at_k(task, generator, verifier, k=5):
    """Generate k candidates and select the best by verification score."""
    candidates = await asyncio.gather(*[
        generator.generate(task) for _ in range(k)
    ])

    scored = []
    for candidate in candidates:
        result = await verifier.verify(candidate, task.context)
        scored.append({
            "output": candidate,
            "accepted": result.accepted,
            "confidence": result.confidence,
            "feedback": result.feedback,
        })

    accepted = [s for s in scored if s["accepted"]]
    if accepted:
        return max(accepted, key=lambda s: s["confidence"])

    return max(scored, key=lambda s: s["confidence"])
LLM-as-Judge 评分器:
python
class LLMJudgeGrader:
    JUDGE_PROMPT = """You are an expert evaluator. Assess the following agent output
against the given task requirements.

Task: {task}
Output: {output}
Criteria: {criteria}

Respond with JSON:
{{"pass": true/false, "score": 0.0-1.0, "feedback": "specific feedback"}}"""

    def __init__(self, judge_model, criteria):
        self.judge_model = judge_model
        self.criteria = criteria

    async def evaluate(self, output, context):
        prompt = self.JUDGE_PROMPT.format(
            task=context.task_description,
            output=output,
            criteria=self.criteria,
        )
        response = await self.judge_model.generate(prompt, temperature=0.0)
        return json.loads(response)
确定性 Schema 评分器:
python
class SchemaGrader:
    def __init__(self, schema: dict):
        self.schema = schema

    async def evaluate(self, output, context):
        try:
            parsed = json.loads(output)
            jsonschema.validate(parsed, self.schema)
            return {"pass": True, "score": 1.0, "feedback": "Schema valid"}
        except jsonschema.ValidationError as e:
            return {"pass": False, "score": 0.0, "feedback": f"Schema violation: {e.message}"}
        except json.JSONDecodeError:
            return {"pass": False, "score": 0.0, "feedback": "Invalid JSON"}

Best Practices

最佳实践

  1. Order graders by cost — run deterministic (free) graders before LLM-as-judge (expensive) graders; most failures are caught cheaply.
  2. Make feedback actionable — grader feedback injected into re-generation prompts must be specific enough to guide correction ("field X is missing" not "output is wrong").
  3. Track pass rates per grader — a grader that never fails adds latency without value; a grader that always fails indicates a prompt or model problem.
  4. Use pass@k strategically — generating 5 candidates costs 5x tokens; reserve pass@k for high-value outputs where accuracy justifies the cost.
  5. Separate verification from generation models — using a different model as judge reduces correlated errors where the same model makes and overlooks the same mistake.
  6. Implement verification caching — identical outputs to identical tasks should return cached verification results without re-evaluation.
  7. Set confidence thresholds per use case — code generation may require 0.95 confidence; creative writing may accept 0.7.
  1. 按成本安排评分器顺序——先运行确定性(免费)评分器,再运行 LLM-as-judge(昂贵)评分器;大多数失败都能以低成本捕获。
  2. 让反馈可执行——注入重新生成提示词的评分器反馈必须足够具体,能够指导修正(“缺少字段 X”,而不是“输出错误”)。
  3. 跟踪每个评分器的通过率——从不失败的评分器只会增加延迟而没有价值;始终失败的评分器则表明提示词或模型存在问题。
  4. 有策略地使用 pass@k——生成 5 个候选会消耗 5 倍 token;仅在准确率足以证明成本合理的高价值输出上使用 pass@k。
  5. 将验证模型与生成模型分离——使用不同模型担任评分器,可以减少相关错误,即同一模型既犯下又忽视同一错误。
  6. 实现验证缓存——针对相同任务的相同输出应返回缓存的验证结果,而无需重新评估。
  7. 按使用场景设置置信度阈值——代码生成可能需要 0.95 的置信度;创意写作则可以接受 0.7。

Platform Compatibility

平台兼容性

FeatureClaude CodeCursorCodexGemini CLI
Deterministic graders✅ Full✅ Full✅ Full✅ Full
LLM-as-judge✅ Full✅ Via API✅ Via API✅ Via API
pass@k generation✅ Full✅ Subagents✅ Full✅ Full
Pre-commit hooks✅ Native hooks✅ Git hooks✅ Git hooks✅ Git hooks
Confidence scoring✅ Full✅ Full✅ Full✅ Full
功能Claude CodeCursorCodexGemini CLI
确定性评分器✅ 完整✅ 完整✅ 完整✅ 完整
LLM-as-judge✅ 完整✅ 通过 API✅ 通过 API✅ 通过 API
pass@k 生成✅ 完整✅ 子 Agent✅ 完整✅ 完整
Pre-commit hooks✅ 原生 hooks✅ Git hooks✅ Git hooks✅ Git hooks
置信度评分✅ 完整✅ 完整✅ 完整✅ 完整

Mythos Preview Reference

Mythos Preview 参考

Anthropic’s Mythos Preview pipeline ends with a second agent pass whose job is triage, not discovery: they prompt along the lines of “I have received the following bug report. Can you please confirm if it’s real and interesting?” to filter true-but-low-impact issues from severe, broadly relevant ones.
Use that as a validation-agent pattern: after the primary agent produces a finding, spawn a fresh review with the artifact, explicit skepticism, and criteria for “real,” “important,” and “actionable.” Source: Mythos Preview.
Anthropic 的 Mythos Preview 流水线以第二次 Agent 执行结束,其任务是分类筛选而非发现:他们会使用类似*“我收到了以下 bug 报告。请确认它是否真实且值得关注?”*的提示,从影响严重且广泛相关的问题中筛选出真实但影响较小的问题。
你可以将其作为一种验证 Agent(validation-agent)模式:主 Agent 生成发现后,使用该产物、明确的质疑态度以及“真实”“重要”“可执行”的标准,启动一次全新的审查。来源:Mythos Preview。

Related Skills

相关 Skill

  • Self-Healing Agents - Error recovery that activates when verification loops reject agent outputs
  • Agent Instinct System - Pre-action validation that prevents errors before verification is needed
  • Prompt Architecture - Schema enforcement in prompt design that reduces verification failure rates
  • Self-Healing Agents - 当验证循环拒绝 Agent 输出时激活的错误恢复机制
  • Agent Instinct System - 在需要验证之前防止错误发生的前置验证
  • Prompt Architecture - 在提示词设计中实施 schema 约束,从而降低验证失败率

Keywords

关键词

verification-loops, evaluation, graders, pass-at-k, llm-as-judge, confidence-scoring, checkpoint-verification, continuous-evaluation, quality-gates, agent-skills

© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License
verification-loops, evaluation, graders, pass-at-k, llm-as-judge, confidence-scoring, checkpoint-verification, continuous-evaluation, quality-gates, agent-skills

© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License