Tracing Quickstart (TS/JS)
Python 入门指南可在 此处 获取。
本快速入门指南将引导您完成使用 MLflow Tracing 设置简单的 GenAI 应用程序。您将在不到 10 分钟的时间内启用跟踪、运行基本应用程序,并在 MLflow UI 中探索生成的跟踪。
先决条件
通过运行以下命令安装所需的软件包
npm install mlflow-openai
MLflow 的官方 TypeScript SDK 仅包含 tracing 功能。如果您想使用完整的实验跟踪体验,可以将其与 mlflow.js 结合使用,这是一个社区维护的包,它提供了与 Python SDK 兼容的实验跟踪 API,构建在 MLflow 的 REST API 之上。
本指南中的代码示例使用了 OpenAI SDK;然而,本指南的内容适用于任何其他 LLM 提供商,例如 Anthropic、Google、Bedrock 等。
对于未与自动 tracing 原生集成的其他 LLM 提供商,请安装 mlflow-tracing 包,然后使用 mlflow.trace 包装器函数包装 LLM 调用。
包装 Anthropic API 调用以生成 trace 的示例
import * as mlflow from "mlflow-tracing";
import Anthropic from '@anthropic-ai/sdk';
// Instantiate the Anthropic client
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
// Define a traced function that wraps the Anthropic API call.
const generate = mlflow.trace(
(prompt: string) => {
return anthropic.messages.create({
model: "claude-sonnet-4-latest",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
});
},
{ spanType: mlflow.SpanType.LLM }
);
// Call the wrapped function as usual.
const response = await generate("Hello, Claude");
第一步:设置您的环境
连接到 MLflow
MLflow 在跟踪服务器中记录 Traces。通过以下任一方法将您的应用程序连接到跟踪服务器。
- 本地 (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 实验
在 MLflow UI 中创建一个新的 MLflow 实验,或选择一个现有实验。

- 在浏览器中导航到 MLflow UI。例如,如果您在端口 5000 上启动了一个本地 MLflow 服务器,您可以导航到 http://127.0.0.1:5000。
- 点击右上方创建按钮。
- 输入实验名称,然后点击“创建”。
目前您可以将 Artifact Location 字段留空。这是一个高级配置,用于覆盖 MLflow 存储实验数据的位置。
初始化 Tracing SDK
- 自托管
- 远程 MLflow 服务器
- Databricks
使用跟踪 URI(例如,http://127.0.0.1:5000)和实验 ID 调用 init 函数。您可以通过在 MLflow UI 中将鼠标悬停在实验名称旁边的
import { init } from "mlflow-tracing";
init({
trackingUri: "<your-tracking-server-uri>",
experimentId: "<your-experiment-id>",
});
如果跟踪服务器上启用了身份验证,则可以通过 trackingServerUsername 和 trackingServerPassword 传递凭据。
import { init } from "mlflow-tracing";
init({
trackingUri: "<your-tracking-server-uri>",
experimentId: "<your-experiment-id>",
trackingServerUsername: "<your-tracking-server-username>",
trackingServerPassword: "<your-tracking-server-password>",
});
使用远程 MLflow 服务器的 URI 和实验 ID 调用 init 函数。您可以通过将鼠标悬停在
import { init } from "mlflow-tracing";
init({
trackingUri: "<remote-tracking-server-uri>",
experimentId: "<your-experiment-id>",
});
如果跟踪服务器上启用了身份验证,则可以通过 trackingServerUsername 和 trackingServerPassword 传递凭据。
import { init } from "mlflow-tracing";
init({
trackingUri: "<remote-tracking-server-uri>",
experimentId: "<your-experiment-id>",
trackingServerUsername: "<remote-tracking-server-username>",
trackingServerPassword: "<remote-tracking-server-password>",
});
使用远程 MLflow 服务器的 URI 和实验 ID 调用 init 函数。您可以通过将鼠标悬停在
方法 1:使用 Databricks 配置文件进行身份验证。
import { init } from "mlflow-tracing";
init({
trackingUri: "databricks",
experimentId: "<your-experiment-id>",
// Optional: Set the Databricks config file path if it is not in the default location
configPath: "<your-databricks-config-file-path>",
});
方法 2:使用环境变量
export DATABRICKS_HOST=<your-databricks-host>
export DATABRICKS_TOKEN=<your-databricks-personal-access-token>
或在项目根目录下创建一个 .env 文件并添加以下内容
DATABRICKS_HOST=<your-databricks-host>
DATABRICKS_TOKEN=<your-databricks-personal-access-token>
// Load environment variables from .env file
import 'dotenv/config';
当跟踪 URI 设置为 databricks 时,init 函数将自动加载上述环境变量。
import { init } from "mlflow-tracing";
init({
trackingUri: "databricks",
experimentId: "<your-experiment-id>",
});
设置 OpenAI API 密钥(或其他 LLM 提供商)
export OPENAI_API_KEY="your-api-key-here" # Replace with your actual API key
步骤 2:跟踪单个 LLM 调用
让我们从一个跟踪单个 LLM 调用的简单示例开始。我们首先使用 tracedOpenAI 函数包装 OpenAI 客户端。之后,每次调用 OpenAI API 都会生成一个 trace span,捕获输入、输出、延迟、token 计数和其他元数据。
import { OpenAI } from "openai";
import { tracedOpenAI } from "mlflow-openai";
// Wrap the OpenAI client with the tracedOpenAI function
const client = tracedOpenAI(new OpenAI());
// Invoke the client as usual
// If you are running this tutorial as a script, remove the `await` keyword.
await 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”选项卡。它应该会显示新创建的 trace。

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

上面截图中的“Chat”视图显示了用户和模型之间交换的完整聊天消息。通过点击“Inputs / Outputs”或“Attributes”等其他表格,您可以查看 trace 的不同方面,包括原始输入 payload、token 使用情况细分等。
步骤 3:跟踪工具调用代理
接下来,我们为应用程序增加一些复杂性。为了获取实时天气信息,我们将使用外部天气 API 作为工具。该应用程序将包含一个工具调用流程,而不仅仅是一个简单的 LLM 调用。为了仪器化这个自定义 Python 流程,我们将使用 mlflow.trace 包装器函数。
import * as mlflow from "mlflow-tracing";
// Wrap the tool function with the `mlflow.trace` wrapper. The wrapped function will be automatically traced and logged to MLflow.
const getWeather = mlflow.trace(
// A tool function that fetches the weather information from a weather API
async function getWeather(latitude: number, longitude: number) {
const response = await fetch(`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`);
const data = await response.json();
return data['current']['temperature_2m'];
},
// Set the span type to TOOL. You can also set other span configuration here.
{ spanType: mlflow.SpanType.TOOL }
);
为了将该函数作为工具传递给 LLM,我们需要定义该函数的 JSON schema。
const tools = [{
type: "function",
function: {
name: "get_weather" as const,
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。此示例使用 mlflow.withSpan API 为代理流程创建父 span,但您也可以通过使用 mlflow.trace API 来实现与先前示例相同的效果。
async function runToolAgent(question: string) {
console.log(`\n🤖 Running tool agent with question: "${question}"`);
return await mlflow.withSpan(
async () => {
const client = tracedOpenAI(new OpenAI());
const messages: any[] = [{"role": "user", "content": question}];
// First LLM call to get tool instructions
const response = await client.chat.completions.create({
model: "o4-mini",
messages: messages,
tools: tools,
});
const aiMsg = response.choices[0].message;
messages.push(aiMsg);
// If the model requests tool call(s), invoke the function
if (aiMsg.tool_calls && aiMsg.tool_calls.length > 0) {
for (const toolCall of aiMsg.tool_calls) {
const functionName = toolCall.function.name;
if (functionName === "get_weather") {
// Invoke the tool function with the provided arguments
const args = JSON.parse(toolCall.function.arguments);
const toolResult = await getWeather(args.latitude, args.longitude);
messages.push({
"role": "tool",
"tool_call_id": toolCall.id,
"content": String(toolResult),
});
} else {
throw new Error(`Invalid tool returned: ${functionName}`);
}
}
// Second LLM call with tool results
const finalResponse = await client.chat.completions.create({
model: "o4-mini",
messages: messages
});
return finalResponse.choices[0].message.content;
}
return aiMsg.content;
},
{
name: "run_tool_agent",
spanType: mlflow.SpanType.AGENT,
}
);
}
现在我们可以运行应用程序了。
// If you are running this tutorial as a script, remove the `await` keyword.
await runToolAgent("What's the weather like in Seattle?")
步骤 4:在 UI 中探索 Traces
运行应用程序后,您可以在 MLflow UI 中探索 traces。

trace 以树形结构显示了所有的 LLM 调用和工具调用。您还可以通过点击树视图旁边的时间线图标来检查时间线细分。这有助于您了解应用程序中时间花费在哪里。

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

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

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

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