LLM API Cost Analysis and Model Selection: A Practical Guide

    Learn how to compare large language model providers using workload-weighted pricing, account for caching and retries, and measure cost per successful task. This guide covers channel-level trade-offs, evaluation practices, and an implementation checklist for building a repeatable cost optimization process.

    1. Start with the Right Conclusion: Unit Prices Alone Are Not Enough

    When choosing a model, teams often begin with a table comparing input and output prices per million tokens, then select the lowest figure. That approach may have worked reasonably well a few years ago, but it can lead to systematically poor decisions today.

    There are three main reasons:

    1. Input and output prices can differ substantially. Output tokens often cost several times as much as input tokens, and real workloads have a relatively consistent input-to-output mix. Comparing input prices alone means basing the decision on the smaller part of the workload.
    2. The same model may differ across delivery channels. Direct access from a provider, a cloud-hosted service, an aggregation gateway, and a private deployment may offer different prices, versions, and rate limits. An intermediary can even cost more than the official channel. A channel is not simply a reseller charging a markup; it may also provide availability, compliance support, and reduced operational overhead.
    3. Engineering practices can affect the bill more than channel price differences do. Cache hits, batching, context trimming, and retries can all have a significant impact on total cost.

    A sound comparison therefore starts by defining the measurement basis, then calculating workload-weighted costs, and finally accounting for non-price factors in a decision matrix.

    2. Build a Reusable Weighted-Cost Model

    2.1 Define the measurement basis

    For AI coding workloads such as code generation, tool use, and iterative rewriting, input tokens often account for roughly 30% of usage and output tokens for around 70%. Long contexts may be read repeatedly, but the amount of content generated can still make up a larger share of the workload.

    This gives us the following weighted unit price:

    1. weighted_price = 0.3 * input_price + 0.7 * output_price

    For prices quoted in different currencies, convert them all to a single local currency using a fixed exchange rate before comparing channels. State the exchange rate in the report so that others can reproduce the calculation.

    2.2 Reference implementation

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Channel:
    4. name: str
    5. input_price: float # Local currency per million tokens
    6. output_price: float
    7. cache_price: float | None = None
    8. version_available: bool = True
    9. def weighted_unit_cost(ch: Channel, in_ratio=0.3, cache_hit=0.0):
    10. """Return weighted cost per million tokens, or None if the version is unavailable."""
    11. if not ch.version_available:
    12. return None
    13. out_ratio = 1 - in_ratio
    14. # Cached input tokens are charged at the cache price.
    15. effective_in = ch.input_price * (1 - cache_hit) + \
    16. (ch.cache_price or ch.input_price) * cache_hit
    17. return in_ratio * effective_in + out_ratio * ch.output_price
    18. def cost_per_successful_task(ch, tokens_in, tokens_out,
    19. success_rate=1.0, retries=0, cache_hit=0.0):
    20. unit = weighted_unit_cost(ch, cache_hit=cache_hit)
    21. if unit is None:
    22. return None
    23. per_attempt = (tokens_in * ch.input_price * (1 - cache_hit)
    24. + tokens_in * (ch.cache_price or ch.input_price) * cache_hit
    25. + tokens_out * ch.output_price) / 1e6
    26. attempts = (1 + retries) / max(success_rate, 1e-6)
    27. return per_attempt * attempts

    Two details matter. First, mark an unavailable model version as not comparable, rather than assigning it a cost of zero or silently omitting it. Otherwise, aggregate averages can be artificially lowered. Second, use successful tasks, not API calls, as the cost denominator. This is the key metric discussed below.

    3. Account for Hidden Costs Across Delivery Channels

    Compare four broad channel types: direct access from the provider, cloud-hosted services, API aggregation gateways, and self-hosted or private deployments. Evaluate each against the following criteria:

    • Version coverage: New flagship models may launch first through the provider’s direct channel. Aggregators may offer an older generation, a lightweight version, or a specialized variant. Price comparisons between different model generations are not meaningful.
    • Pricing structure: Check for tiered pricing, cache pricing, batch discounts, and combinations of subscription and pay-as-you-go plans. If cache pricing is unavailable, use the standard input price for a conservative estimate.
    • Availability and rate limits: Review request limits, concurrency caps, burst quotas, and the consistency of error-code semantics. Rate limiting and queuing can translate directly into higher business latency.
    • Data handling and compliance: Consider whether data may be used for training, log retention periods, deployment regions, and audit capabilities. In finance, healthcare, and government, these factors may outweigh price.
    • Observability: Check whether the service provides token-level usage details and billing that can be grouped by call chain. Without granular measurement, cost optimization is difficult.
    • Migration costs: Determine whether the API follows a commonly supported protocol and whether switching channels requires changes to application code. Better protocol compatibility can also strengthen your negotiating position.

    Cloud providers such as Baidu AI Cloud may offer more complete support for managed operations, detailed usage measurement, compliance, and regional infrastructure. They may be candidates for workloads with strict reliability or audit requirements. Check the provider’s official documentation for current pricing and quotas; this guide does not cite specific figures.

    4. Two Underestimated Levers: Caching and Context Management

    Cache hits are one of the most direct ways to reduce cost. Stable prefixes such as system prompts, tool definitions, and long documents may be cacheable at a lower price. To improve the chances of a hit, keep request prefixes consistent and move changing content—such as timestamps, random IDs, and user input—to the end.

    1. [Stable prefix: system instructions + tool schema + project conventions] <- cacheable
    2. [Partially stable: retrieved code snippets] <- moderate hit rate
    3. [Variable: current user input] <- not cached

    Context management affects the cost denominator. Trimming conversation history, compressing it into summaries, or retrieving relevant information instead of injecting everything can reduce input tokens without lowering task success rates.

    However, excessive trimming may reduce success rates and increase cost per successful task. Validate changes with an A/B test on the same task set rather than looking only at the bill for individual calls.

    5. The Core Metric: Cost per Successful Task

    Use a fixed evaluation set of 50–200 real tasks that covers both typical and edge cases. Then calculate:

    1. CPST = (total token cost) / (number of tasks that pass acceptance)

    Track three supporting metrics as well: average retries, P95 latency, and the rate of human intervention.

    Ranking channels by this metric can produce results that differ from a unit-price comparison. A channel that costs slightly more per token may have higher success rates and fewer retries, resulting in a lower cost per successful task. This is why the cheapest entry in a price table is rarely the final answer.

    6. Implementation Checklist

    1. Define the workload’s input-to-output token ratio, make it a configuration value, and use the same measurement basis across the team.
    2. Build a channel comparison matrix. Leave unavailable or incomparable versions blank and state why.
    3. Use a fixed evaluation set to measure success rates and retries, then calculate CPST instead of comparing unit prices alone.
    4. Implement prefix caching and context trimming before considering a channel switch.
    5. Add a protocol adapter layer so channels can be switched without tightly coupling the application to one provider. This preserves flexibility and negotiating leverage.
    6. Tag bills by business line, use case, and call chain, then review changes in the measurement basis each month.

    Cost optimization is not a one-time price comparison. It is a continuous loop of measurement definitions, usage tracking, evaluation, and workload management. Once the measurement basis is consistent, price changes become parameter updates rather than decision-making crises.