操作指南

本节中的每个指南都针对您作为有经验的用户在使用 Ragas 时可能遇到的实际问题提供了专注的解决方案。这些指南设计得简洁直接,为您的问题提供快速解决方案。我们假设您对 Ragas 的概念有基本了解且能够熟练使用。如果不是,请先浏览 快速入门 (Get Started)部分。

如何将 LLM 对齐为评判器

在本指南中,您将学习如何使用 Ragas 系统地评估和对齐作为评判器(LLM-as-judge)的大语言模型,使其与人类专家的判断保持一致。

  • 构建可重用的评判器对齐评估管道
  • 分析评判器与人类标签之间的不一致模式
  • 迭代优化评判器提示词,提高与专家决策的一致性

为什么先对齐您的 LLM 评判器?

在运行评估实验之前,将您的 LLM 评判器对齐到特定用例非常重要。一个未对齐的评判器就像指向错误方向的指南针——您基于其指导做出的每一项改进都会让您离目标越来越远。将评判器对齐以匹配专家判断,确保您正在改进真正重要的东西。这个对齐步骤是可靠评估的基础。

真正的价值:审视您的数据

虽然构建一个对齐的 LLM 评判器很有用,但真正的业务价值来自于系统地分析您的数据并理解失败模式。评判器对齐过程迫使您深入检查边缘情况、明确评估标准,并揭示关于什么使响应好坏的洞察。将评判器视为扩展您分析能力的工具,而不是替代它。

设置您的环境

我们创建了一个简单的模块,您可以安装并运行,这样您就可以专注于理解评估过程,而不是创建应用程序。

uv pip install "ragas[examples]"
export OPENAI_API_KEY="your-api-key-here"

完整代码
您可以在此处查看评判器对齐评估管道的完整代码。

了解数据集

我们将使用 EvalsBench 数据集,其中包含专家标注的 LLM 对业务问题的响应示例。每一行包括:

  • question :原始问题
  • grading_notes :一个好的响应应涵盖的关键点
  • response :LLM 生成的响应
  • target :人类专家的二元判断(通过/失败)

下载数据集:

# Create datasets folder and download the dataset
mkdir -p datasets
curl -o datasets/benchmark_df.csv https://raw.githubusercontent.com/vibrantlabsai/EvalsBench/main/data/benchmark_df.csv

加载并检查数据集:

import pandas as pd
from ragas import Dataset

def load_dataset(csv_path: str = None) -> Dataset:
    """Load annotated dataset with human judgments.

    Expected columns: question, grading_notes, response, target (pass/fail)
    """
    path = csv_path or "datasets/benchmark_df.csv"
    df = pd.read_csv(path)

    dataset = Dataset(name="llm_judge_alignment", backend="local/csv")

    for _, row in df.iterrows():
        dataset.append({
            "question": row["question"],
            "grading_notes": row["grading_notes"],
            "response": row["response"],
            "target": (row["target"]),
        })

    return dataset

# Load the dataset
dataset = load_dataset()
print(f"Dataset loaded with {len(dataset)} samples")

数据集示例行:

question grading_notes response target
在 A 轮投资之前,确定科技初创公司投前估值的关键方法有哪些,它们之间有何区别? DCF 方法:!未来现金流!,需要预测;可比分析:类似公司倍数;VC 方法:收入 x 倍数 - 投后金额;创始人份额很重要;战略买家支付更高。 在 A 轮投资之前确定科技初创公司的投前估值是关键步骤…(涵盖 DCF、可比分析、VC 方法) pass
初创公司在订阅制商业模式中应优先考虑哪些关键指标和策略来有效管理和降低流失率? 流失率:!每月监控,理想 <5%。保留策略:用户互动,改善入职体验。CAC & LTV:平衡 3:1+。反馈循环:尽早实施。客户支持:主动响应,至关重要。 在订阅制商业模式中管理和降低流失率至关重要…(缺少具体指标和策略) fail

数据集中包含同一问题的多个响应——有些通过,有些失败。这有助于评判器学习可接受和不可接受响应之间的细微差别。

理解您的基准真相
评判器对齐的质量完全取决于基准真相标签的质量。在生产场景中,请让主要领域专家参与——其判断对您的用例最关键的人(例如,心理健康 AI 的心理学家、法律 AI 的律师,或支持聊天机器人的客户服务总监)。他们一致的判断成为评判器对齐的黄金标准。您不需要标注每个示例——一个有代表性的样本(涵盖各种场景的 100-200 个示例)足以进行可靠的对齐。

