Build a Lightweight LLM Evaluation Harness in Python
TL;DR · AI 摘要
Build a Lightweight LLM Evaluation Harness in Python - MachineLearningMastery.com Build a Lightweight LLM Evaluation Har...
核心要点
- 主题聚焦:Build a Lightweight LLM Evaluation Harness in Py
- 来源:Machine Learning Mastery,建议结合原文判断细节。
- AI 分析暂不可用,本条为保底评分与摘要。
在Python中构建轻量级的LLM评估框架 - MachineLearningMastery.com
在Python中构建轻量级的LLM评估框架
作者:
Iván Palomares Carrascosa
于
2026年11月29日
分类:
语言模型
0
分享
文章
在本文中,你将学习如何用Python构建一个轻量级、可复用的LLM评估框架,该框架结合精确匹配评分、LLM作为裁判以及版本化回归跟踪,以捕捉提示回归问题。
我们将涵盖的主题包括:
- 如何使用归一化精确匹配评分器对票务路由等确定性任务进行评分。
- 如何使用基于评分标准的LLM作为裁判对开放式响应进行评分,并返回结构化的Pydantic输出。
- 如何记录每个提示版本的结果,并逐个案例进行比较,以检测总体通过率可能隐藏的回归问题。
介绍
当团队需要评估传递给LLM的提示时,通常采用"人工检查"的方式:他们在游乐场环境中运行几个示例,同时调整系统指令,选择看起来更好的那个,然后部署。这乍看似乎有效,但细微的措辞变化可能会悄无声息地破坏几天前通过的案例。
好消息是:我们不需要重型的MLOps堆栈或可观测性平台就能使这个评估过程更加稳健。本文将指导你通过不到150行Python代码构建一个可复用的评估框架,该框架结合多种指标:
- 对于实体提取或分类等确定性任务,我们使用精确匹配(Exact-Match,EM)评分。
- 对于措辞多样化的开放式响应生成,我们采用基于评分标准的LLM作为裁判。
- 为了捕捉连续提示版本中任何从通过变为失败的情况,我们将使用版本化回归跟踪。
设置
本文附带的代码示例(一个轻量级LLM评估框架)可以直接复制并在Python笔记本环境中运行,例如Colab。它运行在Gemini API的免费层级上,还包含一个内置的"模拟模式",让你可以在不创建和使用自己的API密钥的情况下测试框架。首先,让我们安装一些必要的包:
安装依赖 !pip install -q google-genai pydantic
1
2
安装依赖
!
pip
install
-
q
genai
pydantic
接下来请注意我们使用 USE_MOCK_LLM=True 来通过模拟输出即时运行此代码。要免费调用Gemini LLM,从Google AI Studio获取免费API密钥,在Google Colab中将其添加为新秘密(左侧菜单的密钥图标)命名为 GEMINI_API_KEY,并设置 USE_MOCK_LLM=False 。
设置客户端和模型包装器 import json import os import re from datetime import datetime, timezone import pandas as pd from pydantic import BaseModel, Field pd.set_option("display.max_colwidth", None) # 如果之后将GEMINI_API_KEY添加到Colab Secrets,请设置为False USE_MOCK_LLM = True MODEL_NAME = "gemini-2.5-flash" client = None if not USE_MOCK_LLM: from google import genai from google.genai import types try: from google.colab import userdata api_key = userdata.get("GEMINI_API_KEY") except Exception: api_key = os.getenv("GEMINI_API_KEY") if not api_key: raise ValueError("将GEMINI_API_KEY添加到Colab Secrets或设置USE_MOCK_LLM = True。") client = genai.Client(api_key=api_key)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
设置客户端和模型包装器
import
json
os
re
from
datetime
,
timezone
/
pandas
as
pd
BaseModel
Field
.
set_option
(
"display.max_colwidth"
None
)
如果之后将 GEMINI_API_KEY 添加到 Colab Secrets,请设置为 False
USE_MOCK_LLM
=
True
MODEL_NAME
"gemini-2.5-flash"
client
if
not
:
types
try
colab
userdata
api_key
get
"GEMINI_API_KEY"
except
Exception
getenv
raise
ValueError
"将 GEMINI_API_KEY 添加到 Colab Secrets 或设置 USE_MOCK_LLM = True."
LLM 评估框架分步实现
我们 LLM 评估框架的第一个构建模块是一个包装函数,该函数将整体框架与模型调用解耦。第三个参数 version_tag 表示通过多次模型调用测试的特定提示或使用场景的版本。
为了使代码易于访问并帮助读者理解评估框架的原理,我们默认使用一组模拟的 LLM 输出——如前所述,要使用真实的生成 LLM 输出,您需要使用自己的 Gemini API 密钥并执行模型调用。我的主要目的是让您学习构建框架过程中需要考虑的关键步骤和要素:
def call_llm(system_prompt: str, user_input: str, version_tag: str = "v1") -> str: """调用目标 LLM(或返回确定性的模拟输出以进行离线测试)。""" if USE_MOCK_LLM: mock_outputs = { "v1_baseline": { "My invoice #4021 charged me twice this month.": "Category: BILLING.", "The mobile app crashes every time I tap 'Export PDF'.": "BUG_REPORT", "Cancel my plan immediately, I'm frustrated with the downtime.": ( "Sorry to hear that. You can cancel in Settings." ), "Can I switch from monthly to annual billing mid-cycle?": ( "Yes! Go to Billing > Plan to switch. We prorate your remaining days automatically." ), }, "v2_strict": { "My invoice #4021 charged me twice this month.": "BILLING", "The mobile app crashes every time I tap 'Export PDF'.": "BUG_REPORT", "Cancel my plan immediately, I'm frustrated with the downtime.": ( "I'm really sorry about the downtime. I can help you cancel right away—please " "confirm your account email, or go to Settings > Subscription > Cancel Plan." ), "Can I switch from monthly to annual billing mid-cycle?": ( "BILLING" # 模拟回归:严格的标签指令渗入开放式回复 ), }, } return mock_outputs.get(version_tag, {}).get(user_input, "UNKNOWN") response = client.models.generate_content( model=MODEL_NAME, contents=user_input, config=types.GenerateContentConfig( system_instruction=system_prompt, temperature=0.0, ), ) return response.text.strip()
29
30
31
32
33
34
35
36
37
def
call_llm
system_prompt
str
user_input
version_tag
"v1"
->
""
"调用目标 LLM(或返回确定性的模拟输出以进行离线测试)。"
mock_outputs
{
"v1_baseline"
"My invoice #4021 charged me twice this month."
"Category: BILLING."
"The mobile app crashes every time I tap 'Export PDF'."
"BUG_REPORT"
"Cancel my plan immediately, I'm frustrated with the downtime."
"Sorry to hear that. You can cancel in Settings."
"Can I switch from monthly to annual billing mid-cycle?"
"Yes! Go to Billing > Plan to switch. We prorate your remaining days automatically."
}
"v2_strict"
"BILLING"
"I'm really sorry about the downtime. I can help you cancel right away—please "
"confirm your account email, or go to Settings > Subscription > Cancel Plan."
模拟回归:严格的标签指令渗入开放式回复
return
"UNKNOWN"
response
models
generate_content
model
contents
config
GenerateContentConfig
system_instruction
temperature
0.0
text
strip
重要的是,将温度设置为0.0有助于尽可能保持评估运行的确定性,避免不同运行之间的噪声,使评分变化反映提示修改而非随机采样。
接下来,为了构建黄金测试数据集,我们实际上不需要数百或数千个示例,只要有几个高信号的示例即可。我们的示例集混合了两种类型的任务:需要精确标签(exact_match)的工单路由,以及事实和语气最重要的回复(rubric)。
定义黄金测试数据集 TEST_CASES = [ { "id": "tc_01_billing_route", "task_type": "exact_match", "input": "My invoice #4021 charged me twice this month.", "expected": "BILLING", }, { "id": "tc_02_bug_route", "task_type": "exact_match", "input": "The mobile app crashes every time I tap 'Export PDF'.", "expected": "BUG_REPORT", }, { "id": "tc_03_angry_cancel", "task_type": "rubric", "input": "Cancel my plan immediately, I'm frustrated with the downtime.", "expected": ( "1. Empathetically acknowledges the user's frustration about downtime. " "2. Gives clear next steps to cancel without being pushy or defensive." ), }, { "id": "tc_04_plan_switch", "task_type": "rubric", "input": "Can I switch from monthly to annual billing mid-cycle?", "expected": ( "1. Answers the question directly in full sentences. " "2. Mentions where to change the plan or how billing adjustment/proration works." ), }, ]
定义黄金测试数据集
TEST_CASES
[
"id"
"tc_01_billing_route"
"task_type"
"exact_match"
"input"
"expected"
"tc_02_bug_route"
"tc_03_angry_cancel"
"rubric"
"1. Empathetically acknowledges the user's frustration about downtime. "
"2. Gives clear next steps to cancel without being pushy or defensive."
"tc_04_plan_switch"
"1. Answers the question directly in full sentences. "
"2. Mentions where to change the plan or how billing adjustment/proration works."
]
现在开始实现评估框架的第一个主要支柱:确定性精确匹配评分器。这是一种廉价且快速的方法,旨在捕捉如Category: BILLING 这样的输出。
精确匹配评分器 def normalize_text(text: str) -> str: text = text.strip().upper() text = re.sub(r"[^\w\s]", "", text) return re.sub(r"\s+", " ", text) def score_exact_match(output: str, expected: str) -> dict: passed = normalize_text(output) == normalize_text(expected) return { "score": 5 if passed else 1, "passed": passed, "reasoning": "Exact match" if passed else f"Expected '{expected}', got '{output}'", }
精确匹配评分器
normalize_text
upper
sub
r
"[^\w\s]"
"\s+"
" "
score_exact_match
output
expected
dict
passed
==
"score"
else
"passed"
"reasoning"
"Exact match"
f
"Expected '{expected}', got '{output}'"
精确匹配评分器返回5或1,使所有评分器保持在1-5的相同评分尺度上,这与我们接下来要添加的基于评分标准的LLM评委使用的尺度一致,因此在汇总所有指标的评分时不需要归一化逻辑。
与此同时,我们不再使用字符串匹配来评估开放性问题的回答,而是将用户提示、模型响应和评分标准传递给一个评判模型。这迫使评判模型返回符合Pydantic schema的JSON结构,包含1-5的评分、一个表示测试是否通过的布尔标志,以及一个简短的推理字符串。在此阶段结构化模型输出非常重要,因为它可以避免我们编写基于复杂正则表达式的脆弱解析器:
基于评分标准的LLM作为评判者的评分器类
class JudgeVerdict(BaseModel): score: int = Field(ge=1, le=5, description="从1(差)到5(满足所有评分标准)的质量评分") passed: bool = Field(description="仅当评分是4或5时为True,否则为False") reasoning: str = Field(description="基于评分标准的一句合理说明")
JUDGE_PROMPT_TEMPLATE = """您是一个严格的问答评估者。根据评分标准对助手的响应进行评分。 用户输入:{user_input} 助手响应:{output} 评分标准:{rubric} 评分指南:
- 5:完全满足所有评分标准要求。
- 4:满足要求但存在轻微措辞缺陷。
- 3:部分满足要求;遗漏关键细节。
- 1-2:未满足要求、格式错误或无帮助。
仅当评分是4或5时设置passed=true。"""
def score_with_judge(user_input: str, output: str, rubric: str) -> dict: if USE_MOCK_LLM:
模拟模式下的简单确定性法官模拟
if len(output.split()) < 3: return { "score": 1, "passed": False, "reasoning": "输出只是一个裸标签,而不是有帮助的答案。", } if "downtime" in rubric.lower() and "downtime" not in output.lower(): return { "score": 2, "passed": False, "reasoning": "未承认用户对停机时间的挫败感。", } return { "score": 5, "passed": True, "reasoning": "明确且简洁地满足所有评分标准。", } prompt = JUDGE_PROMPT_TEMPLATE.format( user_input=user_input, output=output, rubric=rubric, ) response = client.models.generate_content( model=MODEL_NAME, contents=prompt, config=types.GenerateContentConfig( temperature=0.0, response_mime_type="application/json", response_schema=JudgeVerdict, ), ) verdict = JudgeVerdict.model_validate_json(response.text) return verdict.model_dump()
带本地 JSON 历史记录的评估运行器
HISTORY_FILE = "eval_history.json"
def run_eval(prompt_version: str, system_prompt: str, test_cases: list) -> pd.DataFrame: rows = [] for case in test_cases: output = call_llm(system_prompt, case["input"], version_tag=prompt_version) if case["task_type"] == "exact_match": result = score_exact_match(output, case["expected"]) else: result = score_with_judge(case["input"], output, case["expected"]) rows.append({ "id": case["id"], "task_type": case["task_type"], "output": output, "score": result["score"], "passed": result["passed"], "reasoning": result["reasoning"], }) df = pd.DataFrame(rows) pass_rate = df["passed"].mean() * 100 avg_score = df["score"].mean()
加载现有历史记录并保存当前版本快照
history = {} if os.path.exists(HISTORY_FILE): with open(HISTORY_FILE, "r") as f: history = json.load(f) history[prompt_version] = { "timestamp": datetime.now(timezone.utc).isoformat(), "system_prompt": system_prompt, "pass_rate": round(pass_rate, 1), "avg_score": round(avg_score, 2), "results": rows, } with open(HISTORY_FILE, "w") as f: json.dump(history, f, indent=2) print(f"[{prompt_version}] Pass Rate: {pass_rate:.1f}% | Avg Score: {avg_score:.2f}/5.00") return df
通过框架运行 v1 和 v2 提示词
PROMPT_V1 = """You are a customer support assistant. If the user reports a bug or billing error, classify it as BUG_REPORT or BILLING. Otherwise, answer their question briefly.""" PROMPT_V2 = """You are a customer support assistant. Rule 1: For ticket routing (billing errors or bug reports), output ONLY the single label BILLING or BUG_REPORT with no extra words. Rule 2: For cancellations, acknowledge the user's frustration empathetically and provide clear steps. Rule 3: For general questions, answer clearly in full sentences."""
df_v1 = run_eval("v1_baseline", PROMPT_V1, TEST_CASES) display(df_v1[["id", "task_type", "score", "passed", "reasoning"]]) print("\n" + "-" * 60 + "\n") df_v2 = run_eval("v2_strict", PROMPT_V2, TEST_CASES) display(df_v2[["id", "task_type", "score", "passed", "reasoning"]])
规则 1:对于工单路由(账单错误或错误报告),仅输出单个标签 BILLING 或 BUG_REPORT,不添加其他任何文字。
规则 2:对于取消请求,共情地承认用户的挫败感并提供明确步骤。
规则 3:对于一般性问题,用完整句子清晰作答。"
df_v1
display
"\n"
+
"-"
df_v2
让我们看看评估结果:
[v1_baseline] 通过率:50.0% | 平均得分:3.25/5.00 id | 任务类型 | 得分 | 是否通过 | 评估依据 0 | tc_01_billing_route | exact_match | 1 | False | 预期 'BILLING',但得到 'Category: BILLING.' 1 | tc_02_bug_route | exact_match | 5 | True | 完全匹配 2 | tc_03_angry_cancel | rubric | 2 | False | 未承认用户对停机问题的挫败感 3 | tc_04_plan_switch | rubric | 5 | True | 清晰简洁地满足所有评估标准
[v2_strict] 通过率:75.0% | 平均得分:4.00/5.00 id | 任务类型 | 得分 | 是否通过 | 评估依据 0 | tc_01_billing_route | exact_match | 5 | True | 完全匹配 1 | tc_02_bug_route | exact_match | 5 | True | 完全匹配 2 | tc_03_angry_cancel | rubric | 5 | True | 清晰简洁地满足所有评估标准 3 | tc_04_plan_switch | rubric | 1 | False | 输出仅为裸标签,而非有帮助的回答
v1_baseline
通过率
50.0%
|
平均得分
3.25
/
5.00
id
任务类型
tc_01_billing_route
exact_match
'BILLING'
得到
'Category: BILLING.'
tc_02_bug_route
tc_03_angry_cancel
未承认
用户
的
挫败感
关于
停机
tc_04_plan_switch
满足
所有
标准
清晰
简洁
--
v2_strict
75.0
4.00
输出
仅为
一个
裸标签
而非
有帮助的
回答
尽管代码使用了模拟示例以避免API成本,但失败模式是现实的:tc_04_plan_switch对开放式账单问题的回应仅返回了裸标签。这是提示工程中经典的、易于识别的错误。总体而言,通过率从50%提升至75%可能看起来像是值得庆祝的成果。
最后,我们添加回归跟踪器:一个函数,用于比较评估历史日志中的两次保存运行,并明确标记状态变化:
每个用例的回归跟踪器
def compare_versions(base_version: str, new_version: str, history_file: str = HISTORY_FILE) -> pd.DataFrame: with open(history_file, "r") as f: history = json.load(f) base_run = history[base_version] new_run = history[new_version] base_df = pd.DataFrame(base_run["results"]).set_index("id") new_df = pd.DataFrame(new_run["results"]).set_index("id") comparison = [] for tc_id in base_df.index: b_pass = bool(base_df.loc[tc_id, "passed"]) n_pass = bool(new_df.loc[tc_id, "passed"]) b_score = int(base_df.loc[tc_id, "score"]) n_score = int(new_df.loc[tc_id, "score"]) if b_pass and not n_pass: status = "REGRESSION (PASS -> FAIL)" elif not b_pass and n_pass: status = "FIXED (FAIL -> PASS)" elif b_pass and n_pass: status = "STILL PASSING" else: status = "STILL FAILING" comparison.append({ "id": tc_id, "status": status, f"{base_version}_score": b_score, f"{new_version}_score": n_score, "score_delta": n_score - b_score, "new_reasoning": new_df.loc[tc_id, "reasoning"], }) diff_df = pd.DataFrame(comparison) pass_delta = new_run["pass_rate"] - base_run["pass_rate"] regressions = (diff_df["status"] == "REGRESSION (PASS -> FAIL)").sum() print(f"Comparison: {base_version} -> {new_version}") print(f"Pass Rate Delta: {pass_delta:+.1f}% ({base_run['pass_rate']}% -> {new_run['pass_rate']}%)") print(f"Regressions Detected: {regressions}\n") return diff_df
diff_df = compare_versions("v1_baseline", "v2_strict") display(diff_df)
每个用例的回归跟踪器
compare_versions
base_version
new_version
base_run
new_run
base_df
set_index
new_df
comparison
tc_id
index
b_pass
loc
n_pass
b_score
n_score
status
"REGRESSION (PASS -> FAIL)"
elif
"FIXED (FAIL -> PASS)"
"STILL PASSING"
"STILL FAILING"
"status"
"{base_version}_score"
"{new_version}_score"
"score_delta"
"new_reasoning"
diff_df
pass_delta
regressions
sum
"Comparison: {base_version} -> {new_version}"
"Pass Rate Delta: {pass_delta:+.1f}% ({base_run['pass_rate']}% -> {new_run['pass_rate']}%)"
"Regressions Detected: {regressions}\n"
输出:
Comparison: v1_baseline -> v2_strict Pass Rate Delta: +25.0% (50.0% -> 75.0%) Regressions Detected: 1 id status v1_baseline_score v2_strict_score score_delta new_reasoning 0 tc_01_billing_route FIXED (FAIL -> PASS) 1 5 4 Exact match 1 tc_02_bug_route STILL PASSING 5 5 0 Exact match 2 tc_03_angry_cancel FIXED (FAIL -> PASS) 2 5 3 Meets all rubric criteria clearly and concisely. 3 tc_04_plan_switch REGRESSION (PASS -> FAIL) 5 1 -4 Output is just a bare label instead of a helpful answer.
Delta
25.0
Detected
v1_baseline_score
v2_strict_score
score_delta
new
FIXED
FAIL
STILL
PASSING
REGRESSION
乍看之下,第二个更严格的版本似乎占优,但逐个用例的分析显示这个结论可能是个错误。有两个用例从失败变为通过,这是真正的改进。然而,有一个用例的评分从5分降至1分,即更严格的规则影响到了一个关于计费的开放性问题,导致模型仅返回了一个裸标签,而没有给出预期的实际答案。
下一步
The lightweight LLM evaluation harness shown throughout this article is designed to be incrementally expanded into a production-ready workflow. Ways to do this include adding an automated CI gate — a checkpoint that runs the tests before updated prompt or model versions go live — turning real bugs into new test cases to ensure the same errors don’t quietly return, and tracking cost and speed to avoid paying twice as much for a marginal improvement.
- Building a Custom LLM Evaluation Harness in Python…
- How To Create an Algorithm Test Harness From Scratch…
- Creating a Qwen-Powered Lightweight Personal Assistant
- Build Semantic Search with LLM Embeddings
- Build an Inference Cache to Save Costs in…
- The Complete Guide to LLM Evaluation
/.entry /entry