LLM Cost Optimization and Model Selection: A Practical Guide

    This guide explains how to control large language model (LLM) API costs without sacrificing output quality. It breaks the bill down into four tunable variables, introduces a four-dimension optimization approach covering routing, context reduction, caching, and output control, and shows how to build observability and run comparable model evaluations. You will learn how to reserve flagship models for requests that truly need them, cut input length, turn repeated calls into near-zero-cost cache hits, and keep spending aligned with business value.

    1. Reframing the Problem: From “Which Model Is Best” to “How to Use Models Well and Control Cost”

    In real engineering environments, choosing a model is rarely a single-objective question about quality alone. It is a multi-objective optimization problem under a cost constraint. If you abstract the publicly available call statistics, a stable structural pattern emerges: the most frequently called models are usually general-purpose tiers with fast responses and low unit cost, suited to high-concurrency preprocessing. The largest share of spending, however, typically goes to the most capable and most expensive flagship tier—a single flagship model can consume more than 30% of total spend, and the top two or three high-capability models together often account for over half of the bill.

    Two things follow from this. First, call volume and cost contribution are different curves: the former reflects where a model is used, the latter reflects which stage of the workflow it is used in. Second, cost overruns are usually not caused by unit price, but by placing high-priced models in pipelines that do not need high capability, and by leaving context and output length unconstrained.

    2. The Cost Model: Breaking the Bill into Tunable Variables

    The cost of a single call can be approximated as:

    1. cost per call ≈ input tokens × input price + output tokens × output price
    2. total cost ≈ Σ(requests × avg input length × input price
    3. + requests × avg output length × output price)

    Only four variables can be optimized: the number of requests, average input length, average output length, and the model tier matched to each request type. Any optimization technique must ultimately act on these four variables; otherwise it is just psychological comfort.

    Note that the output side is usually more expensive than the input side, and output length is directly driven by the length of the business copy, making it the most easily overlooked amplifier. In addition, retries, timeout resends, and failure fallbacks multiply the request count, which is a typical source of hidden cost.

    3. The Four-Dimension Optimization Approach

    3.1 Quality Tiering and Routing: Reserve Expensive Models for Requests That Need Them

    Classify business requests by difficulty. Simple classification, extraction, and formatting tasks that can be decided by rules go to a lightweight tier; requests that require multi-step reasoning, long-document understanding, or complex code generation go to the flagship tier. Routing decisions should rely on explainable rules or a lightweight classifier, avoiding the paradox of “calling an LLM first to decide whether an LLM should be called.”

    1. def route(req):
    2. if req.task_type in ("classify", "extract", "format"):
    3. return "model_light"
    4. if req.input_tokens > 8000 or req.need_reasoning:
    5. return "model_flagship"
    6. return "model_standard"

    In practice, set a budget cap and a circuit-breaker threshold for each tier so that traffic automatically degrades when limits are exceeded, preventing a single anomaly from causing a cost spike.

    3.2 Context Governance: Subtractive Engineering for Input Length

    Input length is the most controllable cost item. Common practices include: compressing retrieved passages in retrieval-augmented generation, keeping only highly relevant segments after deduplication and reranking; producing a structured summary of long documents before passing them in; trimming system prompts and merging duplicate constraints; and using rolling summaries for multi-turn conversations instead of concatenating the full history. In practice, compressing the input side by 30–50% usually has limited impact on quality but a direct impact on the bill.

    3.3 Caching and Reuse: Turn Repeated Requests into Zero Cost

    Caching has three layers: exact caching (reuse for identical requests), semantic caching (reuse after normalizing similar questions), and prefix caching (reuse computed results for stable system prompts and knowledge prefixes). When implementing caching, define a clear invalidation policy and version numbers to avoid returning stale results after a knowledge update.

    1. cache_key = hash(system_prompt_version + normalized_query + params)

    3.4 Output and Call Shape: Streaming, Batching, and Length Limits

    Set a hard cap on output length and apply structured constraints so the model does not “freestyle” and produce longer text. Use batch mode for latency-insensitive tasks in exchange for lower unit cost. Use streaming output for user-facing scenarios to improve perceived responsiveness, and to terminate early on errors, reducing billing for wasted output.

    4. Observability: No Measurement, No Optimization

    Instrument calls uniformly and collect at least: request count, input/output tokens, the model tier hit, cache hit rate, retry count, per-call and cumulative cost, and cost share by business line. With this data, you can pinpoint which pipeline the “cost champion” actually comes from instead of tuning parameters by intuition.

    1. Dashboard suggestions:
    2. - Cost breakdown: split by model tier / business line / API
    3. - Efficiency metrics: average tokens per request, cache hit rate, retry rate
    4. - Quality metrics: degradation rate, human review pass rate

    5. Model Selection: Comparable Testing with a Unified Standard

    Do not rely on a single leaderboard. Build a small evaluation set that reflects your real business distribution, fix parameters such as temperature, and record quality, latency, and unit cost for each model. Plot a quality–cost scatter chart and choose a combination on the Pareto frontier rather than a single optimum. For high-priced tiers, in particular, assess whether the marginal benefit covers the marginal cost.

    6. Implementation Notes from a Baidu AI Cloud Perspective

    When implementing the above on Baidu AI Cloud, you can reuse general cloud capabilities: object storage to hold evaluation sets and prompt versions, a message queue to smooth peaks and support asynchronous batch processing, a container platform to host routing and caching services, and logging plus monitoring and alerting to close the observability loop on tokens and cost. On the model service side, funnel access through a unified gateway to centralize tier routing, rate limiting and circuit breaking, and budget control, avoiding a cost black box created by each business line connecting directly.

    7. Common Anti-Patterns

    • Using the highest-capability tier across the entire pipeline in pursuit of “zero risk,” which unbalances the cost structure;
    • Cutting unit price without cutting length, so the bill still grows linearly;
    • Caching without version management, causing consistency incidents after knowledge updates;
    • Retry policies without backoff or a cap, doubling cost during outages;
    • No cost attribution by business line, making it impossible to identify what to optimize.

    8. Conclusion

    The essence of cost governance is treating model capability as an allocable resource: routing decides where it is used, context governance decides how much is used, caching decides whether repeated work is paid for, and observability decides whether optimization is sustainable. Following this path typically reduces the flagship tier’s share of spend to a reasonable range while keeping quality roughly flat, realigning overall investment with business returns.