LLM API Cost Estimation and Model Selection: A Practical Guide

    This guide explains why per-token price lists fail to predict real LLM API bills and how to build a practical cost model instead. It breaks down the three token types that providers bill separately, the typical multiplier relationships between input, cached input, and output pricing, and how those multipliers should drive optimization priorities. You will find reusable estimation formulas, a scenario-based cost table, a sample Python cost calculation, and engineering patterns such as tiered routing, semantic caching, observability, and elastic capacity. The article closes with a selection framework that compares total cost per completed task rather than headline unit prices.

    1. Why a Price List Cannot Predict Your Actual Bill

    When evaluating LLM APIs, many teams focus on a single number: the price per million tokens. Yet the real bill often differs from intuition by several multiples. The reason is straightforward: the cost of a single call is determined by several billing dimensions at once, and a price list only shows part of them.

    Across common industry billing practices, mainstream platforms typically split a request into three token categories, each priced separately:

    • Regular input tokens: text that fully enters the model context and does not hit any cache;
    • Cached input tokens: the portion reused after a prefix cache hit, priced significantly lower than regular input;
    • Output tokens: content generated by the model, usually priced at several times the regular input rate.

    The two price structures cited in the original article illustrate a common pattern: across multiple model families, the output rate is roughly 6x the regular input rate, while the cache-hit rate is about one-tenth of the regular input rate. These two multipliers form the backbone of any cost model.

    So the first step in model selection is not comparing prices, but writing down your own cost formula:

    1. Cost per call = Input tokens × P_in
    2. + Cached tokens × P_cache
    3. + Output tokens × P_out

    Here, P_out ≈ 6 × P_in and P_cache ≈ 0.1 × P_in are typical order-of-magnitude relationships in the industry. Once the formula is on paper, you will notice that only three variables actually need estimating: input size, cache hit rate, and output length.

    2. Token Multipliers Determine Your Optimization Priorities

    2.1 The output multiplier is the most underestimated cost amplifier

    Suppose a request has 2,000 input tokens and 300 output tokens. With output priced at 6x input, the output portion contributes about 0.9x the cost of the input portion. But when output grows to 2,000 tokens, output cost quickly overtakes input and becomes the main line item on the bill. For any scenario involving long-form generation, full-function code completion, or structured report output, output length is the first optimization target.

    Practical ways to constrain it include: explicitly limiting the output format and fields, using a JSON Schema to constrain structure, splitting “explanatory text” and “structured results” into two separate calls, and using segmented generation with incremental validation for very long outputs.

    1. {
    2. "max_output_tokens": 800,
    3. "response_format": {"type": "json_schema"},
    4. "instructions": "Return fields only, with no explanatory paragraphs"
    5. }

    2.2 Cache hit rate is the most wasted discount

    The cache-hit price is often just one-tenth of the regular input price, yet many applications never capture this discount at all. Whether a cache can be hit depends on whether the request prefix stays stable. Embedding timestamps, random session IDs, or user nicknames in the system prompt makes the prefix different every time, so the cache naturally misses.

    The practical recommendation is to refactor prompts for “prefix stability”:

    1. [Stable prefix] Role definition + tool descriptions + output spec + a few fixed examples
    2. [Variable suffix] Current user input, retrieved snippets, context summary

    Simply reordering the content without changing it often improves the hit rate noticeably. Note that caches usually have a time-to-live window, and cache hits are runtime behavior, so they should not be treated as a strong-consistency dependency in your architecture design.

    2.3 Input size determines feasibility for long-context scenarios

    Tasks such as long-document review and whole-repository code comprehension can involve hundreds of thousands of input tokens. Even at a low unit price, the absolute cost is hard to ignore. A common approach is to first use keyword retrieval or vector recall to compress candidate snippets down to a few thousand tokens, then let the model do fine-grained ranking and summarization. This is the two-stage “recall first, then read closely” pipeline.

    3. A Reusable Cost Estimation Method

    It is worth maintaining an estimation sheet that breaks business workloads into typical tiers and plugs each one into the formula:

    Scenario tier Input tokens Cache hit rate Output tokens Relative cost
    Short Q&A 800 0% 200 Low
    Document summarization 8000 30% 1200 Medium
    Code generation 4000 50% 2000 Medium-high
    Long-document review 60000 20% 1500 High

    When estimating, always use the “output-to-input ratio” rather than looking at the input price alone. As a rule of thumb, when the output-to-input ratio exceeds 1:1, the selection decision shifts noticeably toward tiers with a lower output price; when the ratio falls below 1:4, the input price and the cache discount become the decisive factors.

    Paired with a load-testing script, you can calibrate estimation error against a real traffic distribution:

    1. # Example: estimate per-request cost from a real workload distribution
    2. def estimate_cost(reqs, price):
    3. total = 0.0
    4. for r in reqs:
    5. total += r["input"] * price["in"]
    6. total += r["cached"] * price["cache"]
    7. total += r["output"] * price["out"]
    8. return total / len(reqs) / 1_000_000 # cost per request (based on per-million-token pricing)

    4. Turning Cost Optimization into Engineering Structure

    4.1 Tiered routing: reserve expensive models for hard problems

    Splitting requests by complexity is one of the highest-return changes you can make. You can use upfront rules (input length, whether tool calls are needed, whether multi-step reasoning is required), or use a lightweight model for confidence self-assessment and escalate low-confidence cases to a higher-capability tier. In engineering practice, teams usually keep a configurable threshold table so it can be adjusted weekly.

    4.2 Semantic caching and result reuse

    For high-frequency repeated questions, you can build a result cache at the application layer and return directly on a hit, bringing the cost to zero. Be sure to set a sensible expiration policy and enforce user isolation to avoid cross-tenant data leakage.

    4.3 Observability first

    Without measurement there is no optimization. It is recommended to log the input, cache-hit, and output token counts and the cost of every call into a logging service, configure daily budget thresholds and anomaly-spike alerts in your monitoring, and keep cost dashboards broken down by business line and by endpoint. A common general practice at Baidu AI Cloud in these scenarios is to connect model calls to a unified log collection and monitoring/alerting system, using tag dimensions to attribute costs.

    4.4 Capacity and elasticity

    To handle traffic peaks, you can use container platform auto-scaling and message queues for peak shaving, queuing burst requests instead of scaling up immediately. This controls cost while keeping latency stable.

    5. Selection Conclusion: Compare Cost per Task, Not Unit Price

    After a price change, the correct comparison metric is the “total cost of completing the same business task,” including model fees, retry overhead, manual review cost, and migration/integration cost. The recommended evaluation process is:

    1. Build an evaluation set from real business samples and confirm the quality baseline is met;
    2. Among models that meet the baseline, estimate cost per task using the formula above;
    3. Run a small-traffic canary to validate the cache hit rate and the output length distribution;
    4. Review the cost dashboard on a weekly cycle and adjust routing thresholds dynamically.

    With this approach, teams do not need to chase any single “best value” model. Instead, they can quickly identify the current optimum for their workload amid price fluctuations, and turn optimization capability into reusable engineering assets.