How to Evaluate LLM Inference Costs: From Pricing Structure to A/B Testing

    Understanding the true cost of large language model inference requires more than comparing per-token prices. This article explains how API pricing actually works, walks through building a per-task cost model with example Python code, and shows how to run A/B tests that account for quality, retries, and latency. It also covers practical cost controls for scheduled batch processing and how to make a data-driven, reproducible model selection decision.

    1. Sticker Price Is Not Real Cost

    LLM APIs typically charge by token, with separate prices for input and output. Output tokens usually cost more than input tokens, and the ratio between the two varies by use case. Comparing unit prices alone makes it hard to tell which option is actually cheaper.

    Your actual bill is driven by several factors:

    • Token volume per request: Longer prompts and more context mean more input tokens.
    • Number of calls per task: Multi-turn reasoning, tool calls, and failed retries can multiply call volume.
    • Cache hit rate: Some providers bill cached content at a lower rate when identical prefixes are reused, so cache hit rate directly affects cost.
    • Time-based pricing: Some providers offer different prices for different time windows, allowing batch jobs to run during off-peak hours. Whether such rules exist depends on the provider’s published pricing terms.

    So when comparing options, evaluate the “total cost of completing a job,” not a single unit price.

    2. Build a Per-Task Cost Model

    The cost of a single task can be described with this formula:

    Task cost = (uncached input tokens × input price + cached input tokens × cached price + output tokens × output price) × average number of rounds

    Every variable should be measured from real call logs rather than estimated from experience. The script below demonstrates how to compute per-task cost from logs. Prices shown are illustrative examples only, not quotes from any provider.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Price:
    4. input: float # price per million uncached input tokens (example value)
    5. cached: float # price per million cached input tokens (example value)
    6. output: float # price per million output tokens (example value)
    7. def task_cost(usage: dict, price: Price, rounds: int = 1) -> float:
    8. """Compute the cost of one task. usage fields come from the API usage response."""
    9. per_round = (
    10. usage["input_tokens"] * price.input
    11. + usage["cached_tokens"] * price.cached
    12. + usage["output_tokens"] * price.output
    13. ) / 1_000_000
    14. return per_round * rounds
    15. def average_task_cost(logs: list[dict], price: Price) -> float:
    16. costs = [task_cost(log["usage"], price, log["rounds"]) for log in logs]
    17. return sum(costs) / len(costs) if costs else 0.0

    The key point in this code is that rounds are included in the calculation. Many options look cheap in single-turn tests, but the total cost can be much higher in real tasks that require multiple correction rounds.

    3. Compare Options with A/B Testing

    Comparing cost per call alone ignores quality differences. A cheaper option with a low pass rate can drive up actual spending through frequent retries. A sound A/B test should meet these conditions:

    1. Control variables: Both groups run the same tasks, the same prompt templates, and the same output format constraints; only the underlying service changes.
    2. Cover a full cycle: Run continuously for at least a week to cover both peak and off-peak periods, so occasional fluctuations don’t skew the results.
    3. Randomize traffic: Hash task IDs into groups so that A and B have similar task type distributions.
    4. Track three metric types: cost, quality, and latency.

    The core comparison metric is “cost per accepted result,” computed as follows:

    1. def cost_per_success(records: list[dict]) -> float:
    2. total = sum(r["cost"] for r in records)
    3. passed = sum(1 for r in records if r["passed"])
    4. return total / passed if passed else float("inf")

    This metric accounts for unit price, number of rounds, and pass rate together. If the two options perform similarly on this metric, compare latency and stability as well—don’t decide on cost alone.

    Quality can be judged with a combination of two methods. Automated rules check deterministic conditions such as format, required fields, and keywords. Manual sampling judges semantic quality; the sampling ratio can be set based on task volume, and with small samples it’s best to review everything.

    4. Controlling Costs for Scheduled Batch Jobs

    Many teams invoke models through scheduled batch jobs—for example, generating content overnight or cleaning data periodically. Cost control in these scenarios can focus on the following:

    • Run off-peak: Non-real-time jobs can be scheduled during low-traffic or lower-priced windows. Confirm beforehand that the target window actually has the corresponding pricing rule.
    • Set budget caps: Assign a token budget to each batch, pause automatically and alert when the threshold is exceeded, and prevent runaway tasks from burning resources.
    • Limit retries: Use exponential backoff for failed requests with a maximum retry count. Unbounded retries are a common cause of cost blowups.
    • Improve cache hit rate: Place stable system prompts and fixed examples at the beginning of requests and put variable task content at the end. The longer and more stable the shared prefix, the more likely caching hits.
    • Log usage: Save the input, cached, and output token counts for every call, along with model version and number of rounds. Complete records are the basis for month-end accounting and troubleshooting.

    5. Making the Decision and Re-testing

    A selection decision should meet these requirements:

    • Use “cost per accepted result” as the primary metric, not unit price or cost per call.
    • Document the measurement period, sample size, and quality judgment method so others can reproduce the results.
    • Re-test periodically. Prices, rate limits, and model versions all change—the best option from last cycle isn’t necessarily the best long term.

    The right order for cost optimization is: measure first, then compare, then decide based on data. Only by recording both the cost and result quality of every call can a team tell which optimizations actually work.