追踪快速入门
需要帮助设置追踪吗?试试 MLflow Assistant - 一个强大的 AI 助手,可以自动为您的项目添加 MLflow 追踪。
本快速入门指南将引导您完成使用 MLflow Tracing 设置简单的 GenAI 应用程序。您将在不到 10 分钟的时间内启用跟踪、运行基本应用程序,并在 MLflow UI 中探索生成的跟踪。
先决条件
请确保您已启动 MLflow 服务器。如果您还没有运行 MLflow 服务器,只需按照这些简单的步骤即可启动它。
- 本地 (uv)
- 本地 (pip)
- 本地 (docker)
Python 环境:Python 3.10+
通过 pip 安装 mlflow Python 包并在本地启动 MLflow 服务器。
pip install --upgrade 'mlflow[genai]'
mlflow server
MLflow 提供了一个 Docker Compose 文件,用于启动一个带有 PostgreSQL 数据库和 MinIO 服务器的本地 MLflow 服务器。
git clone --depth 1 --filter=blob:none --sparse https://github.com/mlflow/mlflow.git
cd mlflow
git sparse-checkout set docker-compose
cd docker-compose
cp .env.dev.example .env
docker compose up -d
有关更多详细信息(例如,覆盖默认环境变量),请参阅 说明。
创建 MLflow 实验
您的 GenAI 应用将发送到 MLflow 服务器的追踪被分组到 MLflow 实验中。我们建议为每个 GenAI 应用创建一个实验。
让我们使用 MLflow UI 创建一个新的 MLflow 实验,以便您可以开始发送您的追踪。

- 在浏览器中导航到 MLflow UI,地址是 https://:5000。
- 点击右上角的创建按钮。
- 为实验输入一个名称,然后点击“创建”。
目前您可以将 Artifact Location 字段留空。这是一个高级配置,用于覆盖 MLflow 存储实验数据的位置。
依赖项
要将您的 GenAI 应用连接到 MLflow 服务器,您需要安装 MLflow 客户端 SDK。
- Python(OpenAI)
- TypeScript(OpenAI)
pip install --upgrade 'mlflow[genai]' openai>=1.0.0
npm install mlflow-openai
虽然本指南以使用 OpenAI SDK 的示例为特色,但相同的步骤适用于其他 LLM 提供商,包括 Anthropic、Google、Bedrock 以及许多其他。
有关 MLflow 支持的 LLM 提供商的完整列表,请参阅 LLM 集成概览。
开始追踪
创建实验后,您就可以连接到 MLflow 服务器并开始从您的 GenAI 应用发送追踪了。
- Python(OpenAI)
- TypeScript(OpenAI)
- OpenTelemetry
import mlflow
from openai import OpenAI
# Specify the tracking URI for the MLflow server.
mlflow.set_tracking_uri("https://:5000")
# Specify the experiment you just created for your GenAI application.
mlflow.set_experiment("My Application")
# Enable automatic tracing for all OpenAI API calls.
mlflow.openai.autolog()
client = OpenAI()
# The trace of the following is sent to the MLflow server.
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?"},
],
)
import { init } from "mlflow-tracing";
import { tracedOpenAI } from "mlflow-openai";
import { OpenAI } from "openai";
init({
trackingUri: "https://:5000",
// NOTE: specifying experiment name is not yet supported in TypeScript SDK.
// You can copy the experiment id from the experiment details on the MLflow UI.
experimentId: "<experiment-id>",
});
// Wrap the OpenAI client with the tracedOpenAI function to enable automatic tracing.
const client = tracedOpenAI(new OpenAI());
// The trace of the following is sent to the MLflow server.
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 服务器在 /v1/traces 暴露一个 OTLP 端点(OTLP)。此端点接受来自任何原生 OpenTelemetry 检测的追踪,允许您追踪用其他语言(如 Java、Go、Rust 等)编写的应用程序。
以下示例展示了如何使用 OpenTelemetry FastAPI 仪器收集来自 FastAPI 应用程序的追踪。
import os
import uvicorn
from fastapi import FastAPI
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
# Set the endpoint and header
MLFLOW_TRACKING_URI = "https://:5000"
MLFLOW_EXPERIMENT_ID = "123"
os.environ["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] = f"{MLFLOW_TRACKING_URI}/v1/traces"
os.environ[
"OTEL_EXPORTER_OTLP_TRACES_HEADERS"
] = f"x-mlflow-experiment-id={MLFLOW_EXPERIMENT_ID}"
app = FastAPI()
FastAPIInstrumentor.instrument_app(app)
@app.get("/")
async def root():
return {"message": "Hello, World!"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
要深入了解将 MLflow 与 OpenTelemetry 结合使用,请参阅 OpenTelemetry 指南。
在 MLflow UI 中查看您的追踪
运行上述代码后,转到 MLflow UI,选择“My Application”实验,然后选择“Traces”选项卡。它应该会显示新创建的追踪。


使用会话追踪多轮对话
许多 GenAI 应用与用户保持多轮对话。MLflow 通过使用标准元数据字段,为追踪用户会话提供了内置支持。这使您可以将相关的追踪分组在一起并分析对话流程。
- Python
- TypeScript
以下是如何向您的应用添加用户和会话追踪的方法
import mlflow
@mlflow.trace
def chat_completion(message: list[dict], user_id: str, session_id: str):
"""Process a chat message with user and session tracking."""
# Add user and session context to the current trace
mlflow.update_current_trace(
metadata={
"mlflow.trace.user": user_id, # Links trace to specific user
"mlflow.trace.session": session_id, # Groups trace with conversation
}
)
# Your chat logic here
return generate_response(message)
import * as mlflow from "mlflow-tracing";
const chatCompletion = mlflow.trace(
(message: Array<Record<string, any>>, userId: string, sessionId: string) => {
// Add user and session context to the current trace
mlflow.updateCurrentTrace({
metadata: {
"mlflow.trace.user": userId,
"mlflow.trace.session": sessionId,
},
});
// Your chat logic here
return generateResponse(message);
},
{ name: "chat_completion" }
);
有关追踪用户和会话的更多详细信息,请参阅 追踪用户和会话指南。
下一步
恭喜您使用 MLflow 发送了您的第一个追踪!既然您已经掌握了基础知识,以下是加深您对追踪理解的推荐下一步