LLM Cost Tracking

LLM cost tracking is the practice of recording how many tokens every LLM call uses and what those tokens cost, then attributing that spend to individual requests, agent steps, models, and features. MLflow Tracing captures token usage on each LLM call and, from MLflow 3.10, estimates the cost in USD per span and per trace, so you can see where your LLM budget goes in the MLflow UI or query it from Python. No separate billing tool is required.

Last reviewed: November 26, 2026

MLflow experiment dashboard with the Cost Breakdown donut chart by model and the Cost Over Time chart, plus latency, errors, token usage, and tokens per trace, from MLflow demo data

The MLflow experiment dashboard showing the Cost Breakdown donut by model and the Cost Over Time chart, from MLflow demo data

Quick Navigation:

What Is LLM Cost Tracking?

LLM providers bill by tokens: the input tokens you send and the output tokens the model generates, each at a model-specific price. LLM cost tracking turns those token counts into a per-call cost and keeps it next to the prompt, response, and latency of that call.

A provider invoice tells you what you spent in total. Cost tracking tells you why: which agent step, prompt version, model, or user drove the spend, and whether a change made it better or worse.

Why it matters for agents

A single user request to an agent can fan out into many LLM calls for planning, tool selection, retrieval, and answer generation. Cost per request therefore varies widely and is hard to predict from the prompt alone. Tracking cost on every span of the trace makes the expensive step visible, so you can fix it instead of guessing.

Token usage vs. cost

Token usage is a count reported by the model response. Cost is derived: token counts multiplied by the price of the model. Token usage is the reliable signal, and cost is an estimate that depends on pricing data being available for the model you call.

How MLflow Tracks Token Usage and Cost

MLflow Tracing records each LLM call as a span. For supported integrations, MLflow stores the token counts and the estimated cost as span attributes, and aggregates them on the parent trace.

LevelToken usageCost (USD)
Span (one LLM call)mlflow.chat.tokenUsage: input, output, totalmlflow.llm.cost: input, output, total
Trace (whole request)trace.info.token_usagetrace.info.cost

Requirements

FeatureMLflow version
Token usage tracking3.2.0 or later
Cost tracking3.10.0 or later

The documentation recommends installing the genai extra on the tracking server to compute cost. Prices come from LiteLLM's model price data when LiteLLM is installed and from MLflow's built-in model catalog otherwise, so cost is an estimate at list prices. Some providers or models do not return token usage, and in those cases the usage and cost fields are empty. See the token usage and cost documentation for the full details.

Track LLM Cost in Three Steps

1. Install MLflow 3.10 or later with the genai extra and start a server.

bash
pip install 'mlflow[genai]>=3.10.0'
mlflow server

2. Turn on tracing for your LLM library. This example uses OpenAI; MLflow provides one-line integrations for many other providers and frameworks.

python
import mlflow
from openai import OpenAI
mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_experiment("cost-tracking-demo")
mlflow.openai.autolog()
client = OpenAI()
client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Summarize MLflow in one sentence."}],
)

3. Read token usage and cost from the trace.

python
trace = mlflow.get_trace(mlflow.get_last_active_trace_id())
usage = trace.info.token_usage # {"input_tokens", "output_tokens", "total_tokens"}
cost = trace.info.cost # {"input_cost", "output_cost", "total_cost"} in USD
print(usage)
if cost:
print(f"Total cost: ${cost['total_cost']:.6f}")

Analyze Cost by Trace, Step, and Model

See cost in the MLflow UI

Open a trace to see token usage and cost next to each LLM call in the span tree. The experiment dashboard aggregates the same data into charts for traces, latency, errors, token usage, tokens per trace, cost breakdown, and cost over time, which you can split by model or provider.

Find your most expensive traces

Use mlflow.search_traces to pull traces into Python and aggregate. This example totals spend across the first 500 traces that the search returns and lists the five most expensive of them. For a full experiment, page through results with MlflowClient.search_traces.

python
import mlflow
traces = mlflow.search_traces(
locations=["<experiment_id>"],
return_type="list",
max_results=500,
)
priced = [t for t in traces if t.info.cost]
total_cost = sum(t.info.cost["total_cost"] for t in priced)
print(f"{len(priced)} priced traces, total cost: ${total_cost:.4f}")
for t in sorted(priced, key=lambda t: t.info.cost["total_cost"], reverse=True)[:5]:
print(t.info.trace_id, f"${t.info.cost['total_cost']:.6f}")

Attribute spend to agent steps and models

Cost lives on each LLM span, so you can group it by span name to see which step of an agent is the most expensive, or by model name to compare models.

python
from collections import defaultdict
by_model = defaultdict(float)
by_step = defaultdict(float)
for trace in traces:
for span in trace.data.spans:
if cost := span.llm_cost:
by_model[span.model_name] += cost["total_cost"]
by_step[span.name] += cost["total_cost"]
print(dict(by_model))
print(dict(by_step))

Pair cost with quality. A cheaper model is only a saving if LLM evaluation shows the answers stay good, and evaluation results attach to the same traces that carry the cost.

Cost Control with MLflow AI Gateway

If your applications call models through the MLflow AI Gateway, you can track and cap spend at the gateway instead of in each application. With usage tracking enabled on an endpoint, every request is logged as a trace, and the usage dashboard charts requests, latency, errors, token usage, cost breakdown, and cost over time for each endpoint.

Budget policies set a USD threshold over a daily, weekly, or monthly window. When the threshold is passed, a policy either fires a webhook alert or rejects new requests with HTTP 429.

When Automatic Cost Is Unavailable

Cost is missing when the model name on the span has no entry in the pricing table. Token counts can still be correct. In these cases, set the token usage and cost attributes on the span yourself:

python
import mlflow
@mlflow.trace
def my_llm_call():
span = mlflow.get_current_active_span()
# ... call your model here ...
span.set_attribute(
"mlflow.chat.tokenUsage",
{"input_tokens": 100, "output_tokens": 50, "total_tokens": 150},
)
span.set_attribute(
"mlflow.llm.cost",
{"input_cost": 0.0001, "output_cost": 0.0002, "total_cost": 0.0003},
)
return "response"

How MLflow Compares with Other Ways to Track LLM Cost

ApproachWhat you getLimits
Provider billing dashboardExact invoiced spend per account, project, or API keyNo link to prompts, agent steps, or quality; one provider at a time
Custom logging in your codeWhatever fields you decide to logYou maintain the price tables, schema, and charts
MLflow TracingTokens and estimated cost per span and trace, next to the prompt, response, latency, and evaluation scoresCost is an estimate from list pricing, and depends on the provider returning usage

MLflow is an open-source AI engineering platform for agents, LLMs, and ML models. Backed by the Linux Foundation and licensed under Apache 2.0, MLflow provides token and cost tracking with no per-trace fees. Get started →

Frequently Asked Questions

LLM cost tracking is the practice of recording how many tokens each LLM call consumes and what those tokens cost, then attributing that spend to requests, agent steps, models, users, or features. It answers questions that a monthly provider invoice cannot, such as which step of an agent is the most expensive or which model change raised the bill. MLflow Tracing captures token usage on every LLM span and estimates cost in USD from model pricing.

Related Resources