# LLM Inference Cost Calculation and Multi-Model Tiered Routing in Practice

    Learn how to calculate LLM inference costs from three-segment pricing and a reusable budget-to-capacity formula, calibrate the model with linear regression on real call data, and maximize cost efficiency with prefix caching and four-tier routing that lets expensive models handle high-value tasks while cheaper models take the bulk of execution. All prices and capacity figures are hypothetical examples.

    Introduction: Token Cost Is Moving from “Negligible” to “Make-or-Break”

    As large language models move from experimental setups into production systems, inference call volumes tend to grow exponentially, and cost quickly becomes a critical variable that decides whether a project can keep going. Many teams can comfortably absorb the bill in their first week online, yet by month three they are anxious about credits and quotas. The real question is not simply whether it is “expensive.” It is whether you can calculate costs in advance and control them at the system level.

    This article is not tied to any specific vendor. It breaks down a transferable engineering methodology:

    • Work backward from real call records to derive unit costs.
    • Work forward from a budget to determine the available capacity.
    • Use caching and tiered routing to get several times the actual output from the same budget.

    1. Understanding the Billing Model: Input, Output, and Cached Input

    Mainstream LLM inference services do not charge a single flat rate. Instead, billing is split into three segments, and this split is the starting point for cost optimization:

    • Input (prompt) cost: The context and instructions you send, billed per input token.
    • Output (completion) cost: The content the model generates. Autoregressive decoding produces tokens serially and is hard to parallelize fully, so output usually costs significantly more than input. It is commonly 3–6 times the input price.
    • Cached input cost: When multiple requests share the same prefix (system prompts, long documents, fixed examples), the platform can reuse the already-computed KV cache. The cached portion is charged at a very low rate and, ideally, can drop to a single-digit percentage of the normal input price.

    Once you understand these three segments, some straightforward practices can translate directly into real savings:

    • Send shorter contexts.
    • Reuse common prefixes.
    • Break generation tasks into smaller pieces.

    2. From Budget to Capacity: A Reusable Capacity Formula

    Suppose you have a credit budget B for a given time window and a typical workload made up of input tokens and output tokens. Let p_in be the input share and p_out the output share, with p_in + p_out = 1. The effective (weighted) cost is:

    1. effective_cost = p_in × rate_in + p_out × rate_out (credits per 1M tokens)
    2. total_tokens ≈ B / effective_cost × 1,000,000

    The following example uses a hypothetical credit-based plan to demonstrate the calculation (illustrative only; it does not represent the prices of any real product). It assumes a workload of 80% input + 20% output:

    Model tier Input (credits/1M) Output (credits/1M) Weighted cost (credits/1M) Tokens per 60,000 credits
    Flagship reasoning 80,000 400,000 144,000 ≈417,000
    High-performance general 32,000 112,000 48,000 ≈1.25M
    Efficient reasoning 4,000 8,000 4,800 ≈12.5M
    Lightweight 2,000 2,000 2,000 ≈30M

    Key insight: With the same budget and the same workload structure, capacity across tiers can differ by tens or even hundreds of times. On the output side, the unit price gap between the flagship and lightweight tiers can reach about 200 times (400,000 vs. 2,000 credits/1M). This is not a linear difference but an order-of-magnitude difference, and it directly determines which types of tasks you should assign to which tier.

    3. Cache Hits: An Underestimated Cost Lever

    Suppose a given efficient-tier model charges 2% of its normal input price for cache hits (e.g., 80 vs. 4,000 credits/1M). For workloads that rely on long contexts and repeated prefixes, caching can push input-side costs down to near zero. Such workloads include:

    • Knowledge-base Q&A
    • Code repository retrieval
    • Long-document summarization

    To make caching actually work, your engineering design needs to:

    • Place unchanged content (system prompts, tool definitions, fixed examples) at the very beginning of each request to maximize the stable prefix.
    • Avoid inserting time-varying fields, such as timestamps, random IDs, or session names, into the stable prefix. They break the prefix hash and cause cache misses.
    • Keep conversation history in multi-turn sessions growing in append-only fashion rather than being reordered, so prefix consistency is preserved.

    4. Calibrating the Cost Model with Real Data: Regression Fitting

    In production, the situation is often different. Platforms may report only total consumption without itemized unit prices, or unit prices may change with the plan, time of day, or model version. In these cases, you can calibrate your model by working backward from the data:

    Take the features you can observe for each call (input tokens, cached input tokens, output tokens, and model tier) as independent variables and credit consumption as the dependent variable. Then fit a linear regression:

    1. consumption ≈ a × tokens_in + b × tokens_in_cache + c × tokens_out + d
    1. import numpy as np
    2. # Each sample: [input tokens, cached input tokens, output tokens]
    3. X = np.array([
    4. [120000, 0, 8000],
    5. [ 50000, 40000, 3000],
    6. [200000, 180000, 12000],
    7. # ... more real call samples
    8. ], dtype=float)
    9. y = np.array([15200.0, 6100.0, 30500.0, ...]) # Measured credit consumption per call
    10. coef, *_ = np.linalg.lstsq(X, y, rcond=None) # Back-calculate a, b, c
    11. y_pred = X @ coef
    12. r2 = 1 - np.sum((y - y_pred) ** 2) / np.sum((y - y.mean()) ** 2)
    13. print("Input/cache/output unit cost:", coef, " R² =", r2)
    • The coefficients a, b, and c are the back-calculated unit consumption rates for input, cached input, and output.
    • When the coefficient of determination R² is close to 1 and the residuals are close to zero, the model almost perfectly reproduces the actual billing logic. This lets you not only estimate costs accurately but also forecast budgets, trigger anomaly alerts, and attribute costs.
    • If the residuals are systematically too large, there are usually factors the model does not capture, such as minimum billing granularity, concurrency or time-of-day coefficients, or volume discounts. You then need to add features and refit.

    5. Multi-Model Tiered Routing: Let Expensive Models “Think” and Cheap Models “Work”

    Once you know the real unit cost and capacity of each tier, you can design routing that allocates compute according to task value. The core principle can be stated in one sentence: Let expensive reasoning capability handle only high-value decisions, and push bulk, repetitive execution down to cheaper models.

    Here is a practical four-tier routing example:

    • Flagship tier: Planning and decomposition, architecture design, final review, and high-risk outputs. It has the lowest call share but the highest value per unit.
    • High-performance tier: Complex reasoning, multi-step logic chains, and problems that require stronger generalization.
    • Efficient tier: The main execution workhorse. It handles the vast majority of routine generation, code completion, and structured extraction.
    • Lightweight tier: Bulk simple tasks, such as classification and tagging, format conversion, template-based rewriting, and large-scale filtering.
    1. def route(task):
    2. if task.risk == "high" or task.needs_planning:
    3. return "flagship"
    4. if task.complexity >= 0.6:
    5. return "high_perf"
    6. if task.batch and task.complexity < 0.3:
    7. return "lightweight"
    8. return "efficient"

    You can also combine this with a cascade strategy: have the cheap model answer first and escalate only when confidence is low. This helps lower the average cost with essentially no loss in quality.

    6. Engineering Implementation: Building Cost Optimization into the System

    • Full-pipeline instrumentation: Log the model tier, token breakdown, cache hit, credit consumption, and latency of every call. This builds a cost dataset you can analyze.
    • Unified gateway abstraction: Add a gateway layer between applications and models to hide backend differences. Routing, rate limiting, fallback, and switching then become configurable policies.
    • Budget and quota governance: Set quota limits and alert thresholds per team, project, or environment. This prevents a few runaway calls from consuming the entire budget.
    • Continuous optimization loop: Periodically recheck unit costs using the method in Section 4. Recalibrate whenever the model version or plan rules change.

    Mainstream cloud platforms, such as Baidu AI Cloud, generally provide usage monitoring, billing details, and monitoring alerts. Leveraging these observability and quota management capabilities can turn “reviewing the bill after the fact” into “controlling usage before the fact.”

    Conclusion: Treat Cost as a Modelable Engineering Problem

    Three points deserve emphasis:

    1. All unit prices and capacity figures in this article are hypothetical values used to illustrate the methodology. They do not represent the actual billing of any real product.
    2. Plan rules, cache strategies, and model versions change over time, so any cost model needs continuous recalibration with the latest real data.
    3. Cost optimization must not come at the expense of output quality. The value of tiered routing lies in saving where you can and spending where you should.

    Treat cost as an engineering problem you can model, fit, and schedule, rather than a bill you passively accept. Only then can you keep control of how much “thinking” and “working” cost, even as token usage keeps expanding.