LLM API Cost Analysis and Model Selection After Price Cuts

    Lower token prices do not automatically reduce total LLM spending. This guide explains how to calculate API costs, measure the cost per successful task, match model capability to task difficulty, implement routing and escalation, compare hosted APIs with self-hosted open-weight models, and establish engineering controls for ongoing cost and quality management.

    1. Why Lower Unit Prices Can Still Produce Uncontrolled Bills

    Over the past two years, the unit prices of large language model services have continued to fall, while price differences between providers have widened. However, a lower price list does not automatically mean lower total costs. Growing request volumes, longer contexts, and more complex inference workflows can all increase actual spending. Many teams find that individual calls are inexpensive, yet their monthly bill still exceeds the budget.

    Model selection should therefore focus less on “which model has the lowest token price” and more on “what is the total cost of completing a task?” Answering that question requires analyzing billing rules, calling patterns, and business quality within the same framework.

    2. Understanding Token-Based Pricing

    Most LLM APIs charge by token. Common billing components include:

    1. Input tokens: Prompts, conversation history, retrieved reference material, and other content sent in the request.
    2. Output tokens: The response generated by the model. For the same model, output tokens are typically more expensive than input tokens.
    3. Cached input tokens: Some services offer discounted pricing for repeated prefixes. Long system prompts and fixed documents are good candidates for this pricing rule.
    4. Reasoning tokens: Some reasoning-oriented models count their reasoning process as output tokens. The exact rules depend on the provider’s documentation.

    The general formula for a single call is:

    1. Single-call cost =
    2. uncached input tokens × input price
    3. + cached input tokens × cached price
    4. + output tokens × output price

    Prices are commonly quoted per million tokens. The following implementation uses example prices only and does not represent the actual pricing of any service.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Pricing:
    4. input_per_m: float # Price per million input tokens
    5. output_per_m: float # Price per million output tokens
    6. cached_per_m: float | None = None # Price per million cached tokens; None means no discount
    7. def call_cost(p: Pricing, input_tokens: int, output_tokens: int, cached_tokens: int = 0) -> float:
    8. """Calculate the cost of one call."""
    9. uncached = input_tokens - cached_tokens
    10. if uncached < 0:
    11. raise ValueError("Cached tokens cannot exceed total input tokens")
    12. cached_price = p.cached_per_m if p.cached_per_m is not None else p.input_per_m
    13. cost = uncached * p.input_per_m / 1_000_000
    14. cost += cached_tokens * cached_price / 1_000_000
    15. cost += output_tokens * p.output_per_m / 1_000_000
    16. return cost
    17. # Example: 2,000 input tokens and 500 output tokens.
    18. # The example prices are 2 per million input tokens and 8 per million output tokens.
    19. demo = Pricing(input_per_m=2.0, output_per_m=8.0)
    20. print(round(call_cost(demo, 2000, 500), 6)) # 0.008

    The result is 0.008 in the example currency. At 100,000 calls per day, the daily cost would be approximately 800. As usage scales, details such as the input-to-output ratio and cache hit rate can materially affect the total. Estimates should therefore be based on actual request logs whenever possible.

    3. Token Price Is Not Total Cost

    A model with a lower token price does not necessarily produce a lower task cost. There are three main reasons:

    • Completing the same task may require more tokens, especially when the model generates verbose responses.
    • Failed tasks require retries, and retries incur additional charges.
    • Failed outputs may require human review or later correction, creating costs that do not appear directly on the API bill.

    A more useful metric is the cost per successful task:

    1. Cost per successful task =
    2. single-call cost ÷ task success rate
    3. + human review cost per successful task

    For example, Model A costs 0.008 per call and has a 95% success rate. Model B costs 0.004 per call and has a 60% success rate. The calculated cost per successful task is approximately 0.0084 for Model A and 0.0067 for Model B. Model B is still cheaper in this example, but if it requires substantially more human review, the conclusion may change.

    Review costs should therefore be included in model selection.

    1. def cost_per_success(unit_cost: float, success_rate: float, review_cost: float = 0.0) -> float:
    2. """Calculate the total cost per successful task.
    3. success_rate must be in the range (0, 1].
    4. """
    5. if not 0 < success_rate <= 1:
    6. raise ValueError("success_rate must be in the range (0, 1]")
    7. return unit_cost / success_rate + review_cost

    4. Match Model Capability to Task Difficulty

    Task difficulty varies significantly within the same application. Sending every request to the most capable model can create unnecessary costs. A common approach is to divide models into three capability tiers and assign a default tier to each task category.

    Task type Typical characteristics Recommended tier
    Classification, extraction, and tagging Short outputs and clear rules Light
    Summarization, rewriting, and general question answering Requires some understanding and allows moderate error tolerance Balanced
    Multi-step reasoning, complex code, and long-document analysis Long reasoning chains and high error costs Flagship

    These tiers should be based on measured performance rather than provider naming or pricing. The boundaries between tiers should be validated with an evaluation set.

    5. Routing and Escalation

    After defining the tiers, implement routing rules that direct each request to an appropriate model. A basic strategy is to use lightweight rules or a smaller model to estimate task difficulty, then route the request accordingly. If the response fails validation, escalate it to a higher tier and retry.

    1. def route(task_type: str, context_tokens: int, needs_multi_step: bool) -> str:
    2. """Return a model tier based on task characteristics."""
    3. if needs_multi_step or context_tokens > 32_000:
    4. return "flagship"
    5. if task_type in {"classification", "extraction", "tagging"}:
    6. return "light"
    7. return "balanced"
    8. ESCALATION = {"light": "balanced", "balanced": "flagship", "flagship": None}
    9. def call_with_fallback(tier: str, invoke, validate, max_hops: int = 2):
    10. """Call a model and escalate when validation fails.
    11. invoke and validate are supplied by the caller.
    12. """
    13. for _ in range(max_hops + 1):
    14. result = invoke(tier)
    15. if validate(result):
    16. return tier, result
    17. tier = ESCALATION.get(tier)
    18. if tier is None:
    19. break
    20. raise RuntimeError("No tier passed validation; manual handling is required")

    Escalation must have a hop limit. Otherwise, failed requests may be repeatedly sent to expensive models, causing costs to rise. Validation should rely on deterministic checks whenever possible, such as format validation, field completeness, and comparison of key information.

    6. Open-Weight Models Versus Hosted APIs

    As open-weight models mature, organizations can choose private deployment and potentially fine-tune models for their business needs. This approach offers greater data control and customization. At high request volumes, it may also reduce the unit cost of inference.

    The trade-offs include GPU resources, inference-service operations, model upgrades, and security and compliance investments.

    A preliminary break-even analysis can use the following formula:

    1. Monthly request volume × hosting cost savings per request
    2. ≥ monthly fixed cost of private deployment
    3. including hardware depreciation, operations staff, and electricity

    If usage has not reached this threshold, a hosted API is generally more economical. However, if strict data isolation or customization requirements apply, private deployment may still be the better choice even when its direct cost is somewhat higher.

    7. Engineering Governance and Cost Observability

    Cost reduction requires continuous measurement and controls rather than a one-time model selection decision. Recommended engineering practices include:

    • Usage instrumentation: Record input tokens, output tokens, and cached tokens by feature, tenant, and model. Use the data to build a cost dashboard.
    • Budgets and alerts: Set daily and monthly budgets for each business line. Connect them to monitoring alerts so abnormal usage is detected quickly.
    • Prompt optimization: Remove repetitive system-prompt content, place stable content where it can benefit from caching, and delete unnecessary conversation history.
    • Output constraints: Use clear format requirements and length limits to control output tokens and prevent irrelevant, verbose responses.
    • Batch processing: For tasks that do not require real-time responses, such as offline labeling and overnight reports, use batch processing to reduce costs when supported.
    • Semantic caching: Reuse previous results for frequent or semantically similar questions to reduce duplicate calls. Set expiration policies and isolate sensitive data appropriately.

    8. Use Evaluation Data to Support Cost Decisions

    Every cost-reduction measure should preserve the required level of quality. Build a fixed evaluation set that covers major task types and representative difficult cases. Run regression tests whenever you change a model, adjust prompts, or modify routing rules.

    Evaluation should cover three categories:

    1. Quality: Accuracy, format compliance, and human ratings.
    2. Efficiency: End-to-end latency and time to first token.
    3. Cost: Cost per successful task and total daily cost.

    A cost-reduction strategy is usable only when all three categories meet their targets. If a change lowers spending but causes a significant quality decline, it should be treated as a failed optimization.

    9. Action Checklist

    1. Map current use cases by function and measure the input and output token distribution for each task category.
    2. Use real logs to calculate both single-call cost and cost per successful task.
    3. Assign tasks to capability tiers and validate the assignments with an evaluation set.
    4. Implement routing and escalation with a maximum escalation limit.
    5. Add usage instrumentation and budget alerts, then review cost and quality every week.
    6. Perform a break-even analysis for self-hosted deployment before choosing the deployment strategy.

    LLM prices will continue to change, but a repeatable cost-analysis method is more valuable than any provider’s price at a single point in time. By turning cost into measurable variables and evaluating it alongside quality, teams can quickly adjust their approach as pricing and usage patterns evolve.