将 LLM 评测器与人类判断对齐
本教程是关于如何将 Vertex AI 模型与 Ragas 一起使用的三部分系列的一部分。建议你先阅读 入门:Ragas 与 Vertex AI;即使你还没有读过,也可以轻松跟上。你可以通过这个链接跳转到 Model Comparison 教程。
概述
在本教程中,你将学习如何用 Ragas 训练并对齐你自己的自定义基于 LLM 的指标。虽然基于 LLM 的评测器为给 AI 应用打分提供了强大手段,但由于风格、上下文或细微差别,它们有时会产出与人类期望不一致的判断。按照本指南,你将 refinement 你的指标,使其更准确地反映人类判断。
在本教程中,你将:
- 用 Ragas 定义一个基于模型的指标。
- 从 HHH 数据集的 "helpful" 子集构建一个 EvaluationDataset。
- 运行一次初始评测,为该指标的表现建立基准。
- 审阅并标注 15–20 个评测样例。
- 用你标注的数据训练该指标。
- 重新评测该指标,观察其与人类判断对齐程度的改进。
开始
安装依赖
%pip install --upgrade --user --quiet langchain-core langchain-google-vertexai langchain ragas
重启运行时
要在这个 Jupyter runtime 中使用新安装的包,必须重启运行时。你可以运行下面的 cell 来完成,它会重启当前 kernel。
重启可能需要一分钟或更久。重启完成后,继续下一步。
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
认证你的 notebook 环境(仅 Colab)
如果你在 Google Colab 上运行本 notebook,请运行下面的 cell 来认证你的环境。
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()
设置 Google Cloud 项目信息并初始化 Vertex AI SDK
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
LOCATION = "us-central1" # @param {type:"string"}
if not PROJECT_ID or PROJECT_ID == "[your-project-id]":
raise ValueError("Please set your PROJECT_ID")
import vertexai
vertexai.init(project=PROJECT_ID, location=LOCATION)
设置评测指标
基于 LLM 的指标潜力巨大,但与人类评测者相比,有时会误判回复。为弥合这一差距,我们通过反馈循环把基于模型的指标与人类判断对齐。
定义 evaluator_llm
导入所需的 wrappers,并定义你的 evaluator LLM 和 embedder。
from ragas.llms import LangchainLLMWrapper
from ragas.embeddings import LangchainEmbeddingsWrapper
from langchain_google_vertexai import VertexAI, VertexAIEmbeddings
evaluator_llm = LangchainLLMWrapper(VertexAI(model_name="gemini-2.0-flash-001"))
evaluator_embeddings = LangchainEmbeddingsWrapper(VertexAIEmbeddings(model_name="text-embedding-004"))
Ragas 指标
Ragas 提供多种可以微调以与人类评测者对齐的基于模型的指标。作为演示,我们将使用 Aspect Critic 指标——一种用户定义的二元指标。更多细节请参阅 Aspect Critic 文档。
from ragas.metrics import AspectCritic
helpfulness_critic = AspectCritic(
name="helpfulness",
definition="Evaluate how helpful the assistant's response is to the user's query.",
llm=evaluator_llm
)
你可以运行下面的代码,预览将对 LLM 传入的 prompt(对齐之前):
print(helpfulness_critic.get_prompts()["single_turn_aspect_critic_prompt"].instruction)
输出
Evaluate the Input based on the criterial defined. Use only 'Yes' (1) and 'No' (0) as verdict.
Criteria Definition: Evaluate how helpful the assistant's response is to the user's query.
定义对齐分数
由于我们使用的是二元指标,我们将用 F1-score 来衡量对齐程度。不过,取决于你正在对齐的指标,你可以相应地修改这个函数,使用其他方法来衡量对齐。
from typing import List
from sklearn.metrics import f1_score
def alignment_score(human_score: List[float], llm_score: List[float]) -> float:
"""
Computes the alignment between human-annotated binary scores and LLM-generated binary scores
using the F1-score metric.
Args:
human_score (List[int]): Binary labels from human evaluation (0 or 1).
llm_score (List[int]): Binary labels from LLM predictions (0 or 1).
Returns:
float: The F1-score measuring alignment.
"""
return f1_score(human_score, llm_score)
准备你的数据集
process_hhh_dataset 函数准备来自 HHH 数据集 的数据,用于训练并对齐 LLM 评测器。为每个样例交替分配 0 和 1 分(1 表示 helpful,0 表示 non-helpful),指示更偏好哪一个回复。
import numpy as np
from datasets import load_dataset
from ragas import EvaluationDataset
def process_hhh_dataset(split: str = "helpful", total_count: int = 50):
dataset = load_dataset("HuggingFaceH4/hhh_alignment",split, split=f"test[:{total_count}]")
data = []
expert_scores = []
for idx, entry in enumerate(dataset):
# Extract input and target details
user_input = entry['input']
choices = entry['targets']['choices']
labels = entry['targets']['labels']
# Choose target based on whether the index is even or odd
if idx % 2 == 0:
target_label = 1
score = 1
else:
target_label = 0
score = 0
label_index = labels.index(target_label)
response = choices[label_index]
data.append({
'user_input': user_input,
'response': response,
})
expert_scores.append(score)
return EvaluationDataset.from_list(data), expert_scores
eval_dataset, expert_scores = process_hhh_dataset()
运行评测
定义好评测数据集和 helpfulness 指标后,你现在可以运行评测:
from ragas import evaluate
results = evaluate(eval_dataset, metrics=[helpfulness_critic])
Evaluating: 100%|██████████| 50/50 [00:00<?, ?it/s]
这次初始运行会突出基于 LLM 的评测器中存在的不对齐程度,后续训练将解决这一问题。
接下来,把该指标的表现与专家分数做基准比较:
human_score = expert_scores
llm_score = results.to_pandas()["helpfulness"].values
initial_score = alignment_score(human_score, llm_score)
initial_score
输出
0.8076923076923077
审阅与标注
现在你已经得到评测结果,是时候审阅并标注它们了。正如博客 Aligning LLM as judge with human evaluators 中所讨论的,收集详细反馈对于弥合基于 LLM 的评测与人类评测之间的差距至关重要。至少标注 15–20 个样例,以捕捉指标可能不对齐的多样场景。
这里是上面例子的一份示例标注。你可以下载并使用它。
训练与对齐
下一步是用标注样例训练你的指标。这一训练过程采用无梯度的 prompt 优化方法,根据标注反馈同时调整指令和 few-shot 演示。
from ragas.config import InstructionConfig, DemonstrationConfig
demo_config = DemonstrationConfig(embedding=evaluator_embeddings)
inst_config = InstructionConfig(llm=evaluator_llm)
helpfulness_critic.train(
path="annotated_data.json",
instruction_config=inst_config,
demonstration_config=demo_config,
)
Overall Progress: 100%|██████████| 170/170 [00:00<?, ?it/s]
Few-shot examples [single_turn_aspect_critic_prompt]: 100%|██████████| 16/16 [00:00<?, ?it/s]
训练之后,审阅已针对该指标优化过的更新指令:
print(helpfulness_critic.get_prompts()["single_turn_aspect_critic_prompt"].instruction)
输出
You are provided with a user input and an assistant/model response. Your task is to evaluate the quality of the response based on how well it addresses the user input, considering all requests and constraints. Assign a score/verdict of 1 if the response is helpful, appropriate, and effective, and 0 if it is not. A good response should be accurate, complete, relevant, and provide a tangible improvement or solution, without omitting key information. Provide a brief explanation for your score/verdict.
重新评测
现在你的指标已与人类反馈对齐,在数据集上重新运行评测。这一步让你能够为改进建立基准,并量化对齐过程在多大程度上增强了指标的可靠性。
from ragas.llms import LangchainLLMWrapper
from ragas.embeddings import LangchainEmbeddingsWrapper
from langchain_google_vertexai import VertexAI, VertexAIEmbeddings
evaluator_llm = LangchainLLMWrapper(VertexAI(model_name="gemini-pro"))
evaluator_embeddings = LangchainEmbeddingsWrapper(VertexAIEmbeddings(model_name="text-embedding-004"))
from ragas import evaluate
results2 = evaluate(eval_dataset, metrics=[helpfulness_critic])
Evaluating: 100%|██████████| 50/50 [00:00<?, ?it/s]
把更新后的结果与专家分数做基准比较:
human_score = expert_scores
llm_score = results2.to_pandas()["helpfulness"].values
new_score = alignment_score(human_score, llm_score)
new_score
输出
0.8444444444444444
查看本系列其他教程:
- Ragas with Vertex AI:学习如何将 Vertex AI 模型与 Ragas 一起使用,以评测你的 LLM 工作流。
- Model Comparison:用 Ragas 指标比较 VertexAI 提供的模型在基于 RAG 的问答任务上的表现。