LLM API Pricing: How to Calculate the True Cost per Request for Your Workload

    Comparing LLM API prices across channels is harder than it looks, because listed prices are rarely on the same basis. This article explains how to build a unified cost model, adjust for quality using cost per successful task, account for hidden costs like reasoning tokens and retries, and set up a sustainable process for tracking prices and budgets—so you can choose an API channel based on real workload data instead of sticker prices.

    1. Why Listed Prices Can’t Be Compared Directly

    The price of the same model can vary widely across channels, but the listed numbers are often not comparable on the same terms. Common differences include:

    • Different billing units: Some channels charge per million tokens, others per thousand tokens, and some per request or per unit of time.
    • Separate input and output pricing: Output tokens are usually priced significantly higher than input tokens, so the input/output ratio directly changes the total cost.
    • Cache pricing: Repeated system prompts or long documents that hit the cache may be billed at a much lower rate.
    • Currency and exchange rates: For channels priced in a foreign currency, exchange rates and taxes affect the final bill.
    • Versions and regions: The same model name may cover different versions and context-length tiers, and regional endpoints can also affect pricing.

    Channel type alone doesn’t tell you whether the price is high or low. Official direct APIs, cloud-hosted platforms, aggregation routers, third-party inference services, and private deployments all have different cost structures. You need to verify each quote item by item rather than assuming “resellers are always more expensive” or “the official channel is always the cheapest.”

    2. Building a Unified Cost Model

    Before comparing prices, convert all channels to the same basis. The cost of a single request can be written as:

    Cost per request = (uncached input tokens × input price + cached tokens × cache price + output tokens × output price) ÷ 1,000,000

    The input/output ratio depends on your workload. Text generation and summarization tend to be output-heavy, while retrieval QA and code review tend to be input-heavy. The right approach is to measure the real token distribution from your own call logs, take averages or percentiles, and plug those into the formula. Don’t reuse someone else’s ratio.

    The following code wraps the price table and a single request into functions, making it easy to compare multiple channels in bulk.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class PriceTable:
    4. input_per_m: float # price per million uncached input tokens
    5. output_per_m: float # price per million output tokens
    6. cache_hit_per_m: float = 0.0 # price per million cached tokens
    7. def request_cost(p: PriceTable, input_tokens: int, output_tokens: int,
    8. cached_tokens: int = 0) -> float:
    9. """Cost of a single request. cached_tokens is part of input_tokens."""
    10. uncached = max(input_tokens - cached_tokens, 0)
    11. total = (uncached * p.input_per_m
    12. + cached_tokens * p.cache_hit_per_m
    13. + output_tokens * p.output_per_m)
    14. return total / 1_000_000

    Every number in your price table must carry its source and the time it was captured. Prices change with version updates and policy adjustments, and a price table without timestamps quickly loses its value.

    3. Quality Adjustment with Cost per Successful Task

    Comparing only per-request cost can lead you to a cheap but ineffective option. A better metric is cost per successful task—the average spend required to complete one valid task:

    Cost per success = average cost per request ÷ task pass rate

    The pass rate comes from your own evaluation set—for example, a set of samples representing real business tasks, judged correct or not by rules or human review.

    1. def cost_per_success(avg_cost: float, pass_rate: float) -> float:
    2. """pass_rate is in (0, 1]; 0 means the task cannot be completed."""
    3. if pass_rate <= 0:
    4. return float("inf")
    5. return avg_cost / pass_rate
    6. # Example: the prices and pass rates below are hypothetical
    7. # and do not represent any real pricing
    8. workload = dict(input_tokens=3000, output_tokens=1000)
    9. channel_a = PriceTable(input_per_m=2.0, output_per_m=8.0)
    10. channel_b = PriceTable(input_per_m=1.5, output_per_m=12.0)
    11. cost_a = request_cost(channel_a, **workload) # 0.014
    12. cost_b = request_cost(channel_b, **workload) # 0.0165
    13. print(cost_per_success(cost_a, 0.90)) # about 0.0156
    14. print(cost_per_success(cost_b, 0.75)) # 0.022

    In this example, channel B has a higher per-request price and a lower pass rate, so the cost per completed task ends up higher. You should evaluate both numbers together when selecting a channel.

    4. Hidden Costs That Are Easy to Miss

    Beyond the listed price, the following factors also change what you actually spend:

    • Output tokens consumed by reasoning: Some models emit long intermediate reasoning content, which is usually billed at the output rate. Always estimate based on the actual usage returned.
    • Retries and timeouts: Retries after network timeouts or format validation failures are billed again. Cost statistics should include retry counts.
    • Context-length tiers: Some billing rules raise the unit price once the context exceeds a threshold—verify this carefully for long-document workloads.
    • Cache hit rate: If fixed system prompts or knowledge-base snippets reliably hit the cache, costs can drop noticeably. Structure prompts so the invariant parts come first.
    • Batch and asynchronous APIs: For latency-insensitive offline tasks, batch processing is usually more cost-effective; check whether a discounted API is offered.
    • Quotas and queuing: Queuing caused by concurrency limits extends elapsed time and indirectly adds labor and waiting costs.
    • Compliance and data residency: Whether data must stay within a jurisdiction or meet audit requirements may determine which channels are even eligible—filter on this before comparing costs.

    5. Evaluation Dimensions Beyond Price

    Model selection shouldn’t be driven by price alone. Build a scorecard covering at least these dimensions:

    1. Task quality: Pass rate on your own evaluation set, distinguishing simple from complex tasks.
    2. Latency and stability: Time to first token, total latency, error rate, and historical availability.
    3. Feature support: Function calling, structured output, streaming, multimodal input—whatever your business needs.
    4. Context capability: Effective context length and whether quality stays stable over long inputs.
    5. Portability: Whether the API is compatible with mainstream calling conventions, and how much work switching models or channels would take.
    6. Compliance and terms of service: Data usage scope, retention period, SLA, and invoicing capability.

    Combining these dimensions with cost per successful task gives you a judgment that reflects real business conditions.

    6. A Practical Implementation Process

    A sustainable cost-accounting workflow typically includes the following steps:

    1. Collect usage: Log input, output, cache hits, and retries for every request.
    2. Analyze the distribution: Break down token distribution by business line and identify common traits of high-cost requests.
    3. Maintain price tables: Keep a separate, timestamped price record with its source for each channel, and set a review cadence—for example, monthly.
    4. Validate with a small traffic slice: Run A/B tests on a fraction of real traffic and verify alternatives with your evaluation metrics.
    5. Set budget alerts: Configure daily or per-project thresholds and get notified when consumption looks abnormal.

    If your team uses the LLM services provided by Baidu AI Cloud, you can check the current unit prices and billing units in its official billing documentation, then combine them with the platform’s usage monitoring and budget alert features to build a cost dashboard. Refer to the official documentation for specific configuration options and available features.

    7. Common Pitfalls

    • Pitfall 1: Comparing only input prices. Output prices are usually higher, and in output-heavy workloads they dominate the total cost.
    • Pitfall 2: Comparing different versions directly. A lower price on an older version doesn’t mean it can handle the same task. Compare the same version or models of similar capability.
    • Pitfall 3: Assuming a one-time price check stays valid. Prices and billing rules change and need periodic review.
    • Pitfall 4: Assuming channel type determines price. The same model’s price can differ several-fold across channels, in either direction—verify each one individually.

    Checklist

    • Have you measured your real input, output, and cache-hit ratios?
    • Does your price table unify billing units, currency, and versions, with capture times recorded?
    • Have you included reasoning tokens, retries, and context-length tiers?
    • Have you computed pass rate and cost per successful task on your own evaluation set?
    • Have you evaluated latency, feature support, and compliance requirements?
    • Have you set a price review cycle and budget alerts?