LLM API Pricing and Cost Governance: A Practical Guide

    This guide explains how LLM API costs are actually formed. It covers token-based input and completion pricing, derived price multipliers, prompt caching economics, why aggregator price groups differ, cost estimation examples, and engineering practices for controlling call costs.

    1. Introduction: From “Which Model Is Strongest” to “How Much Does Each Call Cost”

    In many LLM integration workflows, teams still start from a price table. A developer opens a model detail page on an aggregation platform, sorts by price, and picks the cheapest available channel based on intuition.

    That approach is risky because “lowest unit price” is only a static label. Actual spending is shaped by three dynamic factors:

    • Workload structure: the ratio of input tokens to completion tokens, context length, and multi-turn depth.
    • Caching strategy: whether stable prefixes can be reused through prompt caching.
    • Channel attributes: rate limits, concurrency limits, and billing or settlement conditions behind each price group.

    Once these factors are combined, a “cheaper” channel can produce a higher real bill than a more expensive one. This article uses typical group prices for a flagship LLM on an aggregation platform as an example. The numbers are only used to illustrate the pricing structure; actual prices should always be checked against each platform’s real-time public pricing. The goal is to break down the billing mechanism, provide reusable cost estimation methods, and suggest practical engineering optimizations.

    2. The First Layer of Billing: Input and Completion

    Most modern LLM APIs use usage-based billing, with the unit of measurement being the token. The number of tokens produced for the same text can vary across tokenizers. This is especially noticeable with code, tables, and mixed-language content. Therefore, cost estimation should start from token measurement rather than character count or word count.

    2.1 Typical Price Structure and Derived Multipliers

    Billing item Price Group A Price Group B Price Group C Pricing notes
    Input $3.1060 $5.1770 $7.9200 Per 1M input tokens
    Completion $15.5290 $25.8830 $39.6000 Per 1M output tokens
    5-minute cache creation $3.8320 $6.4710 $9.9000 Write cache and keep it for 5 minutes
    1-hour cache creation $6.2120 $10.3530 Not listed Write cache and keep it for 1 hour
    Cache hit $0.0776 $0.1294 Not listed Input portion served from cache

    The full price for Group C was not collected, so only visible items are shown.

    Even this limited table contains useful information. Before doing detailed cost estimation, at least three derived indicators should be calculated:

    • Completion-to-input multiplier: 15.5290 / 3.1060 ≈ 5, 25.8830 / 5.1770 ≈ 5, and 39.6000 / 7.9200 = 5. In all three groups, completion pricing is roughly five times input pricing.
    • Cache-hit-to-input multiplier: 0.0776 / 3.1060 ≈ 0.025, meaning the cached portion of input is charged at roughly 2.5% of the normal input price.
    • 1-hour to 5-minute cache-creation multiplier: 6.2120 / 3.8320 ≈ 1.62, and 10.3530 / 6.4710 ≈ 1.60, or about 1.6 times.

    2.2 Implications for Cost Structure

    Because completion tokens are priced at roughly five times input tokens, long-output tasks can cost much more than expected. Asking the model to “write a bit more” or “rewrite the entire document” can be more expensive than adding a large knowledge base to the context. In billing terms, verbose generation is a cost amplifier.

    The cache-hit discount is very steep, at about 2.5% of the normal input price. At the same time, cache creation is only slightly more expensive than normal input: about 1.24 times for the 5-minute tier and about 2 times for the 1-hour tier. This indicates that platforms generally encourage frequent reuse of stable prefixes.

    The engineering implication is straightforward: any context that can be reused over a long period, such as system prompts, tool definitions, few-shot examples, or fixed reference documents, should be organized into a stable prefix and kept in cache whenever possible.

    2.3 Turning Tokens into an Observable Metric

    Before estimating cost, measure the real token distribution in production traffic.

    1. import json, collections
    2. def load_usage(path):
    3. with open(path, encoding="utf-8") as f:
    4. return [json.loads(line) for line in f if line.strip()]
    5. def token_stats(rows, field="usage"):
    6. """rows: request/response logs; calculate input/output and cache-hit ratios."""
    7. in_tok = out_tok = cache_read = 0
    8. for r in rows:
    9. u = r.get(field, {})
    10. in_tok += u.get("prompt_tokens", 0)
    11. out_tok += u.get("completion_tokens", 0)
    12. cache_read += u.get("prompt_tokens_details", {}).get("cached_tokens", 0)
    13. total_in = in_tok or 1
    14. return {
    15. "Input tokens": in_tok,
    16. "Output tokens": out_tok,
    17. "Output/input ratio": round(out_tok / total_in, 2),
    18. "Cache-hit share of input": round(cache_read / total_in, 3),
    19. }
    20. if __name__ == "__main__":
    21. print(json.dumps(token_stats(load_usage("requests.jsonl")), ensure_ascii=False, indent=2))

    3. The Second Layer of Billing: The Cost of Prompt Caching

    Prompt caching is currently one of the most effective general-purpose mechanisms for controlling long-context costs. Its billing can be abstracted into three parts:

    • a one-time write cost;
    • a retention period that depends on time;
    • a discounted read cost when the cache is hit.

    3.1 A Reusable Estimation Function

    1. # Prices are in USD per 1M tokens; token counts in usage are integers
    2. PRICE_TABLE = {
    3. "A": {"input": 3.1060, "output": 15.5290,
    4. "cache_write_5m": 3.8320, "cache_write_1h": 6.2120,
    5. "cache_hit": 0.0776},
    6. "B": {"input": 5.1770, "output": 25.8830,
    7. "cache_write_5m": 6.4710, "cache_write_1h": 10.3530,
    8. "cache_hit": 0.1294},
    9. }
    10. def estimate_cost(group: str, usage: dict) -> dict:
    11. p = PRICE_TABLE[group]
    12. plain_in = usage["input"] - usage.get("cache_read", 0) - usage.get("cache_write_5m", 0) - usage.get("cache_write_1h", 0)
    13. cost = (plain_in * p["input"]
    14. + usage.get("output", 0) * p["output"]
    15. + usage.get("cache_write_5m", 0) * p["cache_write_5m"]
    16. + usage.get("cache_write_1h", 0) * p["cache_write_1h"]
    17. + usage.get("cache_read", 0) * p["cache_hit"]) / 1_000_000
    18. return {
    19. "Total cost (USD)": round(cost, 6),
    20. "Cost per request (USD)": round(cost / max(1, usage["requests"]), 6),
    21. }

    3.2 Choosing Among Cache Write Tiers

    • No cache: there is no write cost, but every turn pays full price for the system prompt and history.
    • 5-minute cache: the write cost is about 1.24 times normal input. This is suitable for interactive sessions where multiple related requests arrive within a short time. If the stable prefix is not reused within five minutes, the write cost becomes sunk cost.
    • 1-hour cache: the write cost is about 2 times normal input, or about 1.6 times the 5-minute tier. This is suitable for scenarios such as customer support tickets or document Q&A, where the time between requests is uncertain but the same prefix is reused repeatedly.

    The decision rule is simple: a longer retention tier is worthwhile when the expected number of cache hits is high enough.

    In abstract terms, a higher cache tier makes sense only when:

    expected hits × savings per hit > additional write cost

    3.3 Organizing Prefixes for Better Cache Reuse

    Prompt caching matches prefixes. Therefore, the order of the prompt directly affects the cache-hit rate. The recommended structure is: stable content first, variable content last.

    1. def build_messages(system_prompt, tools, few_shots, retrieved, question):
    2. """Put stable content first to keep the cached prefix byte-for-byte identical."""
    3. return [
    4. {"role": "system", "content": system_prompt},
    5. *[{"role": "user", "content": s} for s in few_shots],
    6. {"role": "user", "content": f"Reference material:\n{retrieved}\n\nQuestion:{question}"},
    7. ]

    Three practical points matter:

    • Byte-for-byte consistency: do not insert timestamps, random request IDs, current dates, or other changing values into the prefix. Otherwise, the cache may be recreated on every request.
    • Fixed order: system prompt → tool definitions → few-shot examples → retrieved results → user question.
    • Check the threshold: caching usually triggers only when the request reaches the platform’s minimum cacheable length. Short requests generally do not need to be artificially padded.

    4. Why the Same Model Has Multiple Price Groups

    Aggregation platforms often split the same model into several “groups” or “channels,” and the price gap can exceed twofold. Using the example price table above, Group A is roughly 39% of Group C’s input price, or about 61% cheaper. Group B is roughly 65% of Group C’s input price, or about 35% cheaper.

    These price differences usually do not appear without reason. They are often related to the following factors:

    • Resource pool specifications and rate-limiting policies: lower-priced groups often come with stricter concurrency limits, requests-per-minute limits, and context-length limits. During peak hours, throttling becomes more likely, which means more retries and more queuing.
    • Settlement cycle and prepayment requirements: larger discounts may require longer settlement cycles or prepaid balances. This shifts cash-flow cost and reconciliation cost to the caller.
    • Service quality and availability: whether an availability target is committed, whether dedicated concurrency is provided, and whether fallback behavior is clearly defined all affect price.
    • Metering differences: whether cache hits are billed separately, or whether very long contexts are billed in segments, can make the effective unit price differ significantly across groups.

    The decision should therefore be treated as capacity planning with constraints, not simple price comparison. Filter options using request volume, peak concurrency, SLA requirements, and budget. Then run a small canary test against the same real traffic and compare the cost per successful request, including retries and failed requests, rather than choosing the lowest sticker price.

    5. Cost Estimation Example

    Assume a workload with 1,000,000 requests per month. Each request has an average input of 3,000 tokens, an output of 800 tokens, and a stable prefix of 1,800 tokens that can be cached.

    1. usage = {"requests": 1_000_000, "input": 3_000, "output": 800, "cache_read": 1_800}
    2. print("Group A:", estimate_cost("A", usage))
    3. print("Group B:", estimate_cost("B", usage))

    Under this simplified example, Group A costs about $1,828.80 per month, while Group B costs about $2,855.60 per month. The difference is about $1,026.80.

    If the 5-minute cache write tier is enabled for every request, the creation cost must also be added:

    1,800 × 3.8320 ÷ 1,000,000 × 1,000,000 ≈ $6,897.60

    In that case, caching becomes more expensive overall. This shows that “turning on cache” does not automatically mean “saving money.”

    Key conclusions:

    • Cache hits are worthwhile only when the stable prefix is actually reused repeatedly.
    • The cached portion of input is charged at about 2.5% of normal input price, making it one of the most effective cost-reduction levers.
    • When output accounts for a large share of cost, output optimization can produce proportional savings. In the example, the output/input token ratio is about 0.27, but output tokens are priced at roughly five times input tokens, so output can account for about 47% of total cost.

    6. Making the Bill Controllable: Five Engineering Practices

    1. Tiered routing
      Split tasks by difficulty. Send simple classification, extraction, and rewriting tasks to lower-cost groups or smaller models, and reserve higher-capability groups for complex reasoning. This can reduce both average unit price and peak load.

    2. Context slimming
      Rerank and deduplicate retrieved snippets, keeping only highly relevant passages. For long documents, use summaries rather than full-text concatenation. Trim tool definitions when possible.

    3. Cache-first design
      Keep system prompts, tool definitions, and few-shot examples in a stable long prefix. Put variable content after that prefix. For prefixes with high reuse, consider longer cache retention.

    4. Output constraints
      Use structured output and explicit length or format constraints to reduce redundant generation. Configure separate group and cache strategies for offline batch jobs and online interactive tasks.

    5. Observability and budget control
      Track token usage and cost by business line, feature, and user tier. Set monthly budgets and daily growth alerts. Track throttled and failed requests separately so that retries do not silently consume the budget.

    7. Price Freshness and Reconciliation

    Displayed prices on aggregation platforms can change at any time, and some details may only be visible after signing in. Therefore:

    • Before scaling up or changing architecture, recheck the current price and group description on the model detail page.
    • Maintain a price snapshot inside the system and record its version. The cost dashboard should be calculated from that snapshot.
    • Periodically reconcile the real bill against the snapshot. Alert when the deviation exceeds a defined threshold.

    8. Compliance and Risk Considerations

    When choosing a channel, price is not the only factor. Teams should also confirm:

    • whether the terms of service and data-processing agreements meet the requirements of the relevant industry;
    • whether request and response logs contain sensitive data, and whether retention periods comply with internal and regulatory requirements;
    • whether billing details can be exported by call dimension for auditing.

    If a low-price channel lacks these safeguards, hidden costs can be much higher than the apparent unit-price savings.

    9. Summary

    LLM API cost is determined by three things:

    • billing structure: input and completion tokens are typically priced at about a 5:1 ratio, while cache hits may cost only about 2.5% of normal input;
    • usage patterns: context length, output length, and prefix stability;
    • channel attributes: rate limits, settlement terms, and SLA guarantees.

    Engineering teams should first measure the real token distribution from production traffic, then estimate cost using price snapshots, and finally control spending through tiered routing, caching strategy, and budget alerts. The shift is from “choosing the cheapest channel” to “calculating the marginal cost of each call.” Once that shift happens, the bill stops being an opaque black box and becomes a governable engineering metric.