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

The MLflow experiment dashboard showing the Cost Breakdown donut by model and the Cost Over Time chart, from MLflow demo data
Quick Navigation:
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.
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 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.
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.
| Level | Token usage | Cost (USD) |
|---|---|---|
| Span (one LLM call) | mlflow.chat.tokenUsage: input, output, total | mlflow.llm.cost: input, output, total |
| Trace (whole request) | trace.info.token_usage | trace.info.cost |
| Feature | MLflow version |
|---|---|
| Token usage tracking | 3.2.0 or later |
| Cost tracking | 3.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.
1. Install MLflow 3.10 or later with the genai extra and start a server.
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.
import mlflowfrom openai import OpenAImlflow.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.
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 USDprint(usage)if cost:print(f"Total cost: ${cost['total_cost']:.6f}")
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.
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.
import mlflowtraces = 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}")
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.
from collections import defaultdictby_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.
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.
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:
import mlflow@mlflow.tracedef 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"
| Approach | What you get | Limits |
|---|---|---|
| Provider billing dashboard | Exact invoiced spend per account, project, or API key | No link to prompts, agent steps, or quality; one provider at a time |
| Custom logging in your code | Whatever fields you decide to log | You maintain the price tables, schema, and charts |
| MLflow Tracing | Tokens and estimated cost per span and trace, next to the prompt, response, latency, and evaluation scores | Cost 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 →