LLM 作为评判者模式
了解如何提示能力较强的 LLM,依据正确性、实用性和语气等标准为输出评分或进行比较,以及为什么这种方式比人工评估更易扩展。
LLM 作为评判者模式 是 CoddyKit 上的免费 AI Engineering Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Engineering Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Engineering Academy 课程共包含 4 节课。
为什么必须进行自动化评估
人工评估 LLM 输出既缓慢又昂贵。一个人工评分团队每周只能评估几百条输出,而生产系统每天会生成数千条输出。LLM 评审使用强大的语言模型大规模评估其他 LLM 的输出,从而实现自动化回归测试和持续质量监控,而无需雇佣一支庞大的标注团队。
核心理念:一个 LLM 评估另一个 LLM
在 LLM 评审中,您会将定义评估标准的系统提示词、原始问题、模型的答案,以及可选的参考答案发送给评审模型(通常是 GPT-4o 或 Claude)。评审模型会返回数值评分、标签或排名。之所以可行,是因为先进模型已经充分理解正确性、有用性和连贯性等质量概念。
JUDGE_SYSTEM_PROMPT = '''
You are an expert evaluator of AI-generated responses.
Given a question and an AI-generated answer, score the answer on:
- Correctness (0-5): Is the information factually accurate?
- Completeness (0-5): Does it fully address the question?
- Clarity (0-5): Is it easy to understand?
Return a JSON object with scores and a brief rationale.
'''编写评审提示词
优秀的评审提示词会指定带有评分定义的明确评分标准,而不是使用“好”或“坏”这类模糊词语。请具体定义每个标准中 5 分、3 分和 1 分分别意味着什么。提供问题、待评审的答案,以及可选的参考答案。要求模型先说明理由,再给出评分(思维链),以减少随意评分。
def build_judge_prompt(question: str, answer: str, reference: str = None) -> str:
ref_section = f'Reference answer:\n{reference}\n\n' if reference else ''
return f'''
Question: {question}
{ref_section}Answer to evaluate:
{answer}
Score this answer on correctness (1-5) where:
5 = Completely accurate, no factual errors
3 = Mostly accurate with minor errors
1 = Contains significant factual errors
First explain your reasoning, then provide the score as JSON:
{{"correctness": <1-5>, "rationale": "..."}}
'''调用评审模型
使用您的评估提示词调用评审模型。解析 JSON 响应以提取评分。请始终使用结构化输出或 JSON 模式,确保评审模型返回可解析的数据。让同一个模型既作为待测试系统又作为评审模型可能会引入偏差——请优先使用不同的模型,或者至少为评审模型使用不同的配置。
from pydantic import BaseModel
import instructor
from openai import OpenAI
class JudgeScore(BaseModel):
correctness: int
completeness: int
clarity: int
rationale: str
judge_client = instructor.from_openai(OpenAI())
def judge(question: str, answer: str) -> JudgeScore:
return judge_client.chat.completions.create(
model='gpt-4o', # Use stronger judge than the model being tested
response_model=JudgeScore,
messages=[
{'role': 'system', 'content': JUDGE_SYSTEM_PROMPT},
{'role': 'user', 'content': build_judge_prompt(question, answer)}
]
)无参考评审与基于参考答案的评审
LLM 评审有两种模式。无参考评审要求评审模型在没有标准答案的情况下评估质量,适用于开放式聊天等不存在标准答案的场景。基于参考答案的评审会提供黄金标准答案,并询问模型的答案是否与其一致,更适合已知正确答案的事实问答。在拥有带标签的测试集时,请使用基于参考答案的评审。
# Reference-free: good for open-ended generation
judge_result = judge(question='What is machine learning?', answer=model_answer)
# Reference-based: better for factual QA
judge_result = judge(
question='What year was Python created?',
answer=model_answer,
reference='Python was created by Guido van Rossum and released in 1991.'
)控制评审偏差
LLM 评审模型存在一些已知偏差:它们偏好更长的答案(冗长偏差)、听起来更自信的答案,以及符合其训练数据风格的答案。请在评分标准中明确惩罚不必要的篇幅,以减轻冗长偏差。在成对比较中,通过随机决定哪个答案先出现,并对两种排列的评分取平均,来降低位置偏差。
# Anti-verbosity note in rubric:
ANTI_VERBOSITY_CLAUSE = '''
Note: A concise, accurate answer should score higher than a long,
rambling answer that happens to contain the correct information.
Do not reward length for its own sake.
'''
# Position-debiasing for pairwise comparison:
async def debiased_pairwise(q, a, b):
score_ab = await compare(q, answer_a=a, answer_b=b)
score_ba = await compare(q, answer_a=b, answer_b=a)
# A wins if it wins in both orderings
a_wins = (score_ab == 'A' and score_ba == 'B')
return 'A' if a_wins else 'B' if (score_ab == 'B' and score_ba == 'A') else 'tie'批量评估以提升速度
并行运行评审,以便快速评估大型测试集。借助 asyncio 和信号量,您每分钟可以评估数百条输出。请为评审调用单独保留速率限制预算(因为它们同样会消耗令牌),并考虑对不需要深度推理的标准使用更小但能力仍足够的评审模型,例如 GPT-4o-mini;将 GPT-4o 留给最关键的标准。
import asyncio
async def batch_judge(qa_pairs: list, concurrency: int = 20) -> list:
sem = asyncio.Semaphore(concurrency)
async def judge_one(item):
async with sem:
return await async_judge(item['question'], item['answer'])
return await asyncio.gather(
*[judge_one(item) for item in qa_pairs],
return_exceptions=True
)汇总评审评分
评估完测试集后,将评分汇总为统计摘要:平均值、中位数,以及评分高于质量阈值的响应百分比(例如正确性 ≥ 4)。比较不同模型版本或提示词变体之间的这些汇总指标。如果高于阈值的比例下降超过 5%,则应在部署新版本前触发审查。
import statistics
def summarize_judge_results(scores: list) -> dict:
correctness = [s.correctness for s in scores if isinstance(s, JudgeScore)]
return {
'n': len(correctness),
'mean_correctness': round(statistics.mean(correctness), 2),
'median_correctness': statistics.median(correctness),
'pct_above_4': round(100 * sum(1 for s in correctness if s >= 4) / len(correctness), 1)
}使用评审模型比较 LLM 版本
使用 LLM 评审来比较系统的两个版本,例如提示词修改前后的版本。在同一组测试问题上运行两个版本,评审所有输出,并计算胜率:版本 B 得分高于版本 A 的案例所占百分比。在 100 个以上样本中,超过 55% 的胜率通常具有足够的统计显著性,可以据此决定发布新版本。
async def ab_compare(test_questions: list, version_a, version_b) -> dict:
a_wins = b_wins = ties = 0
for q in test_questions:
answer_a = await version_a.answer(q)
answer_b = await version_b.answer(q)
winner = await debiased_pairwise(q, answer_a, answer_b)
if winner == 'A': a_wins += 1
elif winner == 'B': b_wins += 1
else: ties += 1
total = len(test_questions)
return {'a_win_rate': a_wins/total, 'b_win_rate': b_wins/total, 'tie_rate': ties/total}根据人工评分校准评审评分
在包含 50–200 个示例的校准集上,将评审评分与人工判断进行比较,以验证评审模型。计算评审评分与人工评分之间的皮尔逊相关系数。相关系数高于 0.7 表明评审模型可靠。如果相关性较低,请审查评审提示词,找出其与人工判断不一致的地方,并向评分标准中添加示例或说明。未经校准,切勿部署评审模型。
from scipy.stats import pearsonr
def calibrate_judge(human_scores: list, judge_scores: list) -> dict:
corr, p_value = pearsonr(human_scores, judge_scores)
mean_abs_error = sum(abs(h - j) for h, j in zip(human_scores, judge_scores)) / len(human_scores)
return {
'pearson_r': round(corr, 3),
'p_value': round(p_value, 4),
'mean_abs_error': round(mean_abs_error, 2),
'reliable': corr >= 0.7
}何时不应使用 LLM 评审
LLM 评审并不适用于所有评估场景。以下情况应避免使用:评估标准需要评审模型不具备的领域专业知识(例如医疗诊断准确性、法律合规性);需要具有法律依据的评估(必须进行人工审查);评估能力强于评审模型的模型(评审模型无法可靠地评估自己无法生成的输出);或者评估预算过于紧张,无法承担额外的 API 成本。在这些情况下,请使用人工评估或确定性指标。
# Appropriate uses of LLM-as-judge:
# YES: General helpfulness, clarity, tone, factual accuracy (general knowledge)
# YES: Code correctness for common languages
# YES: Translation quality comparison
# YES: Content safety classification
#
# NOT appropriate:
# NO: Medical/legal/financial accuracy (needs domain expert)
# NO: Evaluating GPT-4o with GPT-4o (same capability ceiling)
# NO: Formal compliance audits (non-deterministic judge)
# NO: Streaming quality at individual token level快速检查
测试您对 LLM 评审评估模式的理解。
课程回顾
在本课中,您学习了:LLM 评审使用强大的模型和明确的评分标准大规模评估质量;无参考模式和基于参考答案的模式适用于不同的评估场景;根据人工判断进行校准可以验证评审模型的可靠性,然后再将其用于生产环境。接下来,我们将实现逐点评估和成对评估策略。
用 AI 导师学习 Python — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 30
- 课程
- 120
常见问题解答
「LLM 作为评判者模式」课时是免费的吗?
是的 — 「LLM 作为评判者模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Engineering Academy 课程的其余内容,请升级到 CoddyKit PRO。 AI Engineering Academy 课程共包含 4 节课。
「LLM 作为评判者模式」这节课中我会学到什么?
了解如何提示能力较强的 LLM,依据正确性、实用性和语气等标准为输出评分或进行比较,以及为什么这种方式比人工评估更易扩展。 你通过在浏览器中直接运行的动手代码来练习 AI Engineering Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Engineering Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Engineering Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「LLM 作为评判者模式」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Engineering Academy 课中编写并运行代码吗?
能。每节 AI Engineering Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- LLM 作为评判者模式
- 逐项评估与成对评估
- 根据人工评估校准评判模型
- 构建持续评估流程