GenAI 评估快速入门
需要帮助设置评估? 试试 MLflow Assistant - 一个强大的 AI 助手,可以帮助您为项目设置评估。
本快速入门指南将引导您使用 MLflow 全面的评估框架来评估您的 GenAI 应用程序。 在不到 5 分钟的时间内,您将学习如何评估 LLM 输出、使用内置和自定义评估标准以及在 MLflow UI 中分析结果。

先决条件
根据您的 Python 环境,您可能希望通过运行以下命令来安装所需的包
pip install openai
本指南中的代码示例使用 OpenAI SDK; 但是,MLflow 的评估框架可与任何 LLM 提供商配合使用,包括 Anthropic、Google、Bedrock 等。
第一步:设置您的环境
MLflow 将评估结果存储在 MLflow 跟踪服务器中。
通过执行以下任一方法启动本地 MLflow 跟踪服务器。
- 本地 (uv)
- 本地 (pip)
- 本地 (docker)
Python 环境:Python 3.10+
通过 pip 安装 mlflow Python 包并在本地启动 MLflow 服务器。
pip install --upgrade 'mlflow[genai]'
mlflow server
MLflow 提供了一个 Docker Compose 文件,用于启动一个带有 PostgreSQL 数据库和 MinIO 服务器的本地 MLflow 服务器。
git clone --depth 1 --filter=blob:none --sparse https://github.com/mlflow/mlflow.git
cd mlflow
git sparse-checkout set docker-compose
cd docker-compose
cp .env.dev.example .env
docker compose up -d
有关更多详细信息(例如,覆盖默认环境变量),请参阅 说明。
第 2 步:创建评估脚本
创建一个名为 quickstart_eval.py 的文件。 该脚本将包含您的模拟代理、评估数据集、评分器和评估执行。 或者,您可以在 笔记本中运行它。
从环境设置开始
# quickstart_eval.py
import os
import mlflow
# Configure environment
os.environ["OPENAI_API_KEY"] = "your-api-key-here" # Replace with your API key
mlflow.set_experiment("GenAI Evaluation Quickstart")
第 3 步:定义模拟代理的预测函数
首先,我们需要创建一个接受问题并返回答案的预测函数。 在这里,我们使用 OpenAI 的 gpt-4o-mini 模型来生成答案,但如果您愿意,您可以使用任何其他 LLM 提供商。
将您的模拟代理实现添加到 quickstart_eval.py
from openai import OpenAI
client = OpenAI()
def my_agent(question: str) -> str:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "You are a helpful assistant. Answer questions concisely.",
},
{"role": "user", "content": question},
],
)
return response.choices[0].message.content
def qa_predict_fn(question: str) -> str:
"""Wrapper function for evaluation using ``my_agent``."""
return my_agent(question)
第 4 步:准备评估数据集
评估数据集是样本列表,每个样本都具有 inputs 和 expectations 字段。
inputs:对上述predict_fn函数的输入。 键必须与predict_fn函数的参数名称匹配。expectations:predict_fn函数的预期输出,即答案的真实值。
数据集可以是字典列表、pandas DataFrame、spark DataFrame。 在这里,我们为了简单起见使用字典列表。
# Define a simple Q&A dataset with questions and expected answers
eval_dataset = [
{
"inputs": {"question": "What is the capital of France?"},
"expectations": {"expected_response": "Paris"},
},
{
"inputs": {"question": "Who was the first person to build an airplane?"},
"expectations": {"expected_response": "Wright Brothers"},
},
{
"inputs": {"question": "Who wrote Romeo and Juliet?"},
"expectations": {"expected_response": "William Shakespeare"},
},
]
第 5 步:使用评分器定义评估标准
评分器是一个函数,它根据各种评估标准计算给定输入-输出对的分数。 您可以使用 MLflow 提供的内置评分器来评估常见评估标准,也可以创建自己的自定义评分器。
from mlflow.genai import scorer
from mlflow.genai.scorers import Correctness, Guidelines
@scorer
def is_concise(outputs: str) -> bool:
"""Evaluate if the answer is concise (less than 5 words)"""
return len(outputs.split()) <= 5
scorers = [
Correctness(),
Guidelines(name="is_english", guidelines="The answer must be in English"),
is_concise,
]
在这里我们使用三个评分器
- 正确性 (Correctness):使用数据集中 "expected_response" 字段评估答案是否在事实上正确。
- 指南 (Guidelines):评估答案是否满足给定的指南。
is_concise:使用 scorer 装饰器定义的自定义评分器,用于判断答案是否简洁(少于 5 个词)。
前两个评分器使用 LLM 来评估响应,这被称为“LLM 即裁判 (LLM-as-a-Judge)”。 这是一种强大的技术,用于评估响应的质量,因为它为复杂的语言任务提供了类似人类的评估,同时比人工评估更具可扩展性和成本效益。
评分器界面允许您以简单的方式为您的应用程序定义各种质量指标。 从简单的自然语言指南到具有完整评估逻辑控制的代码函数。
LLM 即裁判评分器(如 Correctness 和 Guidelines)默认使用的模型是 OpenAI gpt-4o-mini。 MLflow 通过内置适配器和 LiteLLM 支持所有主要的 LLM 提供商,如 Anthropic、Bedrock、Google、xAI 等。
为裁判模型使用不同模型提供商的示例
# Anthropic
Correctness(model="anthropic:/claude-sonnet-4-20250514")
# Bedrock
Correctness(model="bedrock:/anthropic.claude-sonnet-4-20250514")
# Google
# Run `pip install litellm` to use Google as the judge model
Correctness(model="gemini/gemini-2.5-flash")
# xAI
# Run `pip install litellm` to use xAI as the judge model
Correctness(model="xai/grok-2-latest")
第 6 步:运行评估
现在我们有了评估的所有三个组成部分:数据集、预测函数和评分器。 让我们运行评估!
# Run evaluation
if __name__ == "__main__":
results = mlflow.genai.evaluate(
data=eval_dataset,
predict_fn=qa_predict_fn,
scorers=scorers,
)
现在运行您的评估脚本
- uv
- Python
uv run --with openai,mlflow quickstart_eval.py
python quickstart_eval.py
完整脚本
以下是供参考的完整 quickstart_eval.py
查看完整脚本
# quickstart_eval.py
import os
import mlflow
from openai import OpenAI
from mlflow.genai import scorer
from mlflow.genai.scorers import Correctness, Guidelines
# Use different env variable when using a different LLM provider
os.environ["OPENAI_API_KEY"] = "your-api-key-here"
mlflow.set_experiment("GenAI Evaluation Quickstart")
# Your agent implementation
client = OpenAI()
def my_agent(question: str) -> str:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "You are a helpful assistant. Answer questions concisely.",
},
{"role": "user", "content": question},
],
)
return response.choices[0].message.content
# Wrapper function for evaluation
def qa_predict_fn(question: str) -> str:
return my_agent(question)
# Evaluation dataset
eval_dataset = [
{
"inputs": {"question": "What is the capital of France?"},
"expectations": {"expected_response": "Paris"},
},
{
"inputs": {"question": "Who was the first person to build an airplane?"},
"expectations": {"expected_response": "Wright Brothers"},
},
{
"inputs": {"question": "Who wrote Romeo and Juliet?"},
"expectations": {"expected_response": "William Shakespeare"},
},
]
# Scorers
@scorer
def is_concise(outputs: str) -> bool:
return len(outputs.split()) <= 5
scorers = [
Correctness(),
Guidelines(name="is_english", guidelines="The answer must be in English"),
is_concise,
]
# Run evaluation
if __name__ == "__main__":
results = mlflow.genai.evaluate(
data=eval_dataset,
predict_fn=qa_predict_fn,
scorers=scorers,
)
运行上述代码后,转到 MLflow UI 并导航到 "GenAI Evaluation Quickstart" 实验。 您将看到评估结果,其中包含每个评分器的详细指标。

通过单击表格中的每一行,您可以看到分数的详细基本原理和预测的跟踪。

您也可以比较评估运行。 点击(左侧的)"Evaluation runs" 菜单,选择您想与基线运行进行比较的运行。

总结
恭喜!您已成功
- ✅ 为您的应用程序设置了 MLflow GenAI 评估
- ✅ 使用内置评分器评估了问答应用程序
- ✅ 创建了自定义评估指南
- ✅ 学习了如何在 MLflow UI 中分析结果
MLflow 的评估框架提供了评估 GenAI 应用程序质量的全面工具,帮助您构建更可靠和有效的 AI 系统。