LLM API Selection: How to Evaluate Efficiency and Token Costs

    Selecting the right LLM API starts with classifying task complexity, not with choosing the most powerful model. This article explains how to benchmark candidate models on your own workload, estimate monthly token costs from per-token pricing, use prompt caching without introducing data or version risks, and tier simple versus complex tasks across different model classes. It also includes a practical pre-launch checklist for cost control and reliability.

    Start with Task Complexity, Not Model Strength

    Many cost problems come from choosing the model first and looking for savings later. A better sequence is to classify business tasks by complexity, then match each level to an appropriate model.

    Use four questions to classify tasks:

    • Does the task need only one input and one output? For example, text classification or short rewriting.
    • Does the task depend on results from previous steps? For example, retrieving documents before generating a summary.
    • Does the task require external tools, such as database queries, numerical calculation, or code execution?
    • If a single step fails, will the whole chain fail or require human intervention?

    Tasks that satisfy two or more of these conditions are usually complex. Complex tasks test a model’s planning ability and tool-calling accuracy, so they need to be tested separately. Output fluency alone is not enough.

    Validate Efficiency Improvements with Your Own Data

    Vendor efficiency numbers are usually based on their own test sets, which may not match your business scenario. To judge whether an improvement is real, focus on these three mechanisms and confirm that each one’s prerequisites are met.

    1. Fewer invalid intermediate steps. When model planning is more accurate, a task requires fewer call rounds. The prerequisite is a clear task objective and complete tool definitions. If the task description is vague, better planning will produce almost no benefit.
    2. Information location in long contexts. If the model can find key sections in a long document faster, you do not need to put the entire document into the prompt every time. The prerequisite is a clear document structure, such as headings, sections, and fields.
    3. More stable tool parameter parsing. Fewer parameter errors mean fewer retries. This can be measured directly: record the tool call failure rate and retry count.

    The validation method is straightforward. Select 100 to 300 real historical tasks, run the same inputs on candidate models, and record these metrics:

    • Task completion rate: the proportion of outputs that pass business acceptance rules.
    • Average call rounds: the number of model requests needed to complete one task.
    • Median and tail latency, such as P95, rather than average latency.
    • Average token consumption per task.

    If a candidate model does not significantly improve task completion rate, do not replace the current solution just because its unit price is lower. The extra retries and manual review caused by a cheaper model may offset the price advantage.

    Estimate Cost with Token-Based Pricing

    Mainstream LLM APIs usually charge by token and distinguish three price categories:

    • Regular input tokens: prompt and context parts that do not hit the cache.
    • Cached input tokens: repeated prefixes that hit the server-side cache, usually priced lower than regular input.
    • Output tokens: content generated by the model, usually priced higher than input.

    Monthly cost can be estimated with this formula:

    1. Monthly cost =
    2. Monthly requests ×
    3. (
    4. Regular input tokens × Regular input price
    5. + Cached input tokens × Cached input price
    6. + Output tokens × Output price
    7. )
    8. ÷ Unit conversion factor

    Use the vendor’s official price list as the source of unit prices. Before using the formula, confirm whether the billing unit is per million tokens or per thousand tokens. Otherwise, the estimate can be off by an order of magnitude.

    The script below can be run directly. The prices are placeholders and do not represent any vendor’s actual pricing.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class PriceTable:
    4. """Unit price: CNY per million tokens. Placeholder values; replace with official pricing."""
    5. input_per_m: float
    6. cached_input_per_m: float
    7. output_per_m: float
    8. @dataclass
    9. class UsageStats:
    10. """Token usage for a single request."""
    11. input_tokens: int # Regular input that did not hit cache
    12. cached_input_tokens: int # Input that hit the cache
    13. output_tokens: int # Model output
    14. def estimate_request_cost(usage: UsageStats, price: PriceTable) -> float:
    15. """Calculate the cost of one request."""
    16. total = (
    17. usage.input_tokens * price.input_per_m
    18. + usage.cached_input_tokens * price.cached_input_per_m
    19. + usage.output_tokens * price.output_per_m
    20. )
    21. return total / 1_000_000
    22. def estimate_monthly_cost(
    23. usage: UsageStats, price: PriceTable, requests_per_month: int
    24. ) -> float:
    25. """Estimate total monthly cost."""
    26. if requests_per_month < 0:
    27. raise ValueError("requests_per_month cannot be negative")
    28. return estimate_request_cost(usage, price) * requests_per_month
    29. if __name__ == "__main__":
    30. price = PriceTable(input_per_m=10.0, cached_input_per_m=2.0, output_per_m=30.0)
    31. usage = UsageStats(input_tokens=800, cached_input_tokens=3200, output_tokens=500)
    32. print(f"Single request cost: {estimate_request_cost(usage, price):.6f} CNY")
    33. print(f"Monthly cost (100k requests): {estimate_monthly_cost(usage, price, 100_000):.2f} CNY")

    A key assumption is that usage statistics are accurate. After launch, replace estimates with actual usage returned by the API and reconcile with bills regularly.

    Cache Reuse: Save Cost While Avoiding Three Risks

    Caching works best for stable prefixes, such as system prompts, product manuals, and tool definitions. Pay attention to these three points.

    • Cache keys are determined by content. The key should be generated as a hash of the prefix content, model version, and prompt version, not a manually assigned name. Manually assigned keys can remain unchanged after content updates, causing the model to read outdated material.
    • Invalidate old caches when versions change. After document updates, prompt modifications, or model switches, the old prefix must not continue to be used.
    • Do not put private data into a shared prefix. If sensitive information from different tenants or users is placed into the same prefix, it may cause data leakage across tenants.

    The example below shows how to generate a cache key and put fixed content at the front of the message. If the provider manages caching on the server side, the client still needs to keep the prefix content stable; the local key is mainly used for logging and monitoring cache hits.

    1. import hashlib
    2. import json
    3. def build_cache_key(prefix_text: str, model_version: str, prompt_version: str) -> str:
    4. """Generate a stable cache key from prefix content, model version, and prompt version."""
    5. payload = json.dumps(
    6. {"prefix": prefix_text, "model": model_version, "prompt": prompt_version},
    7. ensure_ascii=False,
    8. sort_keys=True,
    9. )
    10. return hashlib.sha256(payload.encode("utf-8")).hexdigest()
    11. def build_request_messages(static_prefix: str, dynamic_query: str) -> list[dict]:
    12. """Put fixed content first for cache hits; put user input last."""
    13. return [
    14. {"role": "system", "content": static_prefix},
    15. {"role": "user", "content": dynamic_query},
    16. ]

    Cache hit rate should be a core monitoring metric. When cached content expires, the same content is billed as regular input, so costs can rise suddenly. The team should know the cache lifetime and receive alerts when the hit rate drops.

    Tiered Routing: Send Simple Tasks to a Lower-Cost Path

    The basic approach is to classify first, then escalate when needed.

    1. Use rules or a lightweight classifier to determine task level.
    2. Send simple tasks directly to a lower-priced model.
    3. For complex tasks, or when the lower-priced model’s output confidence is insufficient, escalate to a higher-priced model.

    Escalation adds latency and cost. Therefore, set a maximum escalation count and record the reason for every escalation. If a certain task type has a persistently high escalation rate, the classification rules need adjustment.

    Pre-Launch Checklist

    1. A small-scale comparison with real historical data has been completed, including completion rate, call rounds, and latency.
    2. The billing unit has been confirmed from the official price list, and a monthly cost range has been calculated.
    3. A monthly budget alert has been set, for example notifying the owner when actual spend reaches 80% of the budget.
    4. Cache keys include version information and have a clear invalidation plan.
    5. Shared prefixes do not contain private data.
    6. Tool calls have a maximum retry count to prevent failure loops from amplifying cost.
    7. Token usage is recorded for each request so bills can be reconciled later.

    Conclusion

    Model selection should start with task complexity, then validate efficiency with your own data, and finally estimate cost with a token-based formula. Vendor efficiency metrics and prices are only a starting point. Use the current official model documentation and price list from each provider, and make decisions only with numbers that have been tested against your actual workload.