LLM API Pricing Explained: Cost Modeling and Optimization Best Practices

    LLM API costs are primarily driven by input, output, and cache-related token usage. This article explains the main billing components, why output tokens often cost more, how to build a practical cost estimation model, and how prompt caching, model routing, context compression, result caching, retries, monitoring, and budget controls can reduce spending without compromising application quality.

    1. Background: Token Billing Is Now a Core LLM Cost Driver

    LLM API usage is typically billed by token. A token is the basic unit used by a model to process text, and the same content can consume different numbers of tokens depending on whether it is written in Chinese, English, or code. Most providers publish prices per million tokens and bill input and output separately.

    Model prices may change as newer generations are released, and different models from the same provider may have different rates. For application teams, price changes are only part of the picture. The more important questions are:

    • How many tokens does each request consume?
    • Which parts of the request are billable?
    • Which parts can be reduced through engineering?

    This article explains the billing structure and provides practical methods for cost estimation, optimization, monitoring, and budget control.

    2. Breaking Down the Billing Components

    2.1 Input Tokens

    Input tokens include the system prompt, conversation history, retrieved document segments, and the user’s current question. The longer the context, the higher the input cost.

    In many applications, cost growth does not come primarily from model output. It comes from continuously expanding conversation history and redundant retrieval results.

    2.2 Output Tokens

    Output tokens include everything generated by the model, such as prose, code, and structured fields. Most providers charge a higher rate for output tokens than for input tokens.

    Some services support prompt caching. Repeated prefix content may be billed separately as cache reads and cache writes. Support and pricing rules vary by provider, so the official documentation should be used as the source of truth.

    2.4 Other Billable Items

    Tool calls, image or audio input, and tokens associated with reasoning may follow different billing rules. They should not be calculated using the same formula by default. Before enabling a new capability, confirm how the provider measures and charges for it.

    When estimating cost, distinguish between non-cached input tokens and cache-read tokens. Mixing them can result in duplicate counting or missed charges. Providers may also use different methods to count input tokens. During initial integration, validate the calculation against a small number of real requests and the corresponding bill.

    3. Why Output Tokens Are Usually More Expensive

    Input can generally be processed in parallel as a whole. Output, however, is generated one token at a time. Each newly generated token depends on the content generated before it, which makes generation more time-consuming in terms of inference resources. This is one common reason providers price output tokens higher, although it is not the only factor.

    For application teams, this means output length is an important cost-control lever. Replacing lengthy natural-language responses with fixed-field structured output can often reduce both API costs and post-processing effort.

    4. Building a Cost Estimation Model

    The following Python code provides a general-purpose cost calculation function. The prices are placeholders for demonstration only. In production, retrieve current prices from the provider’s pricing documentation and manage them through configuration rather than hard-coding them in application logic.

    1. from dataclasses import dataclass
    2. @dataclass(frozen=True)
    3. class Price:
    4. input_per_m: float # Price per million non-cached input tokens
    5. output_per_m: float # Price per million output tokens
    6. cache_read_per_m: float # Price per million cache-read tokens
    7. cache_write_per_m: float # Price per million cache-write tokens
    8. # Demonstration values only. Replace them with the provider's actual prices.
    9. PRICE_TABLE = {
    10. "model-large": Price(10.0, 50.0, 1.0, 12.5),
    11. "model-small": Price(1.0, 5.0, 0.1, 1.25),
    12. }
    13. def estimate_cost(
    14. model: str,
    15. input_tokens: int, # Number of non-cached input tokens
    16. output_tokens: int,
    17. cache_read_tokens: int = 0,
    18. cache_write_tokens: int = 0,
    19. ) -> float:
    20. """Return the estimated cost of one request in the price-table currency."""
    21. p = PRICE_TABLE[model]
    22. cost = (
    23. input_tokens * p.input_per_m
    24. + output_tokens * p.output_per_m
    25. + cache_read_tokens * p.cache_read_per_m
    26. + cache_write_tokens * p.cache_write_per_m
    27. )
    28. return cost / 1_000_000
    29. if __name__ == "__main__":
    30. c = estimate_cost(
    31. "model-large",
    32. input_tokens=3000,
    33. output_tokens=800,
    34. cache_read_tokens=12000,
    35. )
    36. print(f"Estimated cost per request: {c:.6f}")

    This function has two important design characteristics.

    First, the input token parameter is explicitly named input_tokens and documented as non-cached input. This helps prevent it from being counted again as cache-read usage.

    Second, all prices are normalized to a per-million-token basis. This makes the result easier to reconcile with provider invoices.

    5. Prompt Structure and Cache Hit Rates

    When a provider supports prefix caching, prompt organization directly affects cost. Caching usually requires the prefix to match exactly. Stable content should therefore appear first, while frequently changing content should be placed at the end.

    1. STATIC_SYSTEM_PROMPT = """You are an enterprise knowledge assistant.
    2. Answer based on the reference material. If the material is insufficient, say so clearly.
    3. Return JSON with the fields answer and sources."""
    4. def build_messages(retrieved_docs: list[str], question: str) -> list[dict]:
    5. context = "\n\n".join(retrieved_docs)
    6. return [
    7. # Stable prefix: keep the system prompt byte-for-byte consistent for caching
    8. {"role": "system", "content": STATIC_SYSTEM_PROMPT},
    9. # Dynamic content: place documents and the question at the end
    10. {"role": "user", "content": f"Reference material:\n{context}\n\nQuestion: {question}"},
    11. ]

    Three practical considerations are especially important:

    1. Do not place timestamps, request IDs, or other per-request values in the prefix. They can make cache hits nearly impossible.
    2. If the system prompt needs to vary by user, move the variable portion into a later message.
    3. Monitor the cache hit rate continuously. A sudden decline often indicates that the prefix was changed unintentionally.

    6. Engineering Techniques for Reducing Costs

    6.1 Route Tasks by Complexity

    Tasks such as classification, extraction, rewriting, and format conversion often require less model capability and can be handled by a smaller model. More capable models can be reserved for multi-step reasoning or high-accuracy decisions.

    Routing rules should be based on offline evaluations rather than intuition alone.

    6.2 Limit Output Length

    Set a reasonable maximum output token limit for each request type and require structured output where appropriate. Fixed-field JSON is often shorter than free-form text and is easier for programs to process.

    Prompts should also explicitly discourage unnecessary greetings, repeated questions, and other redundant content.

    6.3 Compress Context

    For multi-turn conversations, use rolling summaries. Keep the most recent turns in their original form and compress older content into a summary.

    In retrieval-augmented generation (RAG) workflows, control both the number and length of retrieved segments. Remove duplicate or highly similar passages before sending them to the model.

    6.4 Cache Results

    For exactly identical requests, the application can return a cached result without making another model call. Semantic caching can provide greater savings, but it requires a similarity threshold.

    If the threshold is too low, unrelated requests may incorrectly reuse the same result. Determine the threshold through sampling and evaluation.

    6.5 Batch and Process Asynchronously

    For non-real-time workloads such as offline labeling and bulk summarization, combine work into larger jobs or use a batch interface if the provider offers one. This can reduce request overhead and retry costs.

    6.6 Retry Carefully

    Distinguish retryable errors, such as rate limits and temporary timeouts, from non-retryable errors, such as invalid parameters and policy violations.

    Retries should use exponential backoff and a maximum retry count. Otherwise, failed requests may be charged repeatedly without improving the outcome.

    7. Usage Monitoring and Budget Protection

    Cost governance requires observability. At a minimum, record the following fields for every request:

    • Model name
    • Business scenario
    • Tenant or user identifier
    • Input token count
    • Output token count
    • Cache-read and cache-write token counts
    • Request latency
    • Estimated cost

    Aggregate these metrics by scenario and tenant, and configure alerts for period-over-period increases.

    The following example implements a simple daily budget guard.

    1. import time
    2. from collections import defaultdict
    3. class BudgetGuard:
    4. """Control a daily budget per tenant.
    5. This example uses in-process memory. Multi-instance deployments
    6. should use shared storage instead.
    7. """
    8. def __init__(self, daily_limit: float):
    9. self.daily_limit = daily_limit
    10. self.spent: dict[str, float] = defaultdict(float)
    11. self.current_day = time.strftime("%Y-%m-%d")
    12. def try_spend(self, tenant: str, cost: float) -> bool:
    13. today = time.strftime("%Y-%m-%d")
    14. if today != self.current_day:
    15. self.spent.clear()
    16. self.current_day = today
    17. if self.spent[tenant] + cost > self.daily_limit:
    18. return False
    19. self.spent[tenant] += cost
    20. return True

    Before making a request, calculate its estimated cost and then call try_spend. If it returns False, route the request to a fallback path, such as switching to a smaller model or returning a cached result.

    This implementation does not address concurrency or persistence. A production system should use shared storage with atomic operations.

    8. Architecture Principles for Handling Price Changes

    8.1 Externalize Price Configuration

    Store unit prices in a configuration service or a separate configuration file. Record the configuration version and effective time.

    When prices change, the configuration can be updated without modifying business logic.

    8.2 Evaluate Cost and Quality Together

    Before switching models, use a fixed evaluation set to compare accuracy and format-compliance rates. Cost reduction should not be assessed independently from application quality.