How to Evaluate LLM API Cost and Performance Systematically

    A practical guide to comparing LLM APIs by real cost, token usage, task quality, latency, and throughput—not list price alone. It covers monthly cost estimation, measurement, evaluation sets, cost per successful task, routing and caching choices, and post-launch monitoring.

    1. Why Unit Price Is Not Enough

    Model APIs usually charge separately for input tokens and output tokens, and the two rates often differ. When the output rate is higher, long-form generation costs much more than short-output tasks such as classification or extraction. Unit price is only one parameter in the cost model. Real spend also depends on call volume, context length, retry rate, and similar factors.

    Total cost can be split into these parts:

    • Input cost: tokens from the system prompt, conversation history, retrieved references, and the user question
    • Output cost: tokens in the model’s generated content
    • Hidden cost: failed retries, timeout resends, and extra calls used to validate results
    • Engineering cost: time spent on development, debugging, prompt maintenance, and exception handling

    The script below estimates monthly inference cost from call volume. All parameters are hypothetical and only illustrate the calculation:

    1. def estimate_monthly_cost(
    2. requests_per_day: int,
    3. avg_input_tokens: int,
    4. avg_output_tokens: int,
    5. price_input_per_m: float,
    6. price_output_per_m: float,
    7. retry_rate: float = 0.0,
    8. days: int = 30,
    9. ) -> float:
    10. """Estimate monthly inference cost from call volume. Price units must match the cost output (for example, per million tokens)."""
    11. if not 0 <= retry_rate < 1:
    12. raise ValueError("retry_rate must be in [0, 1)")
    13. total_requests = requests_per_day * days * (1 + retry_rate)
    14. input_cost = total_requests * avg_input_tokens / 1_000_000 * price_input_per_m
    15. output_cost = total_requests * avg_output_tokens / 1_000_000 * price_output_per_m
    16. return input_cost + output_cost
    17. cost = estimate_monthly_cost(
    18. requests_per_day=5000,
    19. avg_input_tokens=1200,
    20. avg_output_tokens=400,
    21. price_input_per_m=2.0,
    22. price_output_per_m=8.0,
    23. retry_rate=0.05,
    24. )
    25. print(f"Estimated monthly cost: {cost:.2f}")

    The retry rate multiplies the cost of every call, so measuring the real production retry rate matters.

    2. Measuring and Estimating Token Usage

    Token counts cannot be inferred directly from character or word counts. Models use different tokenizers, so the same Chinese text can consume very different token counts across services. A reliable approach is:

    1. Sample real production traffic and record the usage fields returned by each request, including input and output token counts.
    2. Group statistics by scenario—for example, customer support Q&A, document summarization, and code generation—and report means and percentiles for each.
    3. Watch long-tail values such as P90 and P99, because a small number of very long requests often account for most of the spend.
    4. For multi-turn conversations, remember that history is counted again on every turn. As context grows, cost rises roughly linearly, and sometimes faster.

    Log each call on the server: model version, input and output tokens, latency, and success or failure. Those records support both cost accounting and later optimization.

    3. Quality Evaluation: Build a Set That Matches the Work

    Public leaderboard scores are only a rough reference. Selection should rest on evaluations tied to the actual workload. A useful evaluation set can be built as follows:

    • Collect representative samples that cover common requests, edge cases, and high-risk scenarios. A few hundred items is often enough to start.
    • Define a rubric for each task type, covering factual correctness, format compliance, tone and style, and whether key information is missing.
    • Combine automated checks with human review. Format, fields, and executability can be judged in code; semantic quality needs people or a calibrated review process.
    • Fix the random seed and decoding parameters so models are compared under the same conditions.

    Report results as task pass rates, not only a single average score. For example, raising the pass rate of a contract-clause extraction task from 80% to 92% is usually easier for the business to interpret than a small change in an overall score.

    4. Latency and Throughput

    Interactive applications are highly sensitive to response speed. Common metrics include:

    • Time to first token: how long the user waits before seeing the first token, which strongly affects streaming UX
    • Output rate: tokens generated per second, which determines how long a long answer takes to finish
    • End-to-end latency at P95 and P99: these reflect peak-hour experience better than the average
    • Timeout and rate-limit rates: whether the service stays stable as concurrency rises

    Offline batch jobs care more about throughput and total runtime. They can accept higher per-request latency in exchange for lower cost or higher concurrency.

    5. Put Cost and Quality on the Same Sheet

    Comparing cost per call alone leads to one-sided conclusions. A better metric is cost per successful task:

    Cost per successful task = cost per call ÷ task pass rate

    For example, suppose option A costs 0.02 per call with an 85% pass rate, so cost per success is about 0.0235. Option B costs 0.05 per call with a 98% pass rate, or about 0.0510 per success. B has a higher unit price, but if A’s failures require human rework, the labor cost of each rework can far exceed the price gap. The comparison should include rework cost.

    These figures are hypothetical. Real selection should use your own data.

    6. Selection and Rollout

    Common ways to choose among models include:

    • A single large model: simpler to build and more consistent, but expensive on easy tasks
    • Tiered routing: a smaller model handles the request first, and low confidence or failure escalates to a stronger model. This can cut average cost substantially, at the price of routing rules and a second validation step
    • Caching: store results for repeated questions or fixed templates, which fits Q&A and knowledge retrieval
    • Prompt trimming: remove redundant instructions and irrelevant history to control input size
    • Output constraints: use explicit format requirements and length limits to cut unnecessary generation

    Start with a single model. Add tiered routing only after you have enough usage data. Complex architecture introduced too early raises maintenance cost and may not pay off.

    7. Ongoing Monitoring After Launch

    Prices, versions, and model behavior can all change. After launch, keep monitoring:

    • Set budget alerts and track spend by day or by product line so unusual swings are investigated quickly
    • Re-run the evaluation set whenever the model version or prompts change, to catch quality regressions
    • Record pass rate, latency, and cost for each version so the history is traceable
    • Keep a fallback for critical workloads so you can switch if the primary service is unavailable or rate-limited, and evaluate that fallback the same way

    Cost and quality have to be managed together over time. A one-time evaluation at selection does not keep up with growing volume or later service changes.