Evaluating LLM API Cost Efficiency: A Practical Guide for Agent Deployments

    Choosing a large language model API by comparing per-million-token prices alone often leads to the wrong conclusion. This guide explains why the lowest unit price does not always mean the lowest cost, and how to evaluate API cost efficiency based on cost per task instead. It breaks the bill into a reproducible formula covering input price, output price, cache discounts, average output length, context reuse rate, and retry rate, then outlines four underestimated cost levers and a methodology for reliable side-by-side evaluations. It also shares practical optimization points for Agent scenarios, such as prefix stabilization, context compression, tiered routing, output constraints, and full-chain observability, along with common pitfalls and a deployment checklist. The goal is to help teams achieve lower cost per task in a multi-model environment through measurable and sustainable engineering practices.

    1. Background: Why the Lowest Unit Price Is Not the Lowest Cost

    When selecting a large language model API, many teams compare the input and output prices per million tokens and conclude that one vendor is the cheapest. In real business workloads, however, the bill is determined by all the tokens consumed by a complete task, not by the numbers on a price sheet. A model with comparable capability may end up costing more per task if it produces more verbose output, has fewer cache hits, or requires more retries.

    Cost efficiency evaluation therefore needs to shift from unit price to cost per task and make the key cost variables explicit: input price, output price, cache discount, average output length, first-turn context reuse rate, and failure retry rate. Only when these quantities are placed in the same formula does a meaningful side-by-side comparison become possible.

    2. Cost Model: Breaking the Bill into a Reproducible Formula

    A practical approximation model is as follows:

    1. Cost per task =
    2. input tokens × input price × (1 - cache discount × cache hit rate)
    3. + output tokens × output price
    4. + retry count × cost per call

    The cache discount refers to the proportional reduction applied to the cached portion relative to the original price. The cache hit rate depends on whether stable prefixes such as system prompts, tool definitions, and long documents are reused. From an engineering perspective, it is recommended to log prompt_tokens, completion_tokens, cached token counts, latency, and a task identifier for every call so that trustworthy attribution is possible.

    Example instrumentation structure:

    1. record = {
    2. "task_id": task_id,
    3. "model": model_name,
    4. "prompt_tokens": usage.prompt_tokens,
    5. "completion_tokens": usage.completion_tokens,
    6. "cached_tokens": getattr(usage, "cached_tokens", 0),
    7. "latency_ms": elapsed_ms,
    8. "retry": attempt_index,
    9. }
    10. log_service.append(record) # Write to the logging service for later aggregation and analysis

    3. Four Underestimated Cost Levers

    1. Cache discounts. The longer the stable prefix and the more frequently it is reused, the more significant the savings from caching. A common industry practice is to offer a relatively high reduction on repeated prefixes. Keeping the system prompt, tool schema, and knowledge base snippets fixed at the front of the request is key to improving the hit rate.
    2. Output length. Output tokens are usually billed at a higher price, so a verbose model directly inflates the bill. If two models have comparable capability but one produces more concise output, its cost advantage is further amplified.
    3. Price structure. The relative multiplier between input and output, and whether tiered pricing exists, affect the optimal choice under different workloads. The best model for extraction tasks with long inputs and short outputs may be completely different from that for generation tasks with short inputs and long outputs.
    4. Stability and retries. Retries caused by timeouts, rate limiting, or non-compliant formatting are the invisible part of the bill. The longer the Agent chain, the more pronounced the multiplier effect of retries.

    4. Methodology: How to Run a Trustworthy Side-by-Side Evaluation

    • Fix the evaluation set: use stratified sampling of real business samples covering three workload types: short question answering, long-document extraction, and multi-turn tool calling.
    • Fix the context strategy: keep system prompts, tool definitions, and parameters such as temperature consistent so that differences are not wrongly attributed to the model itself.
    • Record on two dimensions: capture both capability metrics (task success rate, format compliance rate) and cost metrics (cost per task, P95 latency).
    • Recompute and verify: recalculate the bill with a unified formula and align it with the actual invoice. A large discrepancy indicates missing instrumentation.
    • Express conclusions carefully: state the difference in cost per task under the premise of comparable capability, rather than absolute price levels.

    5. Practical Points for Agent Scenarios

    Agents are characterized by short inputs across multiple turns, tool results fed back into the context, and continuously growing context, so the optimization focus differs from single-turn question answering:

    • Prefix stabilization: place tool definitions and specifications at the very front without dynamic concatenation to improve cache hits.
    • Context compression: summarize or structurally trim historical tool results to suppress input expansion.
    • Tiered routing: send simple intents to a lightweight model and complex planning to a stronger model, using rules or a small classifier to split traffic.
    • Output constraints: control redundancy through structured output and length limits to reduce high-priced output tokens.
    • Full-chain observability: build a cost dashboard based on the logging service and monitoring alerts, and locate abnormal amplification by task dimension.
    1. def route(intent, context):
    2. if intent in {"chitchat", "faq"} and len(context) < 2000:
    3. return "light_model"
    4. return "strong_model"

    6. Common Pitfalls

    • Looking only at unit price while ignoring caching: under high-reuse workloads, the cost ranking may reverse entirely.
    • Using public leaderboards instead of business evaluations: leaderboard task distributions differ greatly from real workloads.
    • Ignoring output length differences: when capability is comparable, the more concise option is often cheaper.
    • Not tracking retries: stability issues show up as a multiplier on the bill.
    • Locking in a single model once and for all: keeping a switchable abstraction layer is the only way to keep up with changing prices and capabilities.

    7. Deployment Checklist

    1. Build a unified invocation abstraction layer that hides differences between vendor interfaces, making switching and canary releases easier.
    2. Enable cost instrumentation with fields covering at least input, output, cache hits, and retries.
    3. Build a stratified evaluation set, retest quarterly, and update routing thresholds.
    4. Set budget alerts and a cost-per-task baseline, with automatic degradation or rate limiting when thresholds are exceeded.
    5. Include cache hit rate and format compliance rate in team metrics to form a continuous optimization loop.

    8. Conclusion

    Cost efficiency is not a number on a price sheet, but an engineering capability that is reproducible, observable, and continuously optimizable. By formalizing the cost formula, normalizing evaluation, and turning routing and caching into infrastructure, teams can reliably achieve a lower cost per task in a multi-model environment with comparable capabilities. If managed logging, monitoring, and containerized inference are needed, they can be assembled on demand from the general cloud product categories offered by Baidu AI Cloud while keeping the architecture neutral and portable.