LLM Invocation Cost Estimation and Multi-Model Routing: A Practical Guide

    This article presents a practical framework for estimating large language model invocation costs and implementing multi-model routing. It covers unified cost metrics, a token-level cost formula, the impact of cache hit rates and input/output ratios, call amplification, price sensitivity, tiered routing, unit conversion, and a production checklist.

    1. Turning “Cost-Effectiveness” into Calculable Metrics

    When discussing LLM invocation costs, a common approach is to compare “how many tokens can be processed per unit of spend.” This metric is useful, but it hides three issues.

    First, pricing scopes are not uniform. Input, output, cache hits, and cache misses are usually priced separately, so directly comparing nominal unit prices can easily lead to errors.

    Second, package quotas and pay-as-you-go billing use different metering methods. Whether a quota is measured in tokens or in monetary value determines the actual consumption of the same task.

    Third, invocation patterns strongly affect consumption. For the same task, different context organization methods can lead to several-fold differences in token consumption.

    Therefore, a more reasonable approach is to define a unified measurement unit first, then make horizontal comparisons. At minimum, use two metrics:

    • Unit cost: the cost per million effective tokens, used to compare the base prices of different options.
    • Task cost: the average cost to complete a standard task (for example, fixing a defect or generating a module), used to measure end-to-end efficiency.

    Unit cost reflects price, while task cost reflects price multiplied by efficiency. A model with a lower unit price but frequent retries may have a higher task cost than a model with a higher unit price and a higher first-pass success rate.

    2. Basic Formula for the Cost Model

    Assume that a request contains three types of tokens: input that misses the cache, input that hits the cache, and output. If the three types are billed at different unit prices, the cost of a single request is:

    C = (N_miss × P_miss + N_hit × P_hit + N_out × P_out) / 1,000,000

    Here, P is the unit price per million tokens (unit: RMB), and N is the corresponding number of tokens.

    The following code encapsulates this formula as a function for batch accounting of historical invocation logs:

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Price:
    4. miss_in: float # input that misses the cache, RMB per million tokens
    5. hit_in: float # input that hits the cache, RMB per million tokens
    6. out: float # output, RMB per million tokens
    7. @dataclass
    8. class Usage:
    9. miss_in_tokens: int
    10. hit_in_tokens: int
    11. out_tokens: int
    12. def request_cost(u: Usage, p: Price) -> float:
    13. return (u.miss_in_tokens * p.miss_in
    14. + u.hit_in_tokens * p.hit_in
    15. + u.out_tokens * p.out) / 1_000_000
    16. def total_cost(usages: list[Usage], p: Price) -> float:
    17. return sum(request_cost(u, p) for u in usages)

    Usage data should come from the usage statistics fields in API responses. Different providers use different field names and accounting methods, so refer to the relevant API documentation when integrating.

    3. Key Variables Affecting Cost

    1. Cache Hit Rate

    Agent-style applications resend system prompts, tool definitions, and conversation history in every invocation round, so the cache hit rate is usually high. When the hit rate is high, the cache-hit unit price determines most of the cost.

    Let the cache-hit unit price become k times its original value under a fixed budget, and let the hit rate be h. Then the proportion of effective input that the budget can handle is:

    R = 1 / (h × k + (1 − h))

    For example, with h = 0.9 and k = 5, R ≈ 0.22. The same budget can handle only about 22% of the original effective input, a drop of nearly 78%. This is the result of a formula calculation and does not represent any specific price change. It shows that when evaluating costs, changes in both the hit rate and the cache-hit unit price must be considered. Looking only at the nominal unit price can easily underestimate risk.

    2. Input-to-Output Ratio

    For tasks such as code retrieval and log analysis, input is far greater than output, and the input unit price dominates. Generation tasks are the opposite. Before selecting a model, first measure the input-to-output ratio of your own business, then decide which unit price to focus on.

    3. Call Amplification

    A multi-step Agent may make dozens of model calls to complete one task. The cost of a single call multiplied by the number of calls is the true task cost. Reducing ineffective loops and limiting tool-call depth are often more direct ways to lower costs than switching models.

    4. Price Change Risk

    Model service prices can change. In budget models, price parameters should be configurable, and sensitivity analysis should be performed: calculate monthly costs when unit prices rise by 20%, 50%, and 100%, respectively, to identify the budget’s tolerance boundary.

    4. Tiered Routing: Let Low-Cost Models Handle Exploratory Work

    Not all tasks require the strongest model. A common tiering approach is as follows.

    • High-capability model: responsible for solution design, core code generation, and complex reasoning.
    • Low-cost model: responsible for exploratory work such as file search, code structure summaries, log filtering, and test case drafts.

    Blended cost can be estimated using a weighted average. Let the unit price of the low-cost model be r times that of the high-capability model, and let its share of requests be s. Then the cost ratio of the blended approach relative to using the high-capability model for everything is:

    M = s × r + (1 − s)

    Assuming r = 0.1 and s = 0.7, M = 0.37, meaning the blended approach costs about 37% of using the high-capability model for everything. This is a calculation example; actual values should be determined from your own price and traffic data.

    The routing logic can be written as a simple routing function:

    1. TASK_TIERS = {
    2. "search": "tier_low",
    3. "summarize_logs": "tier_low",
    4. "explore_repo": "tier_low",
    5. "design": "tier_high",
    6. "codegen": "tier_high",
    7. "review": "tier_high",
    8. }
    9. def pick_model(task_type: str) -> str:
    10. # Unknown task types default to the high-capability model to avoid quality degradation from misclassification of critical tasks
    11. return TASK_TIERS.get(task_type, "tier_high")

    The default routing policy should favor quality. Before tiering, validate the low-cost model’s success rate on exploratory tasks using a fixed evaluation set. Otherwise, the savings may be offset by rework.

    5. Unified Units: From Per Million Tokens to Per Hundred Million Tokens

    Service prices are usually billed per million tokens, while business budgets are often discussed per hundred million tokens. The conversion is:

    Cost per 100 million tokens = unit price per million tokens × 100

    Unit price per million tokens (RMB) Cost per 100 million tokens (RMB)
    0.01 1
    0.02 2
    0.03 3

    There is no universal standard for an “acceptable price range”; it should be determined by business value. A practical way to judge is:

    Acceptable cost per task = business value generated per task × acceptable cost share

    The team can use this to set its own threshold, then compare it with the actual task cost.

    6. Implementation Checklist

    1. Calculate costs using real invocation logs, not just unit prices.
    2. Put model selection and price parameters into configuration, so that service or model changes require only configuration updates.
    3. Set budget alerts and hard limits for usage.