跳到主要内容

超越手动构建的 LLM 评判器:使用 MLflow 自动化构建领域特定的评估器

·10 分钟阅读
MLflow maintainers
MLflow 维护者

如果您尝试过评估 GenAI 应用,您就会知道通用的 LLM 裁判(judges)是不够的。您的客户支持机器人需要根据同理心和问题解决能力进行评估。您的代码生成器需要检查是否存在安全漏洞。您的医疗顾问需要领域特定的准确性检查。同时,将这些需求转化为自定义 LLM 裁判并非易事。裁判必须关注被评估的 GenAI 追踪(trace)的关键部分,并且其提示(prompt)需要进行调整,以捕捉人类专家的细微差别和偏好。这需要大量的努力,并且常常导致次优的裁判,最终会分散于构建有效的 GenAI 应用的主要目标。

在 MLflow 3.4 版本中,我们引入了 make_judge 方法,这是一个强大的新 API,用于创建 MLflow Scorers,这是该框架进行自动化评估的核心抽象。该 API 使您能够使用简单的指令以声明式的方式创建 scorer。使用 make_judge,您可以轻松构建理解您领域特定质量要求并自动与人类专家反馈对齐的裁判。

本文通过展示如何

  • 使用 make_judge 和简单的声明式指令创建自定义 scorer
  • 构建充当具有内置工具进行追踪内省(introspection)的代理(agents)的 scorer,从而无需复杂的提示或复杂的 span 解析逻辑即可执行复杂的评估任务
  • 自动将 scorer 与主题专家的偏好对齐,以随着时间的推移提高 scorer 的准确性

来展示 MLflow Scorers 的强大功能。为了说明新 API 的强大功能,我们将构建一个客户支持质量 scorer,展示它如何评估复杂的代理行为,并演示人类反馈如何使其更有效。MLflow 提供的内置 scorer 只是使用相同功能的预定义版本。一旦您理解了这一点,您就会看到 MLflow 的评估框架实际上有多么灵活和强大。

创建您的第一个 Scorer:客户支持评估器

让我们从一个实际示例开始。假设您正在构建一个客户支持聊天机器人。您需要一个 scorer 来评估响应是否真正有用,而不仅仅是语法正确。

首先,安装最新版本的 MLflow

pip install -U mlflow

现在让我们创建一个理解什么使支持响应变得良好的 scorer

from mlflow.genai.judges import make_judge

# Create a scorer for customer support quality
support_scorer = make_judge(
name="support_quality",
instructions=(
"Evaluate if the response in {{ outputs }} shows appropriate empathy "
"for the customer issue in {{ inputs }}.\n\n"
"Check if the response acknowledges the customer's frustration and "
"responds with understanding and care.\n"
"Rate as: 'empathetic' or 'not empathetic'"
),
model="openai:/gpt-4o"
)

这里的关键在于,我们使用简单的声明式指令来定义一个 scorer,这些指令描述了 *要* 评估的内容,而不是 *如何* 评估。您不需要复杂的评分函数或正则表达式模式。只需描述您正在寻找的内容。此 scorer 现在是一个可以在 MLflow 生态系统任何地方使用的可重用评估组件。

让我们看看我们的 scorer 如何处理一个糟糕的支持响应

# Test the scorer on a support interaction
result = support_scorer(
inputs={"issue": "Can't reset my password"},
outputs={"response": "Have you tried turning it off and on again?"}
)

print(f"Rating: {result.value}")
print(f"Reasoning: {result.rationale}")

输出

Rating: not empathetic
Reasoning: The response completely ignores the customer's frustration with
the password reset issue and provides an irrelevant, dismissive suggestion
that shows no understanding of their problem...

我们刚刚创建的 scorer 可以直接插入 mlflow.genai.evaluate() 中,以将评估规模扩大到整个数据集,或者插入监控 API 以将 scorer 应用于生产流量。

import mlflow
import pandas as pd

# Your support conversations dataset
test_data = pd.DataFrame([
{
"inputs": {"issue": "Billing error - charged twice"},
"outputs": {"response": "I'll immediately refund the duplicate charge."}
},
{
"inputs": {"issue": "Feature request for dark mode"},
"outputs": {"response": "Great suggestion! I've forwarded this to our product team."}
}
])