理解评估方法

在本指南中,我们评估数据集中已有的响应,而不是生成新的响应。这种方法确保评估运行之间的结果可重现,让我们能够专注于评判器对齐而非响应生成。

评估工作流是:数据集行(问题 + 响应)→ 评判器 → 与人类目标比较

定义评估指标

对于评判器对齐,我们需要两个指标:

  • 主要指标:accuracy(LLM 评判器) ——评估响应并返回通过/失败决策及原因。
  • 对齐指标:judge_alignment ——检查评判器的决策是否与人类专家的 verdict 匹配。
设置评判器指标

定义一个简单的基线评判器指标,根据评分要点评估响应:

from ragas.metrics import DiscreteMetric

# Define the judge metric with a simple baseline prompt
accuracy_metric = DiscreteMetric(
    name="accuracy",
    prompt="Check if the response contains points mentioned from the grading notes and return 'pass' or 'fail'.\n\nResponse: {response}\nGrading Notes: {grading_notes}",
    allowed_values=["pass", "fail"],
)
对齐指标

对齐指标用于比较评判器的决策与人类专家的 verdict:

from ragas.metrics.discrete import discrete_metric
from ragas.metrics.result import MetricResult

@discrete_metric(name="judge_alignment", allowed_values=["pass", "fail"])
def judge_alignment(judge_label: str, human_label: str) -> MetricResult:
    """Compare judge decision with human label."""
    judge = judge_label.strip().lower()
    human = human_label.strip().lower()

    if judge == human:
        return MetricResult(value="pass", reason=f"Judge={judge}; Human={human}")

    return MetricResult(value="fail", reason=f"Judge={judge}; Human={human}")

实验函数

实验函数编排完整的评估管道——使用评判器评估响应并测量对齐度:

from typing import Dict, Any
from ragas import experiment
from ragas.metrics import DiscreteMetric
from ragas_examples.judge_alignment import judge_alignment  # The metric we created above

@experiment()
async def judge_experiment(
    row: Dict[str, Any],
    accuracy_metric: DiscreteMetric,
    llm,
):
    """Run complete evaluation: Judge → Compare with human."""
    # Step 1: Get response (in production, this is where you'd call your LLM app)
    # For this evaluation, we use pre-existing responses from the dataset
    app_response = row["response"]

    # Step 2: Judge evaluates the response
    judge_score = await accuracy_metric.ascore(
        question=row["question"],
        grading_notes=row["grading_notes"],
        response=app_response,
        llm=llm,
    )

    # Step 3: Compare judge decision with human target
    alignment = judge_alignment.score(
        judge_label=judge_score.value,
        human_label=row["target"]
    )

    return {
        **row,
        "judge_label": judge_score.value,
        "judge_reason": judge_score.reason,
        "alignment": alignment.value,
        "alignment_reason": alignment.reason,
    }

运行基线评估

执行评估管道并收集结果
import os
from openai import AsyncOpenAI
from ragas.llms import llm_factory
from ragas_examples.judge_alignment import load_dataset

# Load dataset
dataset = load_dataset()
print(f"Dataset loaded with {len(dataset)} samples")

# Initialize LLM client
openai_client = AsyncOpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
llm = llm_factory("gpt-4o-mini", client=openai_client)

# Run the experiment
results = await judge_experiment.arun(
    dataset,
    name="judge_baseline_v1_gpt-4o-mini",
    accuracy_metric=accuracy_metric,
    llm=llm,
)

# Calculate alignment rate
passed = sum(1 for r in results if r["alignment"] == "pass")
total = len(results)
print(f"✅ Baseline alignment: {passed}/{total} passed ({passed/total:.1%})")

📋 输出(基线 v1)

2025-10-08 22:40:00,334 - Loaded dataset with 160 samples
2025-10-08 22:40:00,334 - Initializing LLM client with model: gpt-4o-mini
2025-10-08 22:40:01,858 - Running baseline evaluation...
Running experiment: 100%|████████████████████████| 160/160 [04:35<00:00,  1.72s/it]
2025-10-08 22:44:37,149 - ✅ Baseline alignment: 121/160 passed (75.6%)
初始性能分析

评估生成全面的 CSV 结果,包含所有输入( question 、 grading_notes 、 response )、人类目标、评判器的决策及推理,以及对齐比较。

