跳到主要内容

版本跟踪快速入门

使用 MLflow 的版本管理功能构建和跟踪基于 LangChain 的聊天机器人。本快速入门演示了提示版本控制、应用程序跟踪、跟踪生成和性能评估,使用了 MLflow 的 GenAI 功能。

先决条件

安装所需的软件包

需要 MLflow 3

此快速入门要求 MLflow 版本 3.0 或更高版本才能实现完整的 GenAI 功能。

bash
pip install --upgrade 'mlflow[genai]'
pip install langchain-openai

设置 OpenAI API 密钥

配置您的 OpenAI API 密钥以通过 OpenAI 服务进行身份验证

bash
export OPENAI_API_KEY=your_api_key_here

您将学到什么

此快速入门涵盖了使用 MLflow 的版本管理系统构建可跟踪的 GenAI 应用程序的基本概念。

版本控制提示

注册和跟踪具有完整版本历史记录的提示模板,以实现可重现的实验

构建 LangChain 代理

创建具有自动 MLflow 集成和可观测性的会话代理

跟踪所有内容

启用全面的跟踪日志记录,以监控和调试模型的行为

评估性能

使用内置指标和自定义评估框架来评估模型质量

让我们构建一个简单的 IT 支持聊天机器人,并使用 MLflow 跟踪其开发生命周期。

步骤 1:注册提示模板

首先创建一个带有版本的提示模板。这使您能够跟踪提示的演变,并确保跨实验的可重现性。

python
import mlflow

system_prompt = mlflow.genai.register_prompt(
name="chatbot_prompt",
template="You are a chatbot that can answer questions about IT. Answer this question: {{question}}",
commit_message="Initial version of chatbot",
)

在 MLflow UI 中查看您的提示

导航到 Prompts 选项卡以查看您注册的提示

The MLflow UI showing a prompt version

步骤 2:构建 LangChain 会话链

创建一个简单的链,将您的提示模板与 OpenAI 的聊天模型结合起来

python
from langchain.schema.output_parser import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

# Convert MLflow prompt to LangChain format
prompt = ChatPromptTemplate.from_template(system_prompt.to_single_brace_format())

# Build the chain: prompt → LLM → output parser
chain = prompt | ChatOpenAI(temperature=0.7) | StrOutputParser()

# Test the chain
question = "What is MLflow?"
print(chain.invoke({"question": question}))
# MLflow is an open-source platform for managing the end-to-end machine learning lifecycle...

步骤 3:启用跟踪可观测性

设置自动跟踪日志记录以监控模型在开发过程中的行为。这将创建所有模型交互的链接历史记录。

配置活动模型和自动日志记录

python
# Set the active model for linking traces
mlflow.set_active_model(name="langchain_model")

# Enable autologging - all traces will be automatically linked to the active model
mlflow.langchain.autolog()

生成测试跟踪

运行多个查询以生成要分析的跟踪

python
questions = [
{"question": "What is MLflow Tracking and how does it work?"},
{"question": "What is Unity Catalog?"},
{"question": "What are user-defined functions (UDFs)?"},
]
outputs = []

for question in questions:
outputs.append(chain.invoke(question))

# Verify traces are linked to the active model
active_model_id = mlflow.get_active_model_id()
mlflow.search_traces(model_id=active_model_id)

在 UI 中探索跟踪

  1. 查看已记录的模型:在实验中查看 Models 选项卡
The MLflow UI showing the logged models in an experiment
  1. 访问模型详细信息:点击您的模型以查看其唯一的 model_id
The MLflow UI showing the logged model details page
  1. 分析生成的跟踪:导航到 Traces 选项卡以检查单个交互
The MLflow UI showing the logged model autolog traces lineage

步骤 4:评估模型性能

评估对于理解聊天机器人的性能以及确保随时间推移的质量改进至关重要。MLflow 为系统评估跟踪提供了基础。

关键评估能力

  • 质量评估:使用关键字覆盖率和内容分析系统地评估响应质量,以确保聊天机器人符合预期
  • 性能指标:跟踪响应长度和关键字匹配等定量度量,以监控随时间推移的改进
  • 持续监控:将评估结果记录到 MLflow,以进行持续的性能跟踪和跨模型迭代的比较

使用 MLflow 的跟踪功能来评估您的聊天机器人相对于预期响应的准确性和相关性。

手动分析输出

通过将模型输出与预期响应进行比较来评估它们

python
import pandas as pd

# Create evaluation dataset
eval_data = [
{
"question": "What is MLflow Tracking and how does it work?",
"expected_keywords": [
"experiment tracking",
"parameters",
"metrics",
"artifacts",
"UI",
],
},
{
"question": "What is Unity Catalog?",
"expected_keywords": [
"data assets",
"centralized",
"collaboration",
"governance",
],
},
{
"question": "What are user-defined functions (UDFs)?",
"expected_keywords": [
"custom functions",
"data transformations",
"Spark",
"SQL",
],
},
]


# Simple evaluation metrics
def evaluate_response(response, expected_keywords):
"""Simple keyword-based evaluation."""
response_lower = response.lower()
keyword_matches = sum(
1 for keyword in expected_keywords if keyword.lower() in response_lower
)
coverage_score = keyword_matches / len(expected_keywords)
response_length = len(response.split())

return {
"keyword_coverage": coverage_score,
"response_length": response_length,
"keyword_matches": keyword_matches,
}


# Evaluate each response
evaluation_results = []
for i, (output, eval_item) in enumerate(zip(outputs, eval_data)):
metrics = evaluate_response(output, eval_item["expected_keywords"])
evaluation_results.append(
{
"question": eval_item["question"],
"response": output,
"keyword_coverage": metrics["keyword_coverage"],
"response_length": metrics["response_length"],
"keyword_matches": metrics["keyword_matches"],
}
)

print(
f"Question {i+1}: {metrics['keyword_matches']}/{len(eval_item['expected_keywords'])} keywords found"
)
print(f"Coverage: {metrics['keyword_coverage']:.1%}")
print(f"Response length: {metrics['response_length']} words\n")

# Log evaluation metrics
with mlflow.start_run():
avg_coverage = sum(r["keyword_coverage"] for r in evaluation_results) / len(
evaluation_results
)
avg_length = sum(r["response_length"] for r in evaluation_results) / len(
evaluation_results
)

mlflow.log_metric("avg_keyword_coverage", avg_coverage)
mlflow.log_metric("avg_response_length", avg_length)

print(f"📊 Average keyword coverage: {avg_coverage:.1%}")
print(f"📊 Average response length: {avg_length:.0f} words")

在 MLflow UI 中查看结果

评估指标已记录到 MLflow 以进行跟踪和比较。导航到 Experiments 选项卡以查看您的评估运行并跨不同迭代比较结果。

您构建了什么

您现在拥有一个完整的、经过版本跟踪的 GenAI 应用程序,具有全面的可观测性和评估功能。

您所完成的

  • 版本化提示模板:您的提示现已在 MLflow 中注册,并具有完整的版本历史记录,支持可重现的实验和系统的改进
  • 集成的 LangChain 代理:构建了一个具有自动 MLflow 集成的会话代理,该代理捕获每一次交互以供分析和调试
  • 完整的跟踪可观测性:启用了全面的跟踪日志记录,将所有模型交互链接到您的版本化应用程序,以实现完全可见性
  • 系统评估:使用基于关键字的指标实现了性能跟踪,这些指标将结果记录到 MLflow 中,以进行持续的质量监控

后续步骤