跳到主要内容

评估提示

提示词是 LLM(大语言模型)应用和 AI 智能体的核心组件。然而,迭代提示词往往具有挑战性,因为很难判断新的提示词是否优于旧版本。MLflow 提供了一个框架,用于系统地评估提示词模板并跟踪其性能变化。MLflow 还可以利用基于评估数据改进提示词的算法来自动优化提示词。请参阅优化指南以开始使用。

Prompt Evaluation

工作流

创建提示词模板

在 MLflow 提示词注册中心 (Prompt Registry) 中定义并注册您的提示词模板,以实现版本控制和便捷访问。

准备评估数据集

创建包含输入和预期结果的测试用例,以便系统地评估提示词性能。

定义响应生成的包装函数

将您的提示词封装在一个函数中,该函数接收数据集输入并使用您的模型生成响应。

定义评估评分器

设置内置和自定义评分器,以衡量质量、准确性以及特定任务的标准。

运行评估

执行评估并在 MLflow UI 中查看结果,以分析性能并进行迭代。

示例:评估提示词模板

前提条件

首先,通过运行以下命令安装所需包

bash
pip install --upgrade 'mlflow>=3.3' openai

MLflow 将评估结果存储在跟踪服务器中。通过以下任一方法将您的本地环境连接到跟踪服务器。

安装 Python 包管理器 uv(该管理器还将安装 uvx 命令,以便在不安装的情况下调用 Python 工具)。

在本地启动 MLflow 服务器。

shell
uvx mlflow server
信息

请参阅 安全安装 (Secure Installs),了解如何使用哈希检查和上传时过滤功能将依赖项固定到已知良好版本。

第 1 步:创建提示词模板

让我们定义一个简单的提示词模板来进行评估。我们使用 MLflow 提示词注册中心来保存并进行版本控制,但这对于评估而言是可选的。

python
import mlflow

# Define prompt templates. MLflow supports both text and chat format prompt templates.
PROMPT_V1 = [
{
"role": "system",
"content": "You are a helpful assistant. Answer the following question.",
},
{
"role": "user",
# Use double curly braces to indicate variables.
"content": "Question: {{question}}",
},
]

# Register the prompt template to the MLflow Prompt Registry for version control
# and convenience of loading the prompt template. This is optional.
mlflow.genai.register_prompt(
name="qa_prompt",
template=PROMPT_V1,
commit_message="Initial prompt",
)

第 2 步:创建评估数据集

评估数据集定义为一个字典列表,每个字典包含 inputs(输入)、expectations(预期)以及一个可选的 tags(标签)字段。

python
eval_dataset = [
{
"inputs": {"question": "What causes rain?"},
"expectations": {"key_concepts": ["evaporation", "condensation", "precipitation"]},
"tags": {"topic": "weather"},
},
{
"inputs": {"question": "Explain the difference between AI and ML"},
"expectations": {"key_concepts": ["artificial intelligence", "machine learning", "subset"]},
"tags": {"topic": "technology"},
},
{
"inputs": {"question": "How do vaccines work?"},
"expectations": {"key_concepts": ["immune", "antibodies", "protection"]},
"tags": {"topic": "medicine"},
},
]

第 3 步:创建预测函数

现在,将提示词模板封装在一个简单的函数中,该函数接收一个问题并使用提示词模板生成响应。重要提示:该函数必须接收数据集中 inputs 字段使用的关键字参数。 因此,我们在此使用 question 作为函数的参数。

python
from openai import OpenAI

client = OpenAI()


@mlflow.trace
def predict_fn(question: str) -> str:
prompt = mlflow.genai.load_prompt("prompts:/qa_prompt@latest")
rendered_prompt = prompt.format(question=question)

response = client.chat.completions.create(model="gpt-4.1-mini", messages=rendered_prompt)
return response.choices[0].message.content

第 4 步:定义特定任务的评分器

最后,让我们定义几个评分器来确定评估标准。这里我们使用两种类型的评分器:

  • 用于评估响应定性方面的内置 LLM 评分器。
  • 用于评估关键概念覆盖率的自定义启发式评分器。
python
from mlflow.entities import Feedback
from mlflow.genai import scorer
from mlflow.genai.scorers import Guidelines

# Define LLM scorers
is_concise = Guidelines(
name="is_concise", guidelines="The response should be concise and to the point."
)
is_professional = Guidelines(
name="is_professional", guidelines="The response should be in professional tone."
)


# Evaluate the coverage of the key concepts using custom scorer
@scorer
def concept_coverage(outputs: str, expectations: dict) -> Feedback:
concepts = set(expectations.get("key_concepts", []))
included = {c for c in concepts if c.lower() in outputs.lower()}
return Feedback(
value=len(included) / len(concepts),
rationale=(
f"Included {len(included)} out of {len(concepts)} concepts. Missing: {concepts - included}"
),
)
提示

LLM 评分器默认使用 OpenAI 的 GPT 4.1-mini 模型。您可以通过将 model 参数传递给评分器构造函数来使用其他模型。

第 5 步:运行评估

现在我们准备好运行评估了!

python
mlflow.genai.evaluate(
data=eval_dataset,
predict_fn=predict_fn,
scorers=[is_concise, is_professional, concept_coverage],
)

评估完成后,在浏览器中打开 MLflow UI,然后导航到实验页面。你应该会看到 MLflow 创建了一个新的 Run 并记录了评估结果。

Prompt Evaluation

点击结果中的每一行,您可以打开追踪记录 (trace),查看详细的评分和依据。

Prompt Evaluation

提示词迭代

提示词评估是一个迭代过程。您可以注册新的提示词版本,再次运行相同的评估,并比较评估结果。提示词注册中心会跟踪版本变更,以及提示词版本与评估结果之间的血缘关系。

python
# Define V2 prompt template
PROMPT_V2 = [
{
"role": "system",
"content": "You are a helpful assistant. Answer the following question in three sentences.",
},
{"role": "user", "content": "Question: {{question}}"},
]

mlflow.genai.register_prompt(name="qa_prompt", template=PROMPT_V2)

# Run the same evaluation again.
# MLflow automatically loads the latest prompt template via the `@latest` alias.
mlflow.genai.evaluate(
data=eval_dataset,
predict_fn=predict_fn,
scorers=[is_concise, is_professional, concept_coverage],
)

比较评估结果

当您有多次评估运行时,可以并排比较结果以分析性能变化。要查看比较视图,请打开其中一个运行的评估结果页面,然后从顶部的下拉菜单中选择另一个要比较的运行。

要查看比较视图,请打开其中一个运行的评估结果页面,并从顶部的下拉菜单中选择另一个运行进行比较。

Prompt Evaluation

MLflow 将加载两次运行的评估结果并显示比较视图。在此示例中,您可以看到整体简洁性评分提升了 33%,但概念覆盖率下降了 11%。每一行中的小箭头 ↗️/↘️ 指示了变化的来源。

Prompt Evaluation

后续步骤