分析错误和失败模式

运行基线评估后,我们可以分析不一致模式,以了解评判器在哪些方面与人类专家存在分歧。

基线性能:75.6% 对齐度(160 个样本中 121 个正确)

让我们查看错误分布:
📋 代码

import pandas as pd

# Load results
df = pd.read_csv('experiments/judge_baseline_v1_gpt-4o-mini.csv')

# Analyze misalignments
false_positives = len(df[(df['judge_label'] == 'pass') & (df['target'] == 'fail')])
false_negatives = len(df[(df['judge_label'] == 'fail') & (df['target'] == 'pass')])

print(f"False positives (judge too lenient): {false_positives}")
print(f"False negatives (judge too strict): {false_negatives}")

📋 输出

False positives (judge too lenient): 39
False negatives (judge too strict): 0

关键观察: 所有 39 个不一致(24.4%)都是假阳性——评判器判定为"通过"但人类专家判定为"失败"的情况。基线评判器过于宽松,遗漏了评分要点中缺失关键概念的响应。

失败案例示例

以下是评判器错误地通过了缺失关键概念的响应的示例:

评分要点 人类标签 评判器标签 缺失内容
Valuation caps (估值上限)、金额、投后估值关键。清算优先权:1x+ common(普通股)。反稀释: full vs. weighted (完全 vs. 加权)。董事会席位:1-2 个投资者代表。ESOP:10-20%。 fail pass 响应全面讨论了所有要点,但人类标注员因细微遗漏将其标记为失败
Impact on valuation (对估值的影响):可扩展性潜力、开发成本、集成难度。!开源 vs 专有问题。!技术债务风险。讨论 AWS/GCP/Azure… fail pass 缺少对投后估值影响的具体讨论 历史 vs 预测收入;
自上而下 & 自下而上方法; traction evidence (牵引力证据);!无偏见假设;12-24 个月预测… fail pass 缺少对牵引力证据的明确提及

错误的常见模式:

  1. 评分要点中遗漏 1-2 个特定概念,同时涵盖其他概念
  2. 隐含 vs 显式覆盖——评判器接受隐含概念,我们需要显式提及
  3. 缩写术语未正确解码(例如,“mkt demand” = market demand(市场需求),“post-$” = post-money valuation(投后估值))
  4. 关键标记被忽略——标有 * 或 ! 的要点通常是必不可少的

改进评判器提示词

基于错误分析,我们需要创建一个改进的提示词,使其能够:

  1. 理解评分要点中使用的缩写
  2. 识别关键标记( * 、 ! 、特定数字)
  3. 要求所有概念都存在,而不仅仅是大部分
  4. 接受语义等价物(同一概念的不同表述)
  5. 平衡严格性——不过于宽松也不过于严格
创建改进的 v2 提示词

定义具有全面评估标准的增强评判器指标:

from ragas.metrics import DiscreteMetric

