跳到主要内容

追踪快速入门 (TS/JS)

信息

Python 快速入门可在此处获取。

本快速入门指南将引导您使用 MLflow Tracing 设置一个简单的 GenAI 应用程序。在不到 10 分钟的时间内,您将启用追踪、运行基本应用程序,并在 MLflow UI 中探索生成的追踪。

先决条件

通过运行以下命令安装所需的包

npm install mlflow-openai
信息

本指南中的代码示例使用 OpenAI SDK;但是,本指南的内容适用于任何其他 LLM 提供商,例如 Anthropic、Google、Bedrock 等。

对于未原生集成自动追踪的其他 LLM 提供商,请安装 `mlflow-tracing` 包,并用 `mlflow.trace` 包装函数包装 LLM 调用。

包装 Anthropic API 调用以生成追踪的示例
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");

步骤 1:设置您的环境

连接到 MLflow

MLflow 在追踪服务器中记录追踪。通过以下方法之一将您的应用程序连接到追踪服务器。

TypeScript 包不包含追踪服务器。要从命令行使用 MLflow Python 包启动自托管追踪服务器

# Install mlflow python package. Typescript SDK requires MLflow Tracking Server running on version 3.2.0 or later.
pip install 'mlflow>=3.2.0rc1' -U

# Start MLflow tracking server locally
mlflow ui --port 5000

# This will start the server at http://127.0.0.1:5000
提示

如果您想快速开始而无需托管 MLflow 服务器,请尝试由 Databricks 提供支持的基于云的 MLflow

免费注册 →

创建一个新的 MLflow 实验

在 MLflow UI 中创建一个新的 MLflow 实验,或选择一个现有实验。

New Experiment
  1. 在浏览器中导航到 MLflow UI。例如,如果您在端口 5000 启动了本地 MLflow 服务器,您可以导航到 http://127.0.0.1:5000
  2. 点击
    创建
    右上角的按钮。
  3. 输入实验名称,然后点击“创建”。

现在您可以将 `Artifact Location` 字段留空。它是一个高级配置,用于覆盖 MLflow 存储实验数据的位置。

初始化追踪 SDK

使用追踪 URI(例如,`http://127.0.0.1:5000`)和实验 ID 调用 `init` 函数。您可以通过将鼠标悬停在 MLflow UI 中实验名称旁边的

!
图标上来查找实验 ID。

import { init } from "mlflow-tracing";

init({
trackingUri: "<your-tracking-server-uri>",
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 的每次调用都将生成一个追踪跨度,捕获输入、输出、延迟、令牌计数和其他元数据。

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 并选择“追踪”选项卡。它应该显示新创建的追踪。

Single Trace

表格视图显示追踪的主要元数据,例如追踪 ID、执行持续时间、令牌计数、源系统和状态。您可以通过在下拉列表中选择列来添加或删除显示的列。

通过点击请求行(链接的请求文本),您可以查看追踪中的详细跨度。

Single Trace Detail

上述屏幕截图中的“聊天”视图显示了用户和模型之间交换的完整聊天消息。通过点击“输入/输出”或“属性”等其他表格,您可以看到追踪的不同方面,包括原始输入负载、令牌使用细目等。

步骤 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}&current=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 模式。

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 为代理流程创建父跨度,但您也可以使用 `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 中探索追踪

运行应用程序后,您可以在 MLflow UI 中探索追踪。

Tool Calling Trace

追踪以树状结构显示所有 LLM 调用和工具调用。您还可以通过点击树状视图旁边的时间轴图标来检查时间轴细目。这有助于您了解应用程序中时间的消耗位置。

Tool Calling Trace Timeline

步骤 5:在追踪上附加反馈

作为本快速入门的最后一步,让我们在生成的追踪上附加反馈。在实际开发中,人工反馈对于提高任何基于 LLM 的应用程序的质量至关重要。

要向追踪添加反馈,您可以打开追踪详细信息页面并单击右上角的“添加新评估”按钮。它将打开一个输入表单,您可以在其中提供各种反馈值和元数据。例如,我们可以添加一个名为“质量”的反馈,其整数值(1~5)表示答案的质量。我们还可以为未来的参考提供分数背后的详细理由。

Feedback Input Form

当您点击“创建”按钮提交表单时,反馈将附加到追踪中。

Feedback List

实验中的聚合分数可以在追踪列表中看到。您可以根据各种标准进行切片和分析,例如时间戳、来源、标签,它会实时更新聚合分数。

Feedback Aggregated

总结

恭喜!您已成功

  • ✅ 为 GenAI 应用程序设置 MLflow 追踪
  • ✅ 启用 OpenAI API 调用的自动追踪
  • ✅ 在 MLflow UI 中生成并探索追踪
  • ✅ 学习如何使用装饰器添加自定义追踪
  • ✅ 学习如何在追踪上附加反馈

MLflow Tracing 为您的 GenAI 应用程序提供强大的可观测性,帮助您监控性能、调试问题并了解用户交互。继续探索高级功能,以充分利用您的追踪设置!

后续步骤

现在您已经完成了基本的追踪,探索以下高级功能