ragas官方文档中文版(四十九)

ragas官方文档中文版(四十九) 操作指南本节中的每个指南都针对您作为有经验的用户在使用 Ragas 时可能遇到的实际问题提供了专注的解决方案。这些指南设计得简洁直接为您的问题提供快速解决方案。我们假设您对 Ragas 的概念有基本了解且能够熟练使用。如果不是请先浏览 快速入门 Get Started部分。如何将 LLM 对齐为评判器在本指南中您将学习如何使用 Ragas 系统地评估和对齐作为评判器LLM-as-judge的大语言模型使其与人类专家的判断保持一致。构建可重用的评判器对齐评估管道分析评判器与人类标签之间的不一致模式迭代优化评判器提示词提高与专家决策的一致性为什么先对齐您的 LLM 评判器在运行评估实验之前将您的 LLM 评判器对齐到特定用例非常重要。一个未对齐的评判器就像指向错误方向的指南针——您基于其指导做出的每一项改进都会让您离目标越来越远。将评判器对齐以匹配专家判断确保您正在改进真正重要的东西。这个对齐步骤是可靠评估的基础。真正的价值审视您的数据虽然构建一个对齐的 LLM 评判器很有用但真正的业务价值来自于系统地分析您的数据并理解失败模式。评判器对齐过程迫使您深入检查边缘情况、明确评估标准并揭示关于什么使响应好坏的洞察。将评判器视为扩展您分析能力的工具而不是替代它。设置您的环境我们创建了一个简单的模块您可以安装并运行这样您就可以专注于理解评估过程而不是创建应用程序。uv pip installragas[examples]export OPENAI_API_KEYyour-api-key-here完整代码您可以在此处查看评判器对齐评估管道的完整代码。了解数据集我们将使用 EvalsBench 数据集其中包含专家标注的 LLM 对业务问题的响应示例。每一行包括question 原始问题grading_notes 一个好的响应应涵盖的关键点response LLM 生成的响应target 人类专家的二元判断通过/失败下载数据集# Create datasets folder and download the datasetmkdir-pdatasetscurl-odatasets/benchmark_df.csv https://raw.githubusercontent.com/vibrantlabsai/EvalsBench/main/data/benchmark_df.csv加载并检查数据集importpandasaspdfromragasimportDatasetdefload_dataset(csv_path:strNone)-Dataset:Load annotated dataset with human judgments. Expected columns: question, grading_notes, response, target (pass/fail) pathcsv_pathordatasets/benchmark_df.csvdfpd.read_csv(path)datasetDataset(namellm_judge_alignment,backendlocal/csv)for_,rowindf.iterrows():dataset.append({question:row[question],grading_notes:row[grading_notes],response:row[response],target:(row[target]),})returndataset# Load the datasetdatasetload_dataset()print(fDataset loaded with{len(dataset)}samples)数据集示例行questiongrading_notesresponsetarget在 A 轮投资之前确定科技初创公司投前估值的关键方法有哪些它们之间有何区别DCF 方法!未来现金流!需要预测可比分析类似公司倍数VC 方法收入 x 倍数 - 投后金额创始人份额很重要战略买家支付更高。在 A 轮投资之前确定科技初创公司的投前估值是关键步骤…涵盖 DCF、可比分析、VC 方法pass初创公司在订阅制商业模式中应优先考虑哪些关键指标和策略来有效管理和降低流失率流失率!每月监控理想 5%。保留策略用户互动改善入职体验。CAC LTV平衡 3:1。反馈循环尽早实施。客户支持主动响应至关重要。在订阅制商业模式中管理和降低流失率至关重要…缺少具体指标和策略fail数据集中包含同一问题的多个响应——有些通过有些失败。这有助于评判器学习可接受和不可接受响应之间的细微差别。理解您的基准真相评判器对齐的质量完全取决于基准真相标签的质量。在生产场景中请让主要领域专家参与——其判断对您的用例最关键的人例如心理健康 AI 的心理学家、法律 AI 的律师或支持聊天机器人的客户服务总监。他们一致的判断成为评判器对齐的黄金标准。您不需要标注每个示例——一个有代表性的样本涵盖各种场景的 100-200 个示例足以进行可靠的对齐。理解评估方法在本指南中我们评估数据集中已有的响应而不是生成新的响应。这种方法确保评估运行之间的结果可重现让我们能够专注于评判器对齐而非响应生成。评估工作流是数据集行问题 响应→ 评判器 → 与人类目标比较定义评估指标对于评判器对齐我们需要两个指标主要指标accuracyLLM 评判器 ——评估响应并返回通过/失败决策及原因。对齐指标judge_alignment ——检查评判器的决策是否与人类专家的 verdict 匹配。设置评判器指标定义一个简单的基线评判器指标根据评分要点评估响应fromragas.metricsimportDiscreteMetric# Define the judge metric with a simple baseline promptaccuracy_metricDiscreteMetric(nameaccuracy,promptCheck 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],)对齐指标对齐指标用于比较评判器的决策与人类专家的 verdictfromragas.metrics.discreteimportdiscrete_metricfromragas.metrics.resultimportMetricResultdiscrete_metric(namejudge_alignment,allowed_values[pass,fail])defjudge_alignment(judge_label:str,human_label:str)-MetricResult:Compare judge decision with human label.judgejudge_label.strip().lower()humanhuman_label.strip().lower()ifjudgehuman:returnMetricResult(valuepass,reasonfJudge{judge}; Human{human})returnMetricResult(valuefail,reasonfJudge{judge}; Human{human})实验函数实验函数编排完整的评估管道——使用评判器评估响应并测量对齐度fromtypingimportDict,Anyfromragasimportexperimentfromragas.metricsimportDiscreteMetricfromragas_examples.judge_alignmentimportjudge_alignment# The metric we created aboveexperiment()asyncdefjudge_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 youd call your LLM app)# For this evaluation, we use pre-existing responses from the datasetapp_responserow[response]# Step 2: Judge evaluates the responsejudge_scoreawaitaccuracy_metric.ascore(questionrow[question],grading_notesrow[grading_notes],responseapp_response,llmllm,)# Step 3: Compare judge decision with human targetalignmentjudge_alignment.score(judge_labeljudge_score.value,human_labelrow[target])return{**row,judge_label:judge_score.value,judge_reason:judge_score.reason,alignment:alignment.value,alignment_reason:alignment.reason,}运行基线评估执行评估管道并收集结果importosfromopenaiimportAsyncOpenAIfromragas.llmsimportllm_factoryfromragas_examples.judge_alignmentimportload_dataset# Load datasetdatasetload_dataset()print(fDataset loaded with{len(dataset)}samples)# Initialize LLM clientopenai_clientAsyncOpenAI(api_keyos.environ.get(OPENAI_API_KEY))llmllm_factory(gpt-4o-mini,clientopenai_client)# Run the experimentresultsawaitjudge_experiment.arun(dataset,namejudge_baseline_v1_gpt-4o-mini,accuracy_metricaccuracy_metric,llmllm,)# Calculate alignment ratepassedsum(1forrinresultsifr[alignment]pass)totallen(results)print(f✅ Baseline alignment:{passed}/{total}passed ({passed/total:.1%})) 输出基线 v12025-10-0822:40:00,334-Loaded datasetwith160samples2025-10-0822:40:00,334-Initializing LLM clientwithmodel:gpt-4o-mini2025-10-0822:40:01,858-Running baseline evaluation...Running experiment:100%|████████████████████████|160/160[04:3500:00,1.72s/it]2025-10-0822:44:37,149-✅ Baseline alignment:121/160passed(75.6%)初始性能分析评估生成全面的 CSV 结果包含所有输入 question 、 grading_notes 、 response 、人类目标、评判器的决策及推理以及对齐比较。分析错误和失败模式运行基线评估后我们可以分析不一致模式以了解评判器在哪些方面与人类专家存在分歧。基线性能75.6% 对齐度160 个样本中 121 个正确让我们查看错误分布 代码importpandasaspd# Load resultsdfpd.read_csv(experiments/judge_baseline_v1_gpt-4o-mini.csv)# Analyze misalignmentsfalse_positiveslen(df[(df[judge_label]pass)(df[target]fail)])false_negativeslen(df[(df[judge_label]fail)(df[target]pass)])print(fFalse positives (judge too lenient):{false_positives})print(fFalse negatives (judge too strict):{false_negatives}) 输出Falsepositives(judge too lenient):39Falsenegatives(judge too strict):0关键观察 所有 39 个不一致24.4%都是假阳性——评判器判定为通过但人类专家判定为失败的情况。基线评判器过于宽松遗漏了评分要点中缺失关键概念的响应。失败案例示例以下是评判器错误地通过了缺失关键概念的响应的示例评分要点人类标签评判器标签缺失内容Valuation caps 估值上限、金额、投后估值关键。清算优先权1x common普通股。反稀释 full vs. weighted 完全 vs. 加权。董事会席位1-2 个投资者代表。ESOP10-20%。failpass响应全面讨论了所有要点但人类标注员因细微遗漏将其标记为失败Impact on valuation 对估值的影响可扩展性潜力、开发成本、集成难度。!开源 vs 专有问题。!技术债务风险。讨论 AWS/GCP/Azure…failpass缺少对投后估值影响的具体讨论 历史 vs 预测收入自上而下 自下而上方法 traction evidence 牵引力证据!无偏见假设12-24 个月预测…failpass缺少对牵引力证据的明确提及错误的常见模式评分要点中遗漏 1-2 个特定概念同时涵盖其他概念隐含 vs 显式覆盖——评判器接受隐含概念我们需要显式提及缩写术语未正确解码例如“mkt demand” market demand市场需求“post-$” post-money valuation投后估值关键标记被忽略——标有 * 或 ! 的要点通常是必不可少的改进评判器提示词基于错误分析我们需要创建一个改进的提示词使其能够理解评分要点中使用的缩写识别关键标记 * 、 ! 、特定数字要求所有概念都存在而不仅仅是大部分接受语义等价物同一概念的不同表述平衡严格性——不过于宽松也不过于严格创建改进的 v2 提示词定义具有全面评估标准的增强评判器指标fromragas.metricsimportDiscreteMetric# Define improved judge metric with enhanced evaluation criteriaaccuracy_metric_v2DiscreteMetric(nameaccuracy,promptEvaluate 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: valvaluation, post-$post-money, revrevenue, ARR/MRRAnnual/Monthly Recurring Revenue, COGSCost of Goods Sold, OpexOperating Expenses, LTVLifetime Value, CACCustomer Acquisition Cost • Business: mktmarket, reg/regsregulation/regulatory, corp govcorporate governance, integrintegration, SMSales Marketing, RDResearch Development, acqacquisition • Technical: syssystem, elimelimination, IPIntellectual Property, TAMTotal Addressable Market, diffdifferentiation • Metrics: NPSNet Promoter Score, SROISocial Return on Investment, projprojection, certcertification 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 its addressed: - Accept semantic equivalents (e.g., customer acquisition cost CAC) - Accept implicit coverage when its 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 aboveresultsawaitjudge_experiment.arun(dataset,namejudge_accuracy_v2_gpt-4o-mini,accuracy_metricaccuracy_metric_v2,# ← Using improved v2 promptllmllm,)passedsum(1forrinresultsifr[alignment]pass)totallen(results)print(f✅ V2 alignment:{passed}/{total}passed ({passed/total:.1%})) 输出改进版 v22025-10-0823:42:11,650-Loaded datasetwith160samples2025-10-0823:42:11,650-Initializing LLM clientwithmodel:gpt-4o-mini2025-10-0823:42:12,730-Running v2 evaluationwithimproved prompt...Running experiment:100%|██████████|160/160[04:3900:00,1.75s/it]2025-10-0823:46:52,740-✅ V2 alignment:139/160passed(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 应用程序——知道指标的改进转化为质量的真正提升。