Tracing Quickstart (Python)
TypeScript/JavaScript 入门指南可在此处找到。
本快速入门指南将引导您完成使用 MLflow Tracing 设置简单的 GenAI 应用程序。您将在不到 10 分钟的时间内启用跟踪、运行基本应用程序,并在 MLflow UI 中探索生成的跟踪。
先决条件
通过运行以下命令安装所需的软件包
pip install --upgrade mlflow openai>=1.0.0
本指南中的代码示例使用了 OpenAI SDK;然而,本指南的内容适用于任何其他 LLM 提供商,例如 Anthropic、Google、Bedrock 等。
第一步:设置您的环境
连接到 MLflow
MLflow 将跟踪记录在跟踪服务器中。请通过以下任一方法将您的本地环境连接到跟踪服务器。
- 本地 (pip)
- 本地 (docker)
- 远程 MLflow 服务器
- Databricks
为了最快的设置,您可以安装 mlflow Python 包并在本地运行 MLflow
mlflow ui --backend-store-uri sqlite:///mlflow.db --port 5000
这将启动本地计算机上的服务器,端口为 5000。通过设置跟踪 URI 将您的 notebook/IDE 连接到服务器。您也可以访问 MLflow UI,地址为 https://:5000。
import mlflow
mlflow.set_tracking_uri("https://:5000")
您也可以在 https://:5000 访问 MLflow UI。
MLflow 提供了一个 Docker Compose 文件,用于启动一个本地 MLflow 服务器,其中包含一个 postgres 数据库和一个 minio 服务器。
git clone https://github.com/mlflow/mlflow.git
cd docker-compose
cp .env.dev.example .env
docker compose up -d
这将启动本地计算机上的服务器,端口为 5000。通过设置跟踪 URI 将您的 notebook/IDE 连接到服务器。您也可以访问 MLflow UI,地址为 https://:5000。
import mlflow
mlflow.set_tracking_uri("https://:5000")
有关更多详细信息,请参阅 说明,例如覆盖默认环境变量。
如果您有远程 MLflow 跟踪服务器,请配置连接
import os
import mlflow
# Set your MLflow tracking URI
os.environ["MLFLOW_TRACKING_URI"] = "http://your-mlflow-server:5000"
# Or directly in code
mlflow.set_tracking_uri("http://your-mlflow-server:5000")
如果您有 Databricks 帐户,请配置连接
import mlflow
mlflow.login()
这将提示您输入配置详细信息(Databricks 主机 URL 和 PAT)。
如果您不确定如何设置 MLflow 跟踪服务器,可以从基于云的 MLflow 开始,该服务由 Databricks 提供支持:免费注册 →
创建新的 MLflow 实验
import mlflow
# This will create a new experiment called "Tracing Quickstart" and set it as active
mlflow.set_experiment("Tracing Quickstart")
配置 OpenAI API 密钥(或其他 LLM 提供商)
import os
# Use different env variable when using a different LLM provider
os.environ["OPENAI_API_KEY"] = "your-api-key-here" # Replace with your actual API key
步骤 2:跟踪单个 LLM 调用
让我们从跟踪单个 LLM 调用的简单示例开始。我们首先通过调用 mlflow.openai.autolog() 来为 OpenAI API 调用启用自动跟踪。在此之后,对 OpenAI API 的每次调用都将生成一个跟踪 span,捕获输入、输出、延迟、token 计数和其他元数据。
import mlflow
from openai import OpenAI
# Enable automatic tracing for all OpenAI API calls
mlflow.openai.autolog()
# Instantiate the OpenAI client
client = OpenAI()
# Invoke chat completion API
response = client.chat.completions.create(
model="o4-mini",
messages=[
{"role": "system", "content": "You are a helpful weather assistant."},
{"role": "user", "content": "What's the weather like in Seattle?"},
],
)
运行上面的代码后,转到 MLflow UI 并选择“Traces”选项卡。它应该会显示新创建的跟踪。

表格视图显示了跟踪的主要元数据,例如跟踪 ID、执行持续时间、token 计数、源系统和状态。您可以通过选择下拉列表中的列来添加或删除显示的列。通过单击请求行(链接的请求文本),您可以查看跟踪中详细的 span。

