A Practical Guide to Optimizing LLM API Costs

    This guide explains why published per-token prices are unreliable for LLM cost decisions and how to build a reproducible measurement process instead. It covers normalizing pricing across channels with input/output weighting, currency and unit conversion, and strict model version alignment; a four-layer breakdown of cost structure including base token fees, prefix caching, batch discounts, and channel overhead; three counterintuitive conclusions about official versus third-party pricing, flagship model availability, and discount multipliers; and implementation practices such as a unified gateway abstraction, three-tier routing, prompt prefix layering, and budget guardrails with observability. A final checklist helps teams turn cost optimization into an engineering routine rather than a one-time price comparison.

    1. The Problem: Why a Price Table Is Not Enough for Decision-Making

    When teams first move LLM capabilities into production, the obstacle is usually cost rather than output quality. A common pattern: the same model at the same version can be listed at prices that differ by several multiples across supply channels. Even more counterintuitive, the most expensive channel is not necessarily the model developer’s official endpoint, and the cheapest is not necessarily a third-party reseller.

    The reason is not mysterious. Model delivery is typically split into layers: the model itself at the bottom, hosting and inference services in the middle, and aggregation gateways and cloud marketplaces on top. Each layer has its own pricing objective. Some amortize compute cost through scale, some charge a premium for differentiated services, and some trade low prices for call volume. When all these channels appear in a single comparison sheet without a common measurement basis, the results are almost guaranteed to be distorted.

    So the first step in cost governance is not finding the cheapest channel, but establishing a reproducible measurement method. The conclusion of this article is straightforward: fix the measurement basis, align versions, and account for caching and batch processing. Only then does the portion of the price spread that represents genuine optimization room become visible.

    2. Establishing a Common Measurement Basis

    2.1 Weight input and output instead of comparing unit prices alone

    LLM billing almost always prices input (prompt) and output (completion) separately, with output typically costing several times more per token than input. In coding assistants and agent workloads, repeated context injection drives the input share up, while code generation and reasoning keep the output share substantial. In practice, weighting at roughly 30% input and 70% output tracks the real bill more closely than comparing input or output prices in isolation.

    The calculation logic can be written as:

    1. def blended_price(p_in, p_out, in_ratio=0.3, out_ratio=0.7):
    2. """Blended price per million tokens based on input/output ratio"""
    3. return p_in * in_ratio + p_out * out_ratio
    4. # All values in CNY per million tokens
    5. print(blended_price(5.0, 20.0)) # 15.5

    2.2 Normalize currency and units first

    Channels may quote in different currencies and at different magnitudes (per thousand tokens versus per million tokens). Convert everything to a single currency per million tokens before comparing, which avoids order-of-magnitude errors. Fix the exchange rate used and state it in the report so the conclusions remain reproducible.

    2.3 Align model versions strictly

    The easiest trap is cross-generation comparison. Aggregation channels often list models late, and when the flagship version is missing they offer only the previous generation or a lightweight specialized variant. The correct response is to mark that the channel has no corresponding version, not to fill the cell with a lower-tier model’s price. Doing the latter makes the entire comparison meaningless.

    3. Breaking Down the Cost Structure in Four Layers

    To genuinely reduce cost, the bill has to be decomposed into attributable layers:

    • Base input and output fees: determined by the model and version, and the primary cost item.
    • Cache-related charges: when a repeated context prefix is a cache hit, the hit portion is usually billed at a significant discount while the remainder is billed at standard price. Long system prompts, fixed tool descriptions, and code repository indexes are all high-reuse prefixes.
    • Batch and asynchronous discounts: non-real-time work routed through an asynchronous batch channel usually gets a price reduction, at the cost of unpredictable latency.
    • Channel overhead: network egress, compliance auditing, quota guarantees, and technical support. These rarely show up in the unit price but genuinely affect total cost of ownership.

    One frequently overlooked fact: the channel with the lowest unit price may be compromising on rate limits, availability zone coverage, data residency, or SLA, which raises the hidden cost of retries and fallbacks. The evaluation model should include “retry rate multiplied by cost per call.”

    4. Rigorous Arguments for Three Counterintuitive Conclusions

    Conclusion 1: Official direct access is not necessarily the most expensive, and third parties are not necessarily the cheapest. When a channel pursues scale through low pricing, its resale price may be well below the official endpoint. Conversely, when a channel bundles hosting, auditing, and guarantees, it may cost several times the official price. The only valid basis for judgment is measured data at the same version and the same measurement basis.

    Conclusion 2: Availability of the flagship version is itself a constraint. If the primary channel has not listed the target version, the architecture must reserve a replaceable abstraction layer. Otherwise the system is forced down to a weaker version, which affects quality and retry rates.

    Conclusion 3: A discount multiple is not an absolute cost advantage. A channel priced at 30% of the official rate may still produce a higher absolute bill if its baseline version is a generation behind another channel’s current-generation model. The comparison has to return to the weighted absolute price.

    5. Implementation: From Price Comparison to Cost Guardrails

    5.1 Extract a unified gateway layer

    Do not hardcode a single endpoint in business code. Use an internal gateway to unify authentication, metering, routing, and fallback so channels stay pluggable:

    1. class ModelGateway:
    2. def __init__(self, providers):
    3. self.providers = providers # Channels ordered by priority
    4. def call(self, payload, max_tokens=2048):
    5. last_err = None
    6. for p in self.providers:
    7. try:
    8. return p.complete(payload, max_tokens=max_tokens)
    9. except Exception as e:
    10. last_err = e
    11. raise RuntimeError("all providers failed") from last_err

    5.2 Three-tier routing strategy

    • Tier 1: the primary channel, with the best cost-performance ratio and a version that is aligned.
    • Tier 2: official direct access, as a stability fallback.
    • Tier 3: lightweight or previous-generation models, handling only low-risk tasks that tolerate some quality loss, such as log summarization or format conversion.

    5.3 Prefix caching and prompt layering

    Split prompts into a stable prefix plus dynamic fragments. The stable prefix holds the role definition, tool descriptions, and output specifications; the dynamic fragment holds only the current turn’s context. On channels that support prefix caching, the repeated portion hits the discounted price, which can noticeably reduce long-session cost.

    5.4 Budget guardrails and observability

    Tag and meter usage by project, environment, and task type, set daily and monthly budget thresholds with automatic fallback rules, and monitor average token consumption per task type, cache hit rate, retry rate, and failure distribution. There is no optimization without metering, and billing anomalies usually show up on monitoring charts earlier than on invoices.

    6. A Selection Checklist for Periods of Rising Prices

    1. Fix the basis: record the weighting ratios, currency, units, and capture time in the report.
    2. Align versions: mark a missing version as missing; do not fill gaps or guess.
    3. Evaluate on two tracks: look at both the weighted unit price and end-to-end task cost, including retries.
    4. Preserve replaceability: gateway abstraction plus at least two usable channels.
    5. Review regularly: recheck prices and versions every two weeks to build a trend rather than a snapshot.

    7. Conclusion

    Price spread across channels is not accidental but an inevitable result of a layered delivery system. What developers actually need is not a leaderboard of who is cheapest, but a measurement and governance process that can be executed repeatedly: unify the basis, align versions, decompose the billing structure, compress the real bill with caching and routing, and keep things under control long term with monitoring and budget guardrails. Baidu AI Cloud provides full support in model services along with general-purpose observability and metering capabilities, on top of which teams can turn cost optimization into an engineering standard rather than a one-time price comparison exercise.