用Ragas对齐LLM评审与专家判断

介绍借助Ragas构建可复用的评估流程,将LLM评审指标与人类专家判断对齐,先跑基线再分析分歧模式,并据错误分析改进评审提示词后重跑对比。

## 如何将一个LLM作为法官 在这个指南中,你将学会如何系统地评估 并调整 LLM 现判量度 与使用 Ragas 的人类专家判断。 - 建立可重复使用的评价管道,供法官调整 - 分析法官与人类标签之间的分歧模式 - 对法官进行判决,促使他们改进与专家裁决的一致性 ## 为什么首先让你的LLM法官负责? 在进行评估实验之前,重要的是调整您的LLM判断器与您的特定使用案例。一个错误的判断器就像指向错误的方法的指南针 — 你根据它的指导所做的每一个改进都使你进一步偏离了目标。 调整判断器与专家判断相匹配可以确保您正在改进真正重要的是什么。这个调整步骤是可靠的评估的基础。 真实值: 查看您的数据 尽管构建一个一致的LLM判断器是有用的,但真正的商业价值来自于系统分析您的数据和理解失败模式。 法官调整过程迫使您深入审查边缘案例,澄清评估标准,并发现对反应的好坏的见解。 将法官视为一个衡量您分析的工具,而不是替代它的工具。 ## 设置您的环境 我们已经创建了一个简单的模块,你可以安装和运行,这样你就可以专注于理解评价过程而不是创建应用程序. ``` uv pip install "ragas[examples]" export OPENAI_API_KEY="your-api-key-here" ``` 完整代码 您可以查看法官校正评估流程的完整代码 [这儿](<https://github.com/vibrantlabsai/ragas/tree/main/examples/ragas_examples/judge_alignment>). ## 了解数据集 我们用一下 [EvalsBench 数据集](<https://github.com/vibrantlabsai/EvalsBench/blob/main/data/benchmark_df.csv>) 包含专家说明的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") ``` **数据集样本行 :** | 问题 | grading_notes | 回应 | 目标 | | --- | --- | --- | --- | | 在A系列投资回合之前确定技术启动资金预估的关键方法是什么,它们有何不同? | DCF方法:!未来现金流量!,需要预测;comp.分析:相似的共倍数;VC方法:rev x多倍数 - 美元后; *创始人的股份问题*;战略买家支付更多。 | 在A系列投资回合之前确定技术启动的货币预估是一个关键步骤.(涵盖DCF,可比较分析,VC方法) | 传球 | | 在以订阅为基础的业务模式中,启动阶段应优先采用哪些关键指标和战略,以有效管理和降低收费率? | Churn:! 月度监视器, < 5% 理想。 *保留战略*:接触用户,改进登机. CAC & LTV:平衡3:1+. 反馈循环:提前实施. *客户支助*:主动反应和反应,关键。 | 在以订阅为基础的业务模式中管理和降低成本率至关重要.(缺少具体的衡量标准和战略) | 失败 | 数据集包含对相同问题的多个答复——有些通过,有些失败,这有助于法官学习可接受和不可接受的答复之间的细微区别。 了解你的真相 了解你的真相 了解你的真相 法官的校正质量完全取决于你地面真实标签的质量。 **主要域专家** - 判断对您的使用案件最关键的人(例如心理健康心理学家AI,法律方面的AI律师,或支持聊天员的客户服务总监)。他们的一致判断成为您法官所赞同的金本位标准。你不需要每个标注的例子 — 一个具有代表性的样本(100 - 涵盖不同情景的200实例)足以可靠地对齐。 ## 了解评价办法 在本指南中,我们评价了数据集中原有的回复,而不是产生新的回复。 这一方法确保了整个评价周期的可复制成果,使我们能够注重判断一致性,而不是生成回复。 评价工作流程是: **数据集行(问题+答复) • 法官 → 与人类目标比较** ## 界定评价指标 对于法官的校正,我们需要两个标准: **初级计量: `accuracy` (LLM法官)** - 以合理的理由评价答复和返回的通过/失败决定。 **对齐度量 : `judge_alignment`** - 检查法官的判决是否与人类专家的判决相符. ### 设立法官的衡量标准 定义一个简单的基线法官衡量标准,根据分级说明评价答复: ``` 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"], ) ``` ### 调整尺度 将法官的判决与人类的判决相比较: ``` 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}") ``` ## 实验功能 那个... [实验函数](<https://docs.ragas.io/concepts/experimentation>) 安排完整的评价程序 -- -- 与法官评价对策和衡量一致性: ``` 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结果,包含所有投入(问题,grading_notes,回应),人的目标,以推理判断决定,以及对齐比较. ## 分析错误和失败模式 在进行基线评估后,我们可以分析错配模式,以了解法官与人类专家的分歧之处. **基线性能:75.6%对齐(121 / 160 正确)** 我们来检查一下错误的分布 QQ 代码 ``` 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*, $, post-$ val key. Liquidation prefs: 1x+ common. Anti-dilution: *full vs. weighted*. Board seats: 1-2 investor reps. ESOP: 10-20%.` | 失败 | 传球 | 回应全面讨论所有要点,但人类的注解者将其标注为因细微的遗漏而失败 | | `*Impact on valuation*: scalability potential, dev costs, integration ease. !Open-source vs proprietary issues. !Tech debt risks. Discuss AWS/GCP/Azure...` | 失败 | 传球 | 缺少关于货币估值后影响的具体讨论 | | `Historical vs. forecasted rev; top-down & bottom-up methods; *traction evidence*; !unbiased assumptions; 12-24mo project...` | 失败 | 传球 | 未明确提及牵引证据 | **错误中的常见模式 :** 1. **缺少 1 - 2 具体概念** 从分级笔记开始,同时涵盖其他笔记 2. **隐含性与明确涵盖范围** - 法官接受隐含的概念 我们要明确提及 3. **缩略语** 未适当解码(如"mkt需求"=市场需求,"后美元"=货币估值). 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"], ) ``` 使用 LLMS 优化提示 您可以在识别出错误模式后使用 LLMS 优化提示。 您也可以使用 LLMS 识别错误模式, 但请检查它们, 以便它们与地面真实标签一致 。 您也可以使用诸如 Cursor, Claude Code 或框架等编码代理工具 。 [DSPY 软件](<https://github.com/stanfordnlp/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 判官的同时有所帮助, - **使用更聪明的模型** - 更有能力的模型,如GPT-5或Claude 4.5 Sonnet作为评委一般表现较好. - **调用 AI 助手** - 此指南是使用 Cursor AI 代理来分析失败并在提示上斜拉。 您可以使用 AI 编码代理( Cursor, Claude 等) 或框架 [DSPY 软件](<https://github.com/stanfordnlp/dspy>) 系统优化法官的提示 - 当对齐高原跨越2 - 3 迭代或满足您的业务门槛时停止 ## 你的成就 你用Ragas建造了一个系统的评估管道: - 衡量标准与专家判决的一致 - 通过结构化错误分析确定故障模式 - 通过可复制的实验,在整个评价中跟踪改进情况 这个对齐的法官成为了您可靠的AI评价的基础。 有了一位您可以信任的法官,您现在可以自信地评价您的RAG管道,代理工作流程,或者任何LLM应用程序 — — 知道测量的改进会转化为质量的真正改善。 11月 13, 2026 12月 16, 2025 GitHub

查看原始来源