# Run evaluation with your custom scorer
results = mlflow.genai.evaluate(
data=test_data,
scorers=[support_scorer]
)

# View results
print(results.tables["eval_results_table"])

Scorers 作为代理:基于追踪的评估

到目前为止,我们的 scorer 已经评估了简单的问答对。但 MLflow Scorers 可以以代理(agentically)的方式分析复杂的 AI 代理,这些代理会进行多次 LLM 调用,使用工具,并遵循推理链。

代理 Scorer 评估复杂代理

基于代理的 Scorer 最强大的方面之一是它们能够诊断复杂代理工作流程中的复杂工具调用和逻辑链。例如,下面的片段展示了一个高级代理,它可以回答关于奇幻货币系统物流的问题。它拥有数十种工具,可以进行物理计算、物流评估和标准参考信息,以确定奇幻角色获得的财宝有多么荒谬。

用于评估的基于代理的裁判能够审查每个 span 的整个流程,这不仅使 scorer 在整体评分方面更准确,而且还允许其解释具有针对性和更具证据基础。

MLflow Trace UI showing detailed execution flow

为什么我们称它们为“代理式”(Agentic)

没有 make_judge,实现一个全面的追踪评估器将需要大量的努力。您需要

  1. 编写代码来提取追踪的不同部分(工具调用、LLM 交互、错误处理)
  2. 创建单独的提示来评估每个标准(工具调用是否合理?轨迹中是否有问题?错误是否得到了妥善处理?)
  3. 开发逻辑将这些信号合并为最终评估
  4. 实现更复杂的推理策略以进行细致的评估

相反,make_judge 提供了内置的工具来进行追踪内省,并实现了一个推理循环来评估您的声明式质量标准。这使您可以专注于 *要* 评估什么,而不是 *如何* 实现评估。

真实世界示例:客户支持代理

让我们评估一个使用多个工具来解决问题的更复杂的客户支持代理。

# Example: A customer support agent handling a refund request
import mlflow
from mlflow.genai.judges import make_judge

# Create a comprehensive agent evaluator
agent_scorer = make_judge(
name="support_agent_quality",
instructions=(
"Analyze the {{ trace }} for a customer support interaction.\n\n"
"Evaluate the following:\n"
"1. Did the agent use the correct tools (search_orders, process_refund)?\n"
"2. Were authentication steps properly followed?\n"
"3. Was the customer kept informed throughout the process?\n"
"4. Were any errors handled gracefully?\n\n"
"Rate as: 'excellent', 'satisfactory', or 'needs_improvement'"
),
model="openai:/gpt-4o"
)

# Simulate a complex agent execution with multiple tool calls
with mlflow.start_span("handle_refund_request") as main_span:
with mlflow.start_span("search_customer_orders"):
# Agent searches for customer orders
orders = search_orders(customer_id="12345")
mlflow.log_input({"customer_id": "12345"})
mlflow.log_output({"orders_found": 3})

with mlflow.start_span("verify_refund_eligibility"):
# Agent verifies refund eligibility
eligible = check_refund_policy(order_id="ORD-789")
mlflow.log_output({"eligible": True, "reason": "Within 30-day window"})

with mlflow.start_span("process_refund"):
# Agent processes the refund
refund_result = process_refund(order_id="ORD-789", amount=99.99)
mlflow.log_output({"status": "success", "refund_id": "REF-123"})

with mlflow.start_span("notify_customer"):
# Agent sends confirmation to customer
notification_sent = send_email(
to="customer@example.com",
subject="Refund Processed",
body="Your refund of $99.99 has been processed..."
)
mlflow.log_output({"notification_sent": True})

trace_id = main_span.trace_id

# The scorer analyzes the entire trace
trace = mlflow.get_trace(trace_id)
evaluation = agent_scorer(trace=trace)

print(f"Agent Performance: {evaluation.value}")
print(f"Analysis: {evaluation.rationale}")

输出

Agent Performance: excellent
Analysis: The agent followed all required procedures correctly:
1. Properly searched for customer orders before processing
2. Verified refund eligibility according to policy
3. Successfully processed the refund with correct amount
4. Notified the customer of the completion
All tool calls were necessary and executed in the optimal order.

游戏规则改变者:人类反馈对齐

有趣的地方在这里。当您的 scorer 与您的人类专家意见不符时会发生什么?MLflow Scorers 可以从人类的纠正中学习,而无需无休止地重写提示。

步骤 1:收集人类反馈

您可以通过 MLflow Trace UI 或以编程方式提供反馈。

选项 A:使用 Trace UI / Evaluation UI

导航到您的 MLflow 跟踪服务器,并在评估追踪上直接使用反馈界面。这对于喜欢可视化界面的主题专家,或者为了添加全面的反馈来直接纠正代理提供的解释非常理想。

MLflow Trace UI with human feedback interface

您在此处提供的反馈将作为追踪的一部分进行记录,并可用于对齐。

选项 B:编程反馈

下面的示例展示了如何以编程方式记录反馈。这对于将专家评审集成到您现有的工作流程中很有用。您甚至可以使用 MLflow SDK API 将您应用程序用户的反馈直接嵌入到您的应用程序中。

from mlflow.entities import AssessmentSource, AssessmentSourceType

# Search for traces from production or development environments
production_traces = mlflow.search_traces(
experiment_ids=[experiment_id],
filter_string="attributes.environment = 'production'",
max_results=100
)

# Provide human feedback on specific traces
for trace in production_traces:
# Your expert reviews the trace and provides assessment
mlflow.log_feedback(
trace_id=trace.info.trace_id,
name="support_quality", # Must match scorer name
value="empathetic", # Expert's assessment
source=AssessmentSource(
source_type=AssessmentSourceType.HUMAN,
source_id="support_expert"
)
)

步骤 2:使您的 Scorer 与专家反馈对齐

一旦收集了反馈(建议至少 10 个示例),您就可以对齐您的 scorer。

# Gather traces with human feedback
traces_with_feedback = mlflow.search_traces(
experiment_ids=[experiment_id],
return_type="list"
)

# Create an aligned scorer that learns from expert preferences
aligned_scorer = support_scorer.align(
traces=traces_with_feedback
)

# Use the aligned scorer in your evaluation pipeline
results = mlflow.genai.evaluate(
data=test_data,
scorers=[aligned_scorer] # Now uses expert-aligned scoring
)

print(f"Alignment improved accuracy by: {results.metrics['alignment_improvement']}%")

可插拔优化框架

MLflow 的对齐实现被设计为可扩展的。虽然当前版本包含 DSPy 的内置 SIMBA 优化器,但该架构支持通过 AlignmentOptimizer 抽象基类来实现自定义对齐优化器。

# Use the default SIMBA optimizer
aligned_scorer = support_scorer.align(traces=traces_with_feedback)

# Or provide your own custom optimizer
from mlflow.genai.judges.base import AlignmentOptimizer

class CustomOptimizer(AlignmentOptimizer):
def align(self, judge, traces):
# Your optimization logic here
return optimized_judge

custom_optimizer = CustomOptimizer()
aligned_scorer = support_scorer.align(
traces=traces_with_feedback,
optimizer=custom_optimizer
)

这种可插拔的设计意味着您可以利用外部优化框架或实现领域特定的对齐策略,同时保持与 MLflow 评估生态系统的兼容性。

实际上,与通用提示相比,对齐后的 scorer 在评估错误方面减少了 30-50%。您提供的反馈越多,它们在匹配您团队的质量标准方面就越好。

结论

新的 make_judge API 改变了您为 GenAI 应用构建和维护 LLM 裁判的方式。我们已经展示了这种声明式方法如何消除了传统上创建领域特定评估器所需的手动工作。

关键要点是:

  • 声明式优于命令式:用简单的指令定义 *要* 评估的内容,而不是 *如何* 实现评估。
  • 内置代理能力:Scorer 配备了用于追踪内省的工具,消除了对复杂提取和评估逻辑的需求。
  • 与专家自动对齐:Scorer 从主题专家反馈中学习,评估错误减少了 30-50%。
  • 无缝集成:直接与 mlflow.genai.evaluate() 配合使用,用于数据集评估和生产监控。

MLflow 提供的内置 scorer 只是使用这些相同功能的预定义版本。一旦您理解了这一点,创建领域特定评估器就会变得简单。您可以在几分钟内拥有一个可用的自定义 scorer,该 scorer 会随着从您团队的专业知识中学习而自动改进。

后续步骤