LLM Token Cost Modeling and Tiered Model Routing
Learn how to model LLM token costs from usage and billing data, estimate token capacity within a budget, and route tasks across model tiers. This article covers linear regression, cache-aware billing, and practical monitoring to balance output quality with cost.
1. Why Token Costs Need Modeling, Not Guesswork
Applications built on large language models—such as coding assistants, document-processing pipelines, and multi-turn agents—often use several models. Some handle complex reasoning well; others offer faster responses at lower prices. Because billing rules vary substantially across models, intuitive cost estimates can be misleading.
A more reliable approach is to treat billing as an observable mathematical process. By recording input tokens, output tokens, cache-hit tokens, and the corresponding charges or credits consumed for each call, you can use regression to infer each model’s unit cost coefficients.
This turns cost from a black box into something measurable and explainable.
2. The Basic Structure of Token Billing
Before building a cost model, identify the main billing dimensions:
- Input tokens: Prompts, context, system instructions, and other content sent to the model.
- Output tokens: Content generated by the model, typically billed at a substantially higher rate than input.
- Cache-hit tokens: Repeated request prefixes served from a cache. Depending on the billing rules, these may cost only a small fraction of the standard input rate.
Input and output prices are usually asymmetric: output can cost several times more than input. Cache hits can significantly reduce the cost of repeated context, sometimes to just a few percent of the normal input price.
Together, these components determine the actual bill.
3. Inferring Unit Costs with a Linear Model
For a call with a total charge of cost, a linear cost model can be written as:
cost = w_in * input_tokens+ w_out * output_tokens+ w_cache * cache_hit_tokens+ b
Here, w_in, w_out, and w_cache are the unit cost coefficients to estimate, and b is the intercept. With enough real usage samples, you can fit these parameters using least squares:
import numpy as np# Each row: [input tokens, output tokens, cache-hit tokens, 1 (intercept)]X = np.array([[80000, 20000, 0, 1],[50000, 10000, 30000, 1],[120000, 5000, 0, 1],# ... Additional real usage samples], dtype=float)# Actual credits or charges deducted for each cally = np.array([12.4, 6.1, 9.8], dtype=float)# Estimate unit cost coefficients using least squaresw, residuals, rank, _ = np.linalg.lstsq(X, y, rcond=None)w_in, w_out, w_cache, b = w# Evaluate fit quality using the coefficient of determination, R^2pred = X @ wss_res = np.sum((y - pred) ** 2)ss_tot = np.sum((y - y.mean()) ** 2)r2 = 1 - ss_res / ss_totprint(f"R^2 = {r2:.4f}, residuals = {residuals}")
The rows above illustrate the method; collect enough real samples to estimate all four parameters reliably.
With sufficient, clean data, an R² close to 1 and small residuals indicate that the fitted model closely matches observed billing. Instead of guessing what each token costs, you have coefficients grounded in actual charges.
These coefficients are not universal. They vary by platform, model, and billing period, so use your own billing records rather than fixed reference values.
4. Estimating Token Capacity Within a Budget
Once you know the unit costs, you can estimate how many tokens a model can process within a fixed budget, such as a five-hour or weekly credit allowance.
Let the budget be B, the input share be p_in, and the output share be p_out. Ignoring caching for this approximation:
Total tokens ≈ B / (p_in * w_in + p_out * w_out)
For an illustrative workload consisting of 80% input and 20% output, a high-priced reasoning model might support only hundreds of thousands of tokens per hour within a given hourly budget, while a low-cost lightweight model might support tens of millions.
These figures are illustrative, not price or performance benchmarks. The key point is that budget-limited token capacity can differ by two or three orders of magnitude. That gap provides the economic basis for tiered model routing.
5. Tiered Routing: Expensive Models Reason, Cheaper Models Execute
A cost profile makes it possible to route tasks according to their complexity:
- High-cost reasoning models: Handle planning, task decomposition, and final review—steps where fewer calls can deliver substantial value.
- Mid-priced general-purpose models: Handle intermediate tasks that require reasoning but are not the most demanding.
- Low-cost, fast models: Perform frequent execution tasks, code completion, and format conversion.
- Lightweight models: Process simple, batchable, parallel tasks where throughput matters most.
The routing logic can be expressed as pseudocode:
def route(task):if task.needs_deep_reasoning or task.is_final_review:return "reasoning_model" # High cost, selective useif task.is_batch_simple:return "lite_model" # Low cost, high volumeif task.is_execution_heavy:return "fast_model" # Main execution workloadreturn "general_model" # General-purpose fallback
The guiding principle is simple: use expensive models for reasoning and cheaper models for execution.
6. Caching: An Often-Underused Cost Lever
Beyond tiered routing, cache reuse is another major way to reduce costs.
Placing stable system prompts, long document prefixes, and repeated context at the beginning of requests helps maximize prefix reuse. Where discounted cache billing applies, those repeated tokens can be charged at a much lower rate.
In practice:
- Keep unchanged content at the front of requests and maintain a stable prefix.
- Place frequently changing content later so it does not disrupt the reusable prefix.
- Reuse the same prefix across batch tasks to reduce the cost per task.
7. Practical Implementation Considerations
- Keep the data clean. Avoid mixing anomalous calls into the fitting dataset, as they can distort the estimated coefficients.
- Refit as models and pricing change. Billing rules and rates may change, so periodically update the cost model using recent billing data.
- Protect task quality. Tiered routing should not compromise critical results. Retain higher-capability models for planning and review where needed.
- Maintain observability. Use logging, monitoring, and alerts to continuously collect token usage and charges, creating a feedback loop for cost management.
Effective token cost management follows a clear sequence: model first, route second, optimize third. Regression makes billing explainable, tiered routing directs the budget toward high-value work, and caching reduces repeated overhead. Together, these practices make the balance between quality and cost measurable.
