LLM API Cost Evaluation and Selection: A Practical Guide

    This guide explains why your LLM bill can rise even after vendors cut per-token prices, and how to fix it. It breaks total cost into controllable variables, then walks through practical optimizations: two-tier caching with tenant isolation, three-part context engineering, asynchronous batching, cost observability, scenario-based model evaluation, and multi-model routing. The goal is to optimize cost per unit of business output instead of comparing price lists.

    1. Why the Bill Goes Up When Unit Prices Go Down

    When teams evaluate whether a new-generation LLM is “expensive,” many only look at the price per million tokens and overlook the full cost structure behind a real business call. A common misjudgment is this: a vendor does lower the input-side unit price when releasing a new version, yet the customer’s monthly spending goes up instead. There are usually three reasons.

    First, stronger capabilities drive token consumption up. New models often support longer context windows, stronger multimodal understanding, and more complex reasoning chains, so both input and output lengths per request increase. Second, call volume grows naturally as the business expands, and the savings from a lower unit price are offset by scale. Third, the engineering side lacks caching, batching, and traffic tiering, which leads to a large amount of redundant computation.

    So whether a model is “cost-effective” cannot be judged by unit price alone. What matters is the cost per unit of business output, such as “cost per thousand effective Q&A turns” or “cost per completed ticket.”

    2. Cost Model: Breaking the Bill into Optimizable Variables

    Teams should first build a simplified but quantifiable cost formula:

    1. Monthly total cost ≈ Σ(input tokens × input price + output tokens × output price)
    2. + retries and failed-request overhead
    3. + surrounding computation such as retrieval and embedding
    4. + storage, logging, and monitoring overhead

    There are really only four controllable variables: input length, output length, number of requests, and wasted overhead. The core of engineering optimization is to turn the uncontrollable “unit price” problem into a controllable “structure” problem.

    • Input length: compress it through prompt trimming, context pruning, and reranking of retrieved snippets.
    • Output length: enforce structured output and avoid redundant free-form generation.
    • Number of requests: cut duplicate calls with caching and deduplication.
    • Wasted overhead: reduce failed retries with timeouts, rate limiting, and fallback strategies.

    3. Caching and Deduplication: The Highest-Value First Layer

    In most business scenarios, user questions contain a large amount of semantic duplication. Adding tiered caching can significantly reduce input-side costs.

    1. # Example: a two-tier structure with semantic caching + exact caching
    2. def query_with_cache(prompt: str):
    3. exact = exact_cache.get(prompt) # Tier 1: exact string match
    4. if exact:
    5. return exact
    6. key = embed(prompt) # Tier 2: vector similarity match
    7. hit = vector_cache.search(key, threshold=0.95)
    8. if hit:
    9. return hit.answer
    10. answer = call_model(prompt)
    11. exact_cache.set(prompt, answer, ttl=3600)
    12. vector_cache.add(key, answer)
    13. return answer

    Note that caches must carry a tenant isolation identifier and an expiration time. Otherwise, results from different tenants or different permission scopes can get mixed together, creating a data access-control risk.

    4. Context Engineering: A Long Window Does Not Mean Stuffing Everything In

    Long-context capability is a double-edged sword. Stuffing in an entire document or a full conversation history not only drives up input costs but also introduces stability problems where “information in the middle gets ignored.” The recommended approach is a three-part structure:

    1. Stable prefix: system instructions, output format constraints, and a few examples. This part is suitable for long-term reuse and should hit the cache first.
    2. Dynamic retrieved snippets: keep only the passages highly relevant to the current question, and control the count with reranking.
    3. Conversation summary: compress early long conversations into a structured summary instead of the raw full text.
    1. [System constraints + output schema] ← stable, cacheable
    2. [Retrieved Top-K snippets] ← dynamic, needs reranking
    3. [History summary] ← compressed, length-controlled
    4. [Current question]

    5. Batching and Async: Smoothing Out Peak Costs

    For scenarios like offline analysis, content moderation, and batch summarization, real-time requirements are not high, so an asynchronous queue plus batching works well. Write requests into a message queue and have consumers aggregate them by batch. This improves throughput and makes it easier to use the vendor’s low-priority or batch-pricing channels (refer to the documentation of the chosen cloud service for specific rules).

    1. Business request → message queue → batch aggregation (split by token budget) → model call → write results to object storage → callback notification

    Combined with elastic scaling on a container platform, you can reclaim compute during business troughs and avoid paying for peak capacity all the time.

    6. Observability: No Measurement, No Optimization

    The prerequisite for cost governance is visibility. At a minimum, collect the following dimensions and connect them to logging services and a monitoring and alerting system:

    • Input/output token counts, latency, and status codes for each call;
    • Cost attribution by business line, tenant, and API;
    • Cache hit rate, retry rate, and truncation rate;
    • Time trends and abnormal fluctuations in cost per unit of business output.

    When the “cost per ticket” of a certain API suddenly rises, it is usually not the unit price that changed, but the prompt being modified, retrieved snippets getting longer, or output format constraints failing.

    7. Selection Framework: From Benchmarks to Scenario-Based Evaluation

    Back to the original question: whether a new-generation model delivers value depends on whether it is better in your scenario. Build an internal evaluation set containing real business samples, edge samples, and adversarial samples, and score across four dimensions: task accuracy, format compliance rate, average token consumption, and end-to-end latency. Converting these four into “cost per unit of output” before making a decision is more convincing than comparing leaderboards.

    At the same time, keep multi-model routing in place: simple requests go to a lightweight model, and complex requests escalate to a large-parameter model. This compresses overall spending without sacrificing experience.

    1. def route(prompt, context_len):
    2. if context_len < 2000 and is_simple(prompt):
    3. return light_model
    4. return strong_model

    8. Implementation Checklist

    1. Instrument first, then optimize anything, to ensure costs are attributable.
    2. Build a two-tier exact + semantic cache with strict tenant isolation.
    3. Restructure prompts so the stable prefix hits the cache first.
    4. Make offline tasks fully asynchronous and batched.
    5. Build a scenario-based evaluation set and replace unit-price comparisons with cost per unit of output.
    6. Introduce multi-model routing and fallback strategies to control long-tail spending.
    7. Connect logging, monitoring, and alerting to the general capabilities of Baidu AI Cloud to form a closed-loop governance process.

    Overall, the model unit price is only one factor in the bill. Only by designing context length, call structure, caching strategy, and evaluation methods together can you keep costs under control while capabilities upgrade. This is the core competitiveness of LLM engineering at the current stage.