# Define improved judge metric with enhanced evaluation criteria
accuracy_metric_v2 = DiscreteMetric(
    name="accuracy",
    prompt="""Evaluate if the response covers ALL the key concepts from the grading notes. Accept semantic equivalents but carefully check for missing concepts.

ABBREVIATION GUIDE - decode these correctly:

• Financial: val=valuation, post-$=post-money, rev=revenue, ARR/MRR=Annual/Monthly Recurring Revenue, COGS=Cost of Goods Sold, Opex=Operating Expenses, LTV=Lifetime Value, CAC=Customer Acquisition Cost
• Business: mkt=market, reg/regs=regulation/regulatory, corp gov=corporate governance, integr=integration, S&M=Sales & Marketing, R&D=Research & Development, acq=acquisition
• Technical: sys=system, elim=elimination, IP=Intellectual Property, TAM=Total Addressable Market, diff=differentiation
• Metrics: NPS=Net Promoter Score, SROI=Social Return on Investment, proj=projection, cert=certification

EVALUATION APPROACH:

Step 1 - Parse grading notes into distinct concepts:

- Separate by commas, semicolons, or line breaks
- Each item is a concept that must be verified
- Example: "*Gross Margin* >40%, CAC, LTV:CAC >3:1" = 3 concepts

Step 2 - For each concept, check if it's addressed:

- Accept semantic equivalents (e.g., "customer acquisition cost" = "CAC")
- Accept implicit coverage when it's clear (e.g., "revenue forecasting" covers "historical vs forecasted rev")
- Be flexible on exact numbers (e.g., "around 40%" acceptable for ">40%")

Step 3 - Count missing concepts:

- Missing 0 concepts = PASS
- Missing 1+ concepts = FAIL (even one genuinely missing concept should fail)
- Exception: If a long list (10+ items) has 1 very minor detail missing but all major points covered, use judgment

CRITICAL RULES:

1. Do NOT require exact wording - "market demand" = "mkt demand" = "demand analysis"

2. Markers (* or !) mean important, not mandatory exact phrases:
   - "*traction evidence*" can be satisfied by discussing metrics, growth, or validation
   - "!unbiased assumptions" can be satisfied by discussing assumption methodology

3. Numbers should be mentioned but accept approximations:
   - "$47B to $10B" can be "$47 billion dropped to around $10 billion"
   - "LTV:CAC >3:1" can be "LTV to CAC ratio of at least 3 to 1" or "3x or higher"

4. FAIL only when concepts are genuinely absent:
   - If notes mention "liquidation prefs, anti-dilution, board seats" but response only has board seats → FAIL
   - If notes mention "scalability, tech debt, IP" but response never discusses technical risks → FAIL
   - If notes mention "GDPR compliance" and response never mentions GDPR or EU regulations → FAIL

5. PASS when ALL concepts present:
   - All concepts covered, even with different wording → PASS
   - Concepts addressed implicitly when clearly implied → PASS
   - Minor phrasing differences → PASS
   - One or more concepts genuinely absent → FAIL

Response: {response}

Grading Notes: {grading_notes}

Are ALL distinct concepts from the grading notes covered in the response (accepting semantic equivalents and implicit coverage)?""",
    allowed_values=["pass", "fail"],
)

使用 LLM 优化提示词
在明确识别错误模式后,您可以使用 LLM 来优化提示词。您也可以使用 LLM 来识别错误,但请务必审查它们,确保与基准真相标签保持一致。您还可以使用编码智能体(如 Cursor、Claude Code)或框架(如 DSPy)来系统地优化评判器提示词。

使用改进后的提示词重新运行评估

使用增强的 v2 提示词再次运行评估(设置与基线相同,只需替换指标):

# Use the same dataset and LLM setup from the baseline evaluation above
results = await judge_experiment.arun(
    dataset,
    name="judge_accuracy_v2_gpt-4o-mini",
    accuracy_metric=accuracy_metric_v2,  # ← Using improved v2 prompt
    llm=llm,
)

passed = sum(1 for r in results if r["alignment"] == "pass")
total = len(results)
print(f"✅ V2 alignment: {passed}/{total} passed ({passed/total:.1%})")

📋 输出(改进版 v2)

2025-10-08 23:42:11,650 - Loaded dataset with 160 samples
2025-10-08 23:42:11,650 - Initializing LLM client with model: gpt-4o-mini
2025-10-08 23:42:12,730 - Running v2 evaluation with improved prompt...
Running experiment: 100%|██████████| 160/160 [04:39<00:00,  1.75s/it]
2025-10-08 23:46:52,740 - ✅ V2 alignment: 139/160 passed (86.9%)

显著改进!对齐度从 75.6% 提升到了 86.9%。

如果需要进一步迭代:

  • 分析剩余错误以识别模式(它们是假阳性还是假阴性?)
  • 标注您的推理以及标签——这将有助于改进 LLM 评判器,您也可以将这些作为 few-shot 示例添加
  • 使用更智能的模型——像 GPT-5 或 Claude 4.5 Sonnet 这样更强大的模型通常作为评判器表现更好
  • 利用 AI 助手——本指南是使用 Cursor AI 智能体创建的,用于分析失败并迭代提示词。您可以使用 AI 编码智能体(Cursor、Claude 等)或框架(如 DSPy)来系统地优化评判器提示词
  • 当对齐度在连续 2-3 次迭代中达到平稳状态或满足您的业务阈值时停止

您已完成的工作

您已使用 Ragas 构建了一个系统化的评估管道,它能够:

  • 使用清晰的指标测量评判器与专家判断的对齐度
  • 通过结构化错误分析识别失败模式
  • 通过可重现的实验跟踪评估运行中的改进

这个对齐的评判器成为您进行可靠 AI 评估的基础。有了一个可以信任的评判器,您现在可以自信地评估您的 RAG 管道、智能体工作流或任何 LLM 应用程序——知道指标的改进转化为质量的真正提升。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