LLM Cost Breakdown: Regression Fitting and Tiered Routing for Token-Based Billing

    Comparing the published per-token prices of different LLM services rarely reflects what you actually pay. Metering bases differ, platform products often hide individual prices behind a unified quota, and real cost swings heavily with input/output ratios and cache hit rates. This article shows how to treat your own usage and charges as observed data, fit unit costs with least-squares regression, convert them into effective per-token prices, and estimate how many tokens a budget window supports. It then introduces a four-tier task system and a working routing skeleton with budget guards and quality fallback, so that expensive tiers are reserved for planning and review while cheap tiers handle bulk execution. All figures come from an anonymized personal test and illustrate the method rather than any official pricing.

    1. Why You Can’t Just Plug the Price Sheet Into Your Math

    When comparing the cost of different LLM services, the common approach is to line up each vendor’s published per-token price and estimate a project budget from it. This approach has three problems.

    First, the metering bases differ. Some vendors price input and output separately, some distinguish cache hits from misses, and some set tiers by capability level, context length, or call mode. Comparing a single number hides the parts where the price gap is largest.

    Second, prices aren’t always public. Platform products often aggregate several models under one unified quota. What you see is usage and charges, not the unit price of each model, so “why did this month’s quota drain so fast” becomes a black box.

    Third, estimates drift. The input/output ratio varies by task, whether a cache hit occurs depends on how you call the service, longer contexts raise the input share, and an expensive model’s cost gets amplified quickly.

    A more reliable approach is to treat actual usage and charges as observed data, use regression to back out unit costs, and build a cost model of your own. The rest of this article walks through the whole process using an anonymized real-world case. The case involves one model-aggregation platform, four capability tiers, and a unified credit-based meter, all from the author’s personal testing and used here only as an example.

    1.1 The Abstracted Cost Model

    Write the charge for a single call as a linear combination of three token-usage terms: input, output, and cache hits.

    1. Cost = p_in · T_in + p_out · T_out + p_cache · T_cache

    Here T_in, T_out, and T_cache are the counts of non-cached input, output, and cache-hit tokens, while p_in, p_out, and p_cache are the unit costs (charge per token) for each. This is the most common form of a billing system: multiply each metered quantity by its unit price, then sum them up. If there is also cache-write billing or tiered pricing, you can add features or handle segments the same way.

    To convert to the per-million-token prices engineers are used to, just multiply by 10^6.

    1.2 Reverse-Engineering the Results

    Take the per-call records over a period (input tokens, output tokens, cache-hit tokens, corresponding charge) as samples, and estimate the three unit prices with least squares. The case’s fitted results are below. Values in the table have been normalized by dividing by the lightweight tier’s input price for easier comparison:

    Tier Positioning Input Output Cache hit
    Flagship Deep reasoning, complex planning 40 200 Not tracked separately
    Balanced Complex reasoning 16 56 Not tracked separately
    General Main execution 2 4 0.04
    Lightweight Batch simple tasks 1 1 Not tracked separately

    Two takeaways:

    • The gap in output prices between tiers is usually far larger than for input. In this case, the flagship tier’s per-token output cost is roughly 200x that of the lightweight tier, while input is about 40x.
    • Cache hits are very cheap. After a cache hit, the general tier’s input cost is only 2% of normal input.

    On fit quality: at the integer precision of credit rounding, R²≈1, and the relative residuals match the charge records closely. This only means that within the tested sample range, the bill can be treated as the output of the linear model above. It is not a promise about the pricing of any service.

    1.3 Why the Fit Holds Up

    The model stands on three premises:

    1. The metering relationship is itself linear. For the vast majority of token-based systems, the charge is a weighted sum of the individual usage terms.
    2. The features can’t be collinear. If every sample has a similar input/output ratio, the individual unit prices can’t be separated. When a task doesn’t charge for changing the ratio alone, you need to manually issue requests with different input/output ratios so the matrix has “something to learn.”
    3. The samples must cover the key dimensions. Include different context lengths, cache hit vs. miss, long outputs, and so on, so the model isn’t accurate only inside the range it has seen.

    So rather than “guessing prices,” the fit is a verifiable hypothesis test of the billing mechanism using data: small residuals mean the assumption holds; large residuals usually mean there are tiers, discounts, or a billing item you haven’t identified yet.

    2. From Unit Price to Budget: How Many Tokens a Window Supports

    Once you have unit prices, you can divide each charge by its usage to recompute per-million-token prices, or just solve with linear algebra. Let the charge for call i be y_i, its usage vector be x_i, and the unit-price vector be p:

    1. y_i = pᵀx_i — at least two independent calls let you solve for p

    Here is a worked example. The data is fictional: 3 calls give only 2 independent equations, so we assume the cache price equals the input price and solve for just the input and output prices:

    1. # Fictional example data: input tokens, output tokens, and charge per call
    2. records = [
    3. (10_000, 2_000, 120),
    4. (30_000, 1_000, 140),
    5. (50_000, 5_000, 300),
    6. ]
    7. # Jacobian matrix J: each row is the usage vector for one call
    8. J = [[r[0], r[1]] for r in records]
    9. y = [r[2] for r in records]
    10. JTy = [sum(j[k] * yk for j, yk in zip(J, y)) for k in range(2)]
    11. JTJ = [[sum(row[i] * row[k] for row in J) for k in range(2)] for i in range(2)]
    12. # Normal equations (JᵀJ) p = Jᵀy, solved here by hand via Gaussian elimination
    13. A = [JTJ[i][:] + [JTy[i]] for i in range(2)]
    14. for col in range(2):
    15. pivot = max(range(col, 2), key=lambda r: abs(A[r][col]))
    16. A[col], A[pivot] = A[pivot], A[col]
    17. for r in range(2):
    18. if r == col:
    19. continue
    20. f = A[r][col] / A[col][col]
    21. A[r] = [a - f * b for a, b in zip(A[r], A[col])]
    22. p = [A[i][2] / A[i][i] for i in range(2)]
    23. print(p) # roughly [0.004, 0.02], unit: credits/token

    In practice, it’s better to use a data-analysis library with pseudo-inverse capability, or switch to ridge regression when features are collinear. Whichever tool you use, the three checks—R², residuals, and condition number—can’t be skipped.

    2.1 Effective Unit Price: Converting a Budget Into Tokens

    Real requests have far more input than output. Assuming input is 80% and output is 20% by experience, and ignoring cache for now, define the effective unit price as:

    1. p_eff = 0.8·p_in + 0.2·p_out

    The tokens a budget window can support is roughly budget ÷ p_eff. Taking 60,000 credits per 5 hours and 600,000 credits per week as the example, the normalized results are:

    Tier Effective unit price (normalized) Tokens in 5 hours Tokens per week
    Flagship 72 ~420,000 ~4.17M
    Balanced 24 ~1.25M ~12.5M
    General 2.4 ~1.25M ~125M
    Lightweight 1 ~30M ~300M

    The same budget buys tens of times more tokens on some tiers than others. But this is not a reason to “always use the cheapest.” Now compute the effect of cache hits:

    • General tier with ~70% of input served from cache: p_eff = 0.8 × (0.3 × 2 + 0.7 × 0.04) + 0.2 × 4 = 1.3024, and tokens in 5 hours rise to ~23M—1.84x the no-cache case.
    • If the output share rises from 20% to 40%, the flagship tier’s effective price becomes 0.6 × 40 + 0.4 × 200 = 104, and the budget shrinks to about 69% of before.

    In short, the input/output ratio and the cache hit rate are the variables that actually decide real cost.

    2.2 Doing the Math on a Mixed Call

    A typical agent workflow is “plan first, then execute”: plan once with 80,000 input and 5,000 output; then execute 10 times, each with 40,000 input and 4,000 output.

    • All flagship: about 56,400 credits.
    • Plan on flagship, execute on general: about 2,280 credits, roughly 1/25 of the former.
    • Execute phase with 70% input cache hit: about 1,630 credits, roughly 1/35 of all-flagship.

    This is the quantitative basis for “the expensive model does the thinking, the cheap model does the work”: planning and review are small-volume, high-value reasoning, while execution is high-volume, pattern-driven work.

    3. Tiered Routing: Spending Each Token Where It Counts

    3.1 The Four-Tier Task System

    Layer Responsibility Recommended tier Selection basis
    L1 Planning & decomposition Requirements analysis, solution design, task breakdown Flagship Errors amplify downstream
    L2 Deep review Code review, complex defect localization, solution validation Flagship / Balanced Handles low-probability, high-impact issues
    L3 Complex reasoning Multi-step logic, tricky implementation Balanced Needs strong reasoning ability
    L4 Execution & batch Templated coding, doc generation, classification extraction General / Lightweight High volume, fixed patterns, verifiable

    Tiering isn’t a static config. Routing should also weigh four signals:

    1. Task type: code generation and repair, text summarization, and structured extraction place very different demands on capability.
    2. Context features: input size, whether there’s a long document, whether prefixes repeat.
    3. Historical performance: the first-pass rate and rework rate of a given task type on each tier.
    4. Budget level: when the quota is healthy, you can allow one tier up to trade cost for quality.

    3.2 A Routing Skeleton You Can Actually Deploy

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Task:
    4. kind: str # plan / review / codegen / summarize / extract
    5. input_tokens: int
    6. output_tokens: int
    7. cacheable_prefix: int = 0 # length of the stable, reusable prefix
    8. # Example prices: unit "credits/million tokens", for demonstration only;
    9. # replace with your own fit in practice
    10. PRICES = {
    11. "flagship": {"in": 80_000, "out": 400_000, "cache": 0},
    12. "balanced": {"in": 32_000, "out": 112_000, "cache": 0},
    13. "general": {"in": 4_000, "out": 8_000, "cache": 80},
    14. "lite": {"in": 2_000, "out": 2_000, "cache": 0},
    15. }
    16. def estimate_cost(tier: str, task: Task) -> float:
    17. p = PRICES[tier]
    18. cached = min(task.cacheable_prefix, task.input_tokens)
    19. fresh = task.input_tokens - cached
    20. return (fresh * p["in"] + cached * p["cache"]
    21. + task.output_tokens * p["out"]) / 1_000_000
    22. def choose_tier(task: Task, budget_left: float, pass_rates: dict) -> str:
    23. if task.kind in ("plan", "review"):
    24. return "flagship"
    25. if task.kind in ("codegen", "debug"):
    26. # when the flagship tier's first-pass rate is notably higher,
    27. # the rework cost may actually be lower
    28. if pass_rates["flagship"] - pass_rates["general"] > 0.15:
    29. return "flagship"
    30. return "balanced"
    31. return "lite"
    32. # The block below is meant to "downgrade everything when budget is tight,"
    33. # but written after return it never runs. Put it before tier selection.
    34. # if budget_left < estimate_cost(choose_tier(task), task):
    35. # tier = "general"

    Two notes:

    • Pulling prices and routing rules into config means you don’t have to touch code when the fit is refreshed.
    • The commented block at the end is a common mistake—the downgrade check must come before tier selection, otherwise the downgrade logic never fires.

    After picking a tier, add a budget guard and failure fallback:

    1. class BudgetGuard:
    2. """Expose the window budget as a queryable state; downgrade or queue when it's low."""
    3. def __init__(self, window_budget: float):
    4. self.cap = window_budget
    5. self.spent = 0.0
    6. def admit(self, cost: float) -> bool:
    7. return self.spent + cost <= self.cap
    8. def commit(self, cost: float) -> None:
    9. self.spent += cost
    10. @property
    11. def remaining(self) -> float:
    12. return self.cap - self.spent
    13. def run(task: Task, tier: str, guard: BudgetGuard):
    14. cost = estimate_cost(tier, task)
    15. if not guard.admit(cost):
    16. raise RuntimeError("insufficient budget; should queue or downgrade")
    17. result = invoke(tier, task) # call the model service for that tier
    18. guard.commit(cost)
    19. if not passed(result) and tier != "lite":
    20. # escalate and retry after repeated failures on a cheap tier,
    21. # to avoid infinite loops
    22. return run(task, "balanced", guard)
    23. return result

    A real downgrade chain is a trade-off among three constraints: budget, quality, and latency:

    • The budget guard decides “can we afford it”;
    • The quality check decides “was it worth it”;
    • The timeout/retry decides “can we afford to wait”.

    4. Making Cost Part of Your Engineering

    1. Align the billing basis first. Be clear about whether you’re counting tokens or credits, whether tax is included, and whether cache writes are included. Whether the window is rolling or fixed directly determines how you implement the budget guard.

    2. Fit with a reproducible method. Log the usage and charge of every call, estimate unit prices with least squares, and output R², max residual, and condition number. It’s best to persist the fit as a config file or registry rather than scattering it through the code.

    3. Cache is the biggest lever. Put stable content—system prompts, tool definitions, project conventions—at the very front of the request and keep the prefix byte-for-byte identical, which is the prerequisite for most cache mechanisms to work. Also set an invalidation policy for the cache: change the prefix and every subsequent request falls back to full price.

    4. Build a budget guard. Intercept requests at the gateway layer, estimate cost, check the balance, and then decide whether to admit, queue, downgrade, or reject.

    5. Add instrumentation and attribution. Log the model tier, task type, input/output tokens, cache-hit count, latency, first-pass rate, and charge for every call, so you can break cost down by task and scenario and find “which step burns the most money.”

    6. Keep a quality fallback. Cheap models can be wrong, so critical paths need validation, retries, and escalation. Otherwise the repeated calls from rework will eat right back into the savings.

    7. Re-fit periodically. Re-fit weekly or per release and watch whether unit prices drift. When the price structure changes, adjust the routing thresholds accordingly.

    8. Let the data speak. On cloud platforms such as Baidu AI Cloud, you can combine logging, monitoring alerts, and cost management to continuously observe token usage, charges, and budget levels with automated alerts, so cost optimization is grounded in evidence.

    5. Common Pitfalls

    1. Looking only at output price. In long-context scenarios input dominates, and the input price and cache hit rate matter more.
    2. Ignoring cache-prefix consistency. Inserting volatile content like timestamps or request IDs before a stable prefix will kill the cache entirely.
    3. Splitting the budget evenly. Dividing budget equally across tasks can starve critical tasks while letting low-value ones hog resources. Allocating by value is more sensible.
    4. Ignoring the cost of quality. The rework, retries, and human intervention from a cheap model’s mistakes often cost more than the unit-price difference.
    5. Treating the fit as official pricing. Regression results hold only within your own data range and can’t be extrapolated to other scenarios.
    6. Forgetting units. Mixing credits, currency, and tokens is a common reason bills don’t reconcile—unify your basis.

    6. Conclusion

    The essence of cost accounting is turning “it feels expensive” into “computable unit prices, constrainable budgets, and adjustable routing.”

    From regression to unit prices, to effective unit price adjusted for input/output ratio and cache hit rate, to a four-tier task system that reserves the expensive tiers for planning and review—this method transfers directly to any token-based model service.

    The numbers in this article come from anonymized personal testing and are for illustrating the method only; they don’t represent any official pricing. For actual token prices, credit rules, and budget quotas, follow the latest documentation of your chosen service and keep calibrating against your business data.