Tutorial

Tracking LLM Token Usage and Costs

Capture usage from every model response, attribute spend to features and tenants, and set budgets that trip before a runaway loop becomes a surprising invoice.

On this page

  1. Introduction
  2. Why Token Accounting Matters
  3. Capturing Usage from Responses
  4. Attributing Cost to Features and Tenants
  5. Budgets and Circuit Breakers
  6. Streaming and Missing Usage
  7. Reconciliation Against Invoices
  8. Dashboards and Alerts
  9. Cheaper Models and Caching
  10. Testing the Accounting
  11. Sources

Introduction

Model spend is easy to start and hard to see. A new feature ships, a retry loop misbehaves, and the monthly invoice reveals it weeks after the damage. The discipline is the same one you apply to any unbounded resource: measure the consumption per request, attribute it to the feature and tenant that caused it, and enforce a budget that stops the bleeding automatically. Token accounting is the connective tissue between product decisions and the bill.

Why Token Accounting Matters

Every request has a price, and the price varies by model, by input and output length and by caching. Without per-request accounting you cannot answer basic questions: which feature costs the most, whether a prompt change raised spend, or which tenant is unprofitable. An average cost per request hides the heavy tail, and the heavy tail is where the budget dies. Measuring at the request level is what turns a single number into a controllable dial.

from dataclasses import dataclass
import tiktoken

PRICES = {  # USD per 1M tokens
    "gpt-4o": {"in": 2.50, "out": 10.00},
    "gpt-4o-mini": {"in": 0.15, "out": 0.60},
}
ENC = tiktoken.get_encoding("cl100k_base")

@dataclass
class Usage:
    model: str
    input_tokens: int
    output_tokens: int

    def cost(self) -> float:
        p = PRICES[self.model]
        return (self.input_tokens * p["in"] + self.output_tokens * p["out"]) / 1_000_000

def record(usage: Usage, *, tenant: str, feature: str, prompt_version: str, request_id: str):
    # Prefer provider reported counts; fall back to a labelled estimate.
    sink.write({
        "tenant": tenant, "feature": feature, "prompt_version": prompt_version,
        "request_id": request_id, "model": usage.model,
        "input_tokens": usage.input_tokens, "output_tokens": usage.output_tokens,
        "cost_usd": usage.cost(),
    })

Capturing Usage from Responses

Most provider responses include a usage object with input and output token counts, so record it rather than estimating from character length. For streaming responses the usage may arrive only in a final chunk or require a separate call, so accumulate it explicitly. Estimate when the provider omits usage, but label estimates as estimates so they never contaminate reconciliation. Store the model, the counts, the request id and the cache status on every record.

class BudgetGuard:
    def __init__(self, store, limit_usd: float, window_seconds: int):
        self.store, self.limit, self.window = store, limit_usd, window_seconds

    def check(self, tenant: str, feature: str, est_cost: float) -> str:
        spent = self.store.spend(tenant, feature, self.window)
        if spent + est_cost > self.limit:
            return "refuse"
        if spent + est_cost > self.limit * 0.8:
            return "downgrade"  # route to a cheaper model before the hard stop
        return "allow"

    def charge(self, tenant: str, feature: str, cost: float) -> None:
        self.store.incr(tenant, feature, cost, self.window)

Attributing Cost to Features and Tenants

A cost number is only actionable when it is attributed. Tag every request with the feature, the tenant, the prompt version and the environment, and aggregate spend along each of those axes. Per-feature attribution explains what to optimise; per-tenant attribution exposes abuse and informs pricing. Attribution also propagates into trace data, so an expensive request can be found and inspected rather than merely counted.

Budgets and Circuit Breakers

A budget that only reports after the fact is a post mortem. Enforce budgets at request time: refuse or downgrade a request when a tenant or feature has consumed its allowance for the window. Use rolling windows rather than calendar months so a spike early in the month does not hide behind a quiet start. Degrade gracefully, for example to a cheaper model, instead of failing users outright when a soft limit is crossed, and reserve the hard stop for genuine runaway conditions.

Streaming and Missing Usage

Streaming complicates accounting because tokens are produced incrementally and the usage summary may be absent if the client disconnects. Count output tokens as they are emitted so a disconnected stream still contributes to the record, and reconcile against the provider usage when it does arrive. Input tokens are known before the call, so log them at request start; this split lets you attribute cost even for interrupted generations.

Reconciliation Against Invoices

Your internal totals will drift from the provider invoice due to retries, caching, failed calls and rounding. Reconcile periodically and explain the gap: if the invoice is higher, you are probably not counting retried or rejected calls; if lower, you may be double counting. Treat a persistent gap as a bug in the instrumentation, because an accounting system that disagrees with the bill cannot be used to make decisions.

Dashboards and Alerts

Expose cost per feature, per tenant and per thousand requests, with day over day deltas so a change is visible immediately. Alert on the derivative, not just the total: a sudden rise in cost per request signals a prompt or model change, while a rise in total cost may simply be growth. Set a forecast alert when the projected month end spend exceeds budget, giving days of warning instead of a surprise at close.

Cheaper Models and Caching

Once cost is visible, the levers become obvious: route simple requests to a cheaper model, cache repeated answers, shorten prompts by removing redundant context, and cap output length. Measure the quality cost of each lever with your evaluation harness so you trade spend for quality deliberately rather than by accident. The cheapest request is the one you never make, which is why caching and routing often beat prompt micro-optimisation.

Testing the Accounting

Write tests that feed synthetic responses into the accounting layer and assert that tokens, cost and attribution are recorded correctly, including for a disconnected stream and for a retried call. Include a test that a budget crossing triggers the expected downgrade or refusal. Accounting bugs are silent and cumulative, so covering them with tests is the only way to trust the numbers you steer by, and an untested accounting layer produces confidently wrong numbers that are worse than none at all.

Sources

Sources: OpenAI usage API, OpenAI pricing, tiktoken.

FAQ

Should I estimate tokens or read them from the response?
Read provider reported counts whenever available, because estimates drift, especially with different tokenizers. Use estimates only as a fallback and label them so they do not contaminate reconciliation.
Why does my total not match the invoice?
Typical causes are uncounted retries, cached requests billed differently, and failed calls that still consume input tokens. Reconcile and explain the gap, then fix the instrumentation rather than the invoice.

Related Examples