LLM API Cost Estimation and Optimization: A Practical Guide

    A practical guide to estimating large language model API costs beyond simple per-token pricing. It breaks down input, cached input, output, and cache storage charges, presents a unified cost model, explains time-based pricing, context caching, batch discounts, and discount exclusivity, and provides a reusable estimation script along with an optimization checklist.

    1. Why a Low Unit Price Does Not Mean a Low Bill

    Many teams compare a single price sheet when choosing a model, then find the actual bill several times higher than expected after launch. The reason is simple: LLM API billing is not based on a single “cost per thousand words” metric. It is the sum of several independent metering items. Ignoring any one of them makes the estimate inaccurate.

    The four common metering items are:

    • Input tokens (cache miss): charged at the full rate, often one of the main cost drivers;
    • Input tokens (cache hit): priced significantly below the full rate, commonly 10–20% of it;
    • Output tokens: generally priced higher than input, and often the largest expense for long-form generation;
    • Cache writes and storage: charged once per written token, or continuously by “million tokens · hour.”

    Beyond these four, two adjustment factors are easy to miss: time of day (peak/off-peak) and invocation mode (synchronous/batch). They are not separate charges but multipliers applied to the unit price.

    2. Abstracting Billing Items into a Unified Model

    Regardless of the cloud provider, the cost can be expressed as:

    1. Cost per request =
    2. uncached input tokens × full input price × time factor × invocation factor
    3. + cached input tokens × cache hit price × time factor × invocation factor
    4. + output tokens × output price × time factor × invocation factor
    5. + cache write tokens × write price
    6. + cache duration × storage unit price

    This formula has three practical implications:

    1. Cost is extremely sensitive to output length. The output price is often three to five times the input price, so long-form generation and code completion scenarios should reduce output first.
    2. Cache savings depend on the hit rate, not on how low the cache price is. Raising the hit rate from 30% to 70% often saves more than switching to a cheaper model.
    3. Time of day and invocation mode are multipliers. They can stack or be mutually exclusive, so the official billing rules must be confirmed item by item.

    3. Common Forms of the Four Billing Rules

    1. Time-Based Pricing

    Some platforms classify weekday daytime as peak and the remaining hours as off-peak, with off-peak prices often half of peak prices. The key detail is that the tier is determined by the request completion time, not the start time. A long request started at 8:58 and finished at 9:03 may be billed entirely at the peak rate. For offline jobs, this means scheduling must leave enough lead time.

    2. Context Caching

    Cache hits are cheap, but caching is not free: it is charged either per written token or continuously by storage duration. So caching has a break-even point—only when the same prefix is reused enough times do the input savings exceed the write and storage costs.

    1. def cache_is_worth(prefix_tokens, reuse_times, hit_price, full_price, write_price):
    2. save = prefix_tokens * reuse_times * (full_price - hit_price)
    3. cost = prefix_tokens * write_price
    4. return save > cost, save - cost

    A common practice is to keep stable prefixes—system prompts, tool definitions, long documents—at the very front and ensure they are byte-for-byte identical so the hit rate stays stable.

    3. Batch Discounts

    Batch processing typically offers a 50–60% discount, at the cost of latency rising from seconds to minutes or even hours. It suits data cleaning, offline summarization, and bulk labeling, but not online interaction.

    4. Discount Exclusivity

    This is the easiest pitfall: batch discounts and context caching discounts often cannot apply at the same time. Let the batch discount be b and the cache saving ratio be s:

    1. Batch only: cost = original price × b
    2. Cache only: cost = original price × (1 - s)
    3. Rule: use batch when b < 1 - s, otherwise use cache

    Calculate both numbers before running a batch job, then decide which path to take.

    4. A Reusable Cost Estimation Script

    1. def estimate(in_tok, out_tok, hit_tok, p_in, p_out, p_hit,
    2. peak=1.0, batch=1.0, write_tok=0, p_write=0.0):
    3. k = peak * batch
    4. return (in_tok * p_in + hit_tok * p_hit) * k + out_tok * p_out * k \
    5. + write_tok * p_write

    Plugging the parameters of different models and time tiers into the same function yields comparable side-by-side results. Note that all prices must be converted to the same unit (such as “per million tokens”) before comparison.

    5. Cost Optimization Checklist

    • Reduce output: cap the maximum generation length and use structured output to cut redundant wording;
    • Improve hit rate: stabilize prefixes, fix prompt order, and avoid inserting volatile content such as timestamps into the cached segment;
    • Choose the right tier: move offline jobs entirely to off-peak hours and leave a completion-time buffer;
    • Use batch processing: enable it only for tasks without real-time requirements, and compare pricing with the caching option first;
    • Tiered routing: send simple requests to lightweight models and complex requests to flagship models;
    • Observability: tag logs and monitoring alerts by business dimension to identify the callers that actually burn money.

    If you already use Baidu AI Cloud capabilities, you can combine its object storage for corpus retention, message queues for peak shaving, and container platform for an elastic inference front layer, turning “measurable” into “controllable.”