跳到主要内容

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

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

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

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

本文通过展示如何

  • 使用 make_judge 和简单的声明式指令创建自定义 Scorer
  • 构建充当具有内置工具的代理的 Scorer,用于轨迹内省,从而在没有复杂提示或复杂跨度解析逻辑的情况下执行复杂的评估任务
  • 自动使 Scorer 与主题专家的偏好保持一致,以随着时间的推移提高 Scorer 的准确性

为了说明新 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"])

Scorer 作为代理:基于轨迹的评估

到目前为止,我们的 Scorer 已经评估了简单的问答对。但是 MLflow Scorers 可以像代理一样分析复杂的 AI 代理,这些代理进行多次 LLM 调用、使用工具并遵循推理链。

代理 Scorer 评估复杂代理

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

用于评估的基于代理的评判器能够审查每个跨度的整个流程,这不仅可以提高 Scorer 在总体评分方面的准确性,还可以使其推理具有针对性且更具证据支持。

MLflow Trace UI showing detailed execution flow

为什么称它们为“代理式”

没有 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,它会随着学习您团队的专业知识而自动改进。

后续步骤