上面截图中的“Chat”视图显示了用户和模型之间交换的完整聊天消息。通过单击其他表格,例如“Inputs / Outputs”或“Attributes”,您可以查看跟踪的不同方面,包括原始输入负载、token 使用量细分等。
步骤 3:跟踪工具调用代理
接下来,让我们为应用程序增加一点复杂性。为了获取实时天气信息,我们将使用外部天气 API 作为工具。该应用程序将包含一个工具调用流程,而不仅仅是简单的 LLM 调用。要 instrument 这种自定义 Python 流程,我们将使用 @mlflow.trace 装饰器。使用此简单装饰器可以为函数调用生成 span,并自动捕获函数输入、输出、延迟和异常。
让我们定义一个从天气 API 获取天气信息的 Python 函数。
import requests
from mlflow.entities import SpanType
# Decorated with @mlflow.trace to trace the function call.
@mlflow.trace(span_type=SpanType.TOOL)
def get_weather(latitude, longitude):
response = requests.get(
f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m"
)
data = response.json()
return data["current"]["temperature_2m"]
为了将函数作为工具传递给 LLM,我们需要定义函数的 JSON schema。
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current temperature for provided coordinates in celsius.",
"parameters": {
"type": "object",
"properties": {
"latitude": {"type": "number"},
"longitude": {"type": "number"},
},
"required": ["latitude", "longitude"],
"additionalProperties": False,
},
"strict": True,
},
}
]
最后,定义一个简单的流程,该流程首先要求 LLM 获取调用工具的指令,然后调用工具函数,最后将结果返回给 LLM。
import json
from mlflow.entities import SpanType
# Define a simple tool calling agent
@mlflow.trace(span_type=SpanType.AGENT)
def run_tool_agent(question: str):
messages = [{"role": "user", "content": question}]
# Invoke the model with the given question and available tools
response = client.chat.completions.create(
model="o4-mini",
messages=messages,
tools=tools,
)
ai_msg = response.choices[0].message
messages.append(ai_msg)
# If the model requests tool call(s), invoke the function with the specified arguments
if tool_calls := ai_msg.tool_calls:
for tool_call in tool_calls:
function_name = tool_call.function.name
if function_name == "get_weather":
# Invoke the tool function with the provided arguments
args = json.loads(tool_call.function.arguments)
tool_result = get_weather(**args)
else:
raise RuntimeError("An invalid tool is returned from the assistant!")
messages.append(
{
"role": "tool",
"tool_call_id": tool_call.id,
"content": str(tool_result),
}
)
# Sent the tool results to the model and get a new response
response = client.chat.completions.create(model="o4-mini", messages=messages)
return response.choices[0].message.content
现在我们可以运行应用程序了。
# Run the tool calling agent
question = "What's the weather like in Seattle?"
answer = run_tool_agent(question)
步骤 4:在 UI 中探索跟踪
运行应用程序后,您可以在 MLflow UI 中探索跟踪。

跟踪显示了所有 LLM 调用和工具调用,并以树状结构组织。您还可以通过单击树状视图旁边的时间线图标来检查时间线细分。这有助于您了解应用程序中的时间消耗情况。

步骤 5:为跟踪附加反馈
作为本次快速入门的最后一步,让我们为生成的跟踪附加反馈。在实际开发中,人类反馈对于提高任何 LLM 驱动的应用程序的质量至关重要。
要向跟踪添加反馈,您可以打开跟踪详细信息页面,然后单击右上角的“Add new Assessment”按钮。它将打开一个输入表单,您可以在其中提供各种反馈值和元数据。例如,我们可以添加一个名为“Quality”的反馈,其值为整数(1~5),表示答案的质量。我们还可以放回分数背后的详细理由以供将来参考。

当您使用“Create”按钮提交表单时,反馈将被附加到跟踪。

在实验中汇总的分数可以在跟踪列表中看到。您可以按各种标准进行切片和切块,例如时间戳、来源、标签,它将实时更新汇总分数。

总结
恭喜!您已成功
- ✅ 设置 MLflow Tracing 以用于 GenAI 应用程序
- ✅ 为 OpenAI API 调用启用了自动跟踪
- ✅ 在 MLflow UI 中生成并探索了跟踪
- ✅ 学习了如何使用装饰器添加自定义跟踪
- ✅ 学习了如何为跟踪附加反馈
MLflow Tracing 为您的 GenAI 应用程序提供了强大的可观察性,帮助您监控性能、调试问题并理解用户交互。继续探索高级功能,以充分利用您的跟踪设置!
后续步骤
现在您已经基本掌握了跟踪功能,请探索这些高级功能