Token 使用与成本跟踪
MLflow 会在您的跟踪(traces)中自动记录 LLM 调用产生的 Token 使用量和成本。这使您能够监控资源消耗,并优化跨 LLM 应用和 AI 代理的成本。
概述
当启用跟踪功能时,MLflow 将捕获:
- Token 使用量:每次 LLM 调用的输入 Token、输出 Token 及总 Token 数量
- 成本:每次 LLM 调用的预计美元(USD)成本,基于模型定价计算得出
此信息可在跨度(span)级别(单个 LLM 调用)和跟踪(trace)级别聚合查看。
要求
| 功能 | MLflow 版本 |
|---|---|
| 令牌使用跟踪 | >= 3.2.0 |
| 成本跟踪 | >= 3.10.0 |
要启用成本跟踪,您需要使用已安装 [genai] 额外功能的 MLflow 跟踪服务器。
- pip
- uv
bash
pip install 'mlflow[genai]>=3.10.0'
mlflow server
bash
uv add 'mlflow[genai]>=3.10.0'
uv run mlflow server
什么是 GenAI 额外功能?
[genai] 额外功能支持其他强大特性,如 AI 网关 (AI Gateway)、自动评估 和 提示词优化。建议在启动 MLflow 服务器时安装此额外功能,即使您当前不需要成本跟踪功能。
信息
在使用 Databricks 托管的 MLflow 时,成本计算要求客户端应用程序安装 LiteLLM 或 手动设置跨度上的成本属性。对于自托管的 MLflow,则不需要此操作。
在 UI 中查看
Token 使用量和成本信息将显示在 MLflow 跟踪 UI 中。
聚合成本和趋势图表可在实验页面的 概览 (Overview) 选项卡中查看。
以编程方式访问
Python SDK
- 跟踪级别
- 跨度级别
python
import mlflow
# Get the most recent trace
last_trace_id = mlflow.get_last_active_trace_id()
trace = mlflow.get_trace(trace_id=last_trace_id)
# Access token usage
total_usage = trace.info.token_usage
if total_usage:
print("== Total token usage: ==")
print(f" Input tokens: {total_usage['input_tokens']}")
print(f" Output tokens: {total_usage['output_tokens']}")
print(f" Total tokens: {total_usage['total_tokens']}")
# Access cost (requires MLflow >= 3.10.0 and LiteLLM)
total_cost = trace.info.cost
if total_cost:
print("\n== Total cost (USD): ==")
print(f" Input cost: ${total_cost['input_cost']:.6f}")
print(f" Output cost: ${total_cost['output_cost']:.6f}")
print(f" Total cost: ${total_cost['total_cost']:.6f}")
python
import mlflow
# Get the most recent trace
last_trace_id = mlflow.get_last_active_trace_id()
trace = mlflow.get_trace(trace_id=last_trace_id)
# Access token usage and cost for each LLM call
print("== Token usage and cost for each LLM call: ==")
for span in trace.data.spans:
usage = span.get_attribute("mlflow.chat.tokenUsage")
cost = span.llm_cost
print(f"{span.name}:")
if usage:
print(f" Input tokens: {usage['input_tokens']}")
print(f" Output tokens: {usage['output_tokens']}")
print(f" Total tokens: {usage['total_tokens']}")
if cost:
print(f" Input cost: ${cost['input_cost']:.6f}")
print(f" Output cost: ${cost['output_cost']:.6f}")
print(f" Total cost: ${cost['total_cost']:.6f}")
TypeScript / JavaScript SDK
注意
TypeScript SDK 的成本跟踪支持即将推出。目前已提供 Token 使用量支持。
typescript
import * as mlflow from "mlflow-tracing";
// Flush any pending spans then fetch the most recent trace
await mlflow.flushTraces();
const lastTraceId = mlflow.getLastActiveTraceId();
if (lastTraceId) {
const client = new mlflow.MlflowClient({ trackingUri: "https://:5000" });
const trace = await client.getTrace(lastTraceId);
// Access token usage
console.log("== Total token usage: ==");
console.log(trace.info.tokenUsage); // { input_tokens, output_tokens, total_tokens }
// Per-span usage
console.log("\n== Usage for each LLM call: ==");
for (const span of trace.data.spans) {
const usage = span.attributes?.["mlflow.chat.tokenUsage"];
if (usage) {
console.log(`${span.name}:`, usage);
}
}
}
输出示例
bash
== Total token usage: ==
Input tokens: 84
Output tokens: 22
Total tokens: 106
== Total cost (USD): ==
Input cost: $0.000013
Output cost: $0.000013
Total cost: $0.000026
== Token usage for each LLM call: ==
Completions_1:
Input tokens: 45
Output tokens: 14
Total tokens: 59
Completions_2:
Input tokens: 39
Output tokens: 8
Total tokens: 47
数据结构
令牌使用情况
TraceInfo 对象中的 token_usage 字段返回一个包含以下键的字典:
| 键 | 类型 | 描述 |
|---|---|---|
input_tokens | int | 输入/提示词中的 Token 数量 |
output_tokens | int | 输出/补全中的 Token 数量 |
total_tokens | int | 输入和输出 Token 的总和 |
成本
cost 字段返回一个包含以下键的字典:
| 键 | 类型 | 描述 |
|---|---|---|
input_cost | 浮点数 | 输入 Token 的美元成本 |
output_cost | 浮点数 | 输出 Token 的美元成本 |
total_cost | 浮点数 | 输入和输出成本的美元总和 |
支持的集成
大多数 MLflow 跟踪集成均支持 Token 使用量和成本跟踪。具体支持详情请参阅各 集成页面。
提示
某些提供商或模型可能不会返回 Token 使用量信息。在这种情况下,token_usage 和 cost 字段将为 None。
手动设置 Token 和成本信息
如果您的模型不支持自动成本跟踪,或者您想覆盖计算出的成本,可以手动在跨度上设置 Token 和成本信息。
python
import mlflow
@mlflow.trace
def my_llm_call():
# Get the current span
span = mlflow.get_current_active_span()
# Your LLM call logic here...
# Manually set token usage
span.set_attribute(
"mlflow.chat.tokenUsage",
{
"input_tokens": 100,
"output_tokens": 50,
"total_tokens": 150,
},
)
# Manually set cost (in USD)
span.set_attribute(
"mlflow.llm.cost",
{
"input_cost": 0.0001,
"output_cost": 0.0002,
"total_cost": 0.0003,
},
)
return "response"