LLM API Cost Analysis and Model Selection: A Practical Guide

    This guide explains how to evaluate large language model API costs and choose the right model tier. It breaks down real billing into input, cached input, and output tokens, provides a cost formula for estimating per-request and daily spend, and shows how tiered models, prompt caching, output length control, and routing can reduce expenses. A four-step evaluation framework and common pitfalls help teams balance cost and quality.

    1. Why the Lowest Unit Price Is Rarely the Best Value

    When building AI applications, teams often fixate on a single number: the price per million input tokens. Real bills are driven by three token types—regular input, cache-hit input, and model-generated output. Their unit prices usually differ by an order of magnitude, and output is often several times more expensive than input.

    This means a workload with short inputs and long outputs (long-form generation, code completion, structured extraction) is dominated by output costs. A workload with long inputs and short outputs (long-document summarization, retrieval-augmented Q&A) is driven mainly by input volume and cache hit rate.

    So the first step is not to compare prices, but to translate business requests into a quantifiable token profile.

    2. Cost Model: Write the Bill as a Formula

    Let I be regular input tokens, C cache-hit tokens, and O output tokens for a single request, with unit prices p_in, p_cache, and p_out (per million tokens). The cost per request is:

    1. Cost = (I * p_in + C * p_cache + O * p_out) / 1_000_000

    For load testing or capacity planning, you can estimate daily cost with an approximate model:

    1. DailyCost ≈ QPS * 86400 * (I_avg * p_in + C_avg * p_cache + O_avg * p_out) / 1_000_000

    Here I_avg, C_avg, and O_avg are average token counts. In practice, make these three variables configuration items rather than hard-coded values, so you can run sensitivity analysis across model tiers.

    A key implication: when output costs 6 times more than input, a 10% increase in output tokens can contribute far more to the total bill than the same proportional change on the input side. Compressing output usually reduces cost more directly than compressing input.

    3. Three Model Tiers: Matching Capability, Cost, and Use Case

    General-purpose LLM APIs from major cloud providers typically offer a tiered product matrix, which can be abstracted into three levels:

    • Flagship: complex reasoning, multi-step planning, and specialized domain tasks; highest unit price, with output typically 5–6 times the input price.
    • Balanced: a compromise between capability and cost, suitable for most core business flows.
    • Lightweight: high concurrency, low latency, and cost-sensitive scenarios, with significantly lower input and output prices.

    The point of tiering is to avoid sending every request to the most expensive tier. A common mistake is routing all traffic to the flagship model, so that 80% of the bill comes from simple requests a lightweight model could handle.

    4. Cache Hits: The Underrated Cost Lever

    Cached input is often priced at around one-tenth of regular input. To capture this benefit, design the request prefix to be stable and reusable:

    1. # Put the long, stable system prompt and knowledge prefix first to improve cache hit rate
    2. SYSTEM_PROMPT = "You are an enterprise knowledge base assistant. Answer strictly based on the provided material." # long and stable
    3. def build_messages(question: str, retrieved: str):
    4. return [
    5. {"role": "system", "content": SYSTEM_PROMPT},
    6. {"role": "user", "content": f"Material: {retrieved}\nQuestion: {question}"},
    7. ]

    The rule is to place long, fixed content at the front and the changing user input at the end. Avoid inserting volatile fields such as timestamps or random IDs at the beginning of the prompt, or the cache will keep missing.

    5. Output Length Governance: The Most Direct Way to Cut Costs

    • Set explicit output format and length limits, and use structured output to reduce redundant explanation.
    • For summarization, classification, and extraction tasks, require “return only the result, not the reasoning process.”
    • Use streaming responses and early termination at the application layer to avoid generating useless long-tail content.
    • For very long generation tasks, split them into stages and reuse intermediate results to avoid repeated generation.

    Example constraint:

    1. Output requirement: return JSON only, with fixed fields, no more than 200 words in total, and no explanation.

    6. Tiered Routing: Make Cost Efficiency an Architectural Capability

    A practical approach is to add a routing layer that first runs a lightweight classification, then decides which model tier to call:

    1. def route(task):
    2. if task["complexity"] == "high" or task["need_reasoning"]:
    3. return "flagship"
    4. if task["latency_sensitive"] and task["short_output"]:
    5. return "light"
    6. return "balanced"

    Combined with monitoring, alerting, and logging, build dashboards for each tier’s call volume, average tokens, cache hit rate, and failure rate. Only then can you continuously calibrate routing thresholds. Without observability, cost optimization often just moves spending from one line item to another.

    7. Evaluation Framework: Four Steps to Find Your Best Value

    1. Sample: draw representative requests from real traffic and measure the distribution of input/output lengths and the reusable cache ratio.
    2. Model: plug each tier’s unit prices into the cost formula above to calculate cost per thousand requests.
    3. Quality check: compare output quality across tiers on a unified evaluation set to confirm that downgrading does not break business metrics.
    4. Canary: validate cost and quality with a small traffic share, then ramp up gradually while keeping a rollback switch.

    8. Common Pitfalls

    • Looking only at input price and ignoring the output multiplier.
    • Overlooking cache hit rate, so long prompts are billed as regular input every time.
    • Using the flagship model for templated tasks.
    • Lacking token-level monitoring, making it impossible to locate the source of cost anomalies.
    • Treating cost reduction as intelligence reduction without running a quality regression.

    9. Conclusion

    The value of an LLM API is not a static ranking. It is a function of “request profile × pricing structure × routing strategy.” By formalizing the cost model, structuring the cache, constraining output, and architecting routing, you can build a controllable and scalable cost system on top of general-purpose model services such as those offered by Baidu AI Cloud.