Optimizing LLM Inference Costs: A Multi-Provider Routing Approach

    This article reframes LLM cost optimization from picking the cheapest model to designing a multi-provider, multi-model, and observable calling system. It explains the four structural sources of price differences across channels, how to build a reproducible cost calculation baseline, and how tiered routing with fallback reduces spend. It also covers three underrated levers—caching, batch processing, and context governance—plus how to make cost observable and a checklist for model selection and governance.

    1. Reframing the Problem: From “Which Model” to “How to Organize Calls”

    When teams first integrate an LLM, the instinct is to compare the per-token prices of each vendor’s flagship model horizontally and wire in the cheapest one. Once real traffic starts flowing, the bill often deviates sharply from expectations. There are usually three reasons. First, the listed price for the same model varies noticeably across supply channels: official direct access, cloud-hosted offerings, third-party aggregation platforms, and enterprise procurement discounts can all land in completely different ranges. Second, billing conventions differ: input and output prices are often asymmetric, and cache hits, batch processing, and long-context tiers all change the effective average price. Third, call structure differs: agent and code workloads have a high output ratio, which naturally amplifies the impact of the output price.

    A more rigorous approach is therefore to redefine the problem: not to pick a single “cheapest LLM,” but to design a “multi-channel + multi-model + observable” calling system that routes each request to the cost-optimal path as long as capability requirements are met.

    2. Where the Price Gaps Come From: Four Structural Causes

    First, channel positioning differences. Official direct access usually anchors to public pricing and serves as the baseline of the price system. Cloud-hosted channels fold models into a unified package of resource bundles, vouchers, and billing, so prices float with the packaging. Aggregation platforms gain discount room through bulk procurement and traffic scheduling. Enterprise procurement often trades committed usage for tiered pricing. Because channels differ, prices naturally differ—the expensive one is not necessarily the official channel, and the cheap one is not necessarily a third party.

    Second, uneven version availability. Newly released flagship versions often appear first on the official channel and a few others, while other channels may only offer the previous generation, a lightweight version, or a domain-specialized variant. If you force different versions’ prices into the same comparison table, the conclusion becomes distorted. The proper practice is to explicitly mark “no corresponding version on this channel” rather than filling the gap with an approximate model.

    Third, billing dimension differences. Input and output are usually priced separately, with output being more expensive; whether the system prompt is cached, whether batch discounts are supported, and whether context length is tiered all significantly change the average price.

    Fourth, exchange rates and settlement methods. Cross-currency comparison requires a unified conversion baseline, with the conversion ratio and point in time noted; otherwise cross-channel comparison is meaningless.

    3. Building a Reproducible Measurement Baseline

    A price comparison is only worth something to engineering if others can reproduce it. It is recommended to fix three things: capture time, conversion baseline, and weighting ratios.

    1. Effective unit price = input price × input share + output price × output share
    2. Conversion rule: convert to a single currency at a fixed exchange rate, and note the capture date
    3. Weighting basis: agent/code scenarios use input 30% / output 70%; customer-service summarization uses input 70% / output 30%

    The same price table can rank differently under a different set of weights. Writing the weights into the documentation makes the comparison discussable and regression-testable. In addition, null semantics such as “not listed / no public price” should be preserved to avoid contaminating conclusions with estimated values.

    4. Tiered Routing: The Core Lever for Cutting Costs

    No single model can be both the cheapest and the best. A workable approach is to tier by task difficulty while keeping a fallback.

    1. # Illustrative: a vendor-agnostic routing skeleton
    2. def route(task):
    3. if task.kind in ("classify", "extract", "format"):
    4. return Tier.LITE # lightweight model, low-price channel
    5. if task.kind in ("code", "agent"):
    6. return Tier.FLAGSHIP # flagship model, stable channel
    7. return Tier.FALLBACK # fallback: switch after main channel timeout/rate limit
    8. def with_fallback(call, tiers):
    9. for t in tiers:
    10. try:
    11. return call(t)
    12. except (TimeoutError, RateLimitError):
    13. continue
    14. raise RuntimeError("all tiers failed")

    Recommended routing keys include: task type, context length, whether structured output is required, latency budget, and historical failure rate. Latency-sensitive online paths should prioritize low-latency channels, while offline batch processing should prioritize low-price channels. The same model can therefore present a different “cost-performance” profile on different paths.

    5. Three Underrated Levers: Caching, Batching, and Context Governance

    Caching: place the system prompt, tool descriptions, and long-document prefixes in stable positions so prefix caching can hit; the cached portion is usually billed at a lower price, with the biggest gains in long-context scenarios.

    Batching: switch offline tasks to an asynchronous batch API. Most platforms offer a discount for batch processing, at the cost of uncontrollable latency, making it suitable for log analysis, bulk rewriting, and offline evaluation.

    Context governance: deduplicate and rerank retrieved snippets, keeping only necessary evidence; summarize and compress conversation history; trim fields from tool return results. Reducing input tokens saves money linearly, with no model-side changes required.

    1. Before trimming: system 1.8k + history 6.4k + retrieved 9.1k = 17.3k tokens
    2. After trimming: system 0.9k + summary 1.2k + top-k 3.0k = 5.1k tokens

    6. Making Cost an Observable Metric

    Without measurement there is no optimization. It is recommended to instrument uniformly at the gateway layer, recording at least: channel, model version, input/output tokens, cache hit volume, retry count, failure reason, end-to-end latency, and cost per task.

    1. cost_per_task = Σ(channel unit price × tokens) / number of successful tasks
    2. Key dashboards: effective unit cost, cache hit rate, fallback trigger rate, cross-channel failure rate

    Here “effective unit cost” should be divided by the number of tasks that succeeded and passed validation, not the number of requests; otherwise retries and fallbacks will steer optimization in the wrong direction. After setting budget thresholds and alerts, the system can automatically switch to a low-price channel or throttle and degrade when costs spike.

    7. Selection and Governance Checklist

    First, put compliance and data boundaries first: clarify which data may leave the internal network and which must stay in a private environment. Second, abstract a unified gateway to mask channel differences and avoid binding business code to a single vendor’s API. Third, keep at least two available channels and run regular health checks. Fourth, periodically review price and version information, noting the capture time. Fifth, fix the evaluation set; any routing strategy change must run a regression to prevent cost cuts from causing quality regressions. Sixth, declare conflicts of interest: if the team uses a particular channel in-house, disclose it proactively.

    8. Conclusion

    LLM cost-performance is not a question a static price table can answer; it is a result jointly determined by channel structure, billing conventions, and calling architecture. Solidify the comparison baseline, tier the routing, make caching and context governance solid, and pair them with an observation system centered on “effective unit cost”—then cost turns from an uncontrollable bill into a sustainably optimizable engineering metric. If the entire pipeline is deployed on Baidu AI Cloud, it can leverage general capabilities such as the container platform, message queue, logging service, and monitoring and alerting to host the gateway and observation system, while specific pricing and version information should still be based on the real-time data on each platform’s public pricing page.