LLM API Cost Optimization and Model Selection: A Practical Guide
Learn how to evaluate LLM APIs by cost, capability, and latency rather than token prices alone. This guide covers task-level cost modeling, prefix caching, output limits, agent budgets, tiered routing, batch processing, and cost monitoring to help engineering teams reduce spending while maintaining quality.
1. Why Cost Matters as Model Capabilities Converge
Over the past two years, large language models have improved rapidly, narrowing the gaps between mainstream models in general comprehension, code generation, and structured extraction. Once capability is no longer the main bottleneck, engineering teams face a more practical question: how much does each task cost, and can the application operate at scale?
A model that scores a few percentage points higher on a benchmark may still be a poor production choice if it costs several times more per task. This is particularly important for large-scale offline processing and high-frequency online requests.
Model selection is therefore shifting from capability alone to a three-way trade-off between capability, cost, and latency. Rather than benchmarking specific products, this guide provides a reusable approach to cost analysis and optimization.
2. Build a Task-Level Cost Model
Most LLM APIs charge separately for input and output tokens, with output tokens typically costing substantially more. Prefix-cache availability and caching discounts can also have a major impact on the actual bill.
A simplified task-cost formula is:
cost = (in_tokens * p_in * (1 - hit_rate * discount)+ out_tokens * p_out) / 1_000_000
Here, hit_rate represents the share of input tokens served from cache, and discount is the reduction relative to the full input price.
Consider hypothetical prices of CNY 1 per million input tokens, CNY 2 per million output tokens, and a 98% cached-input discount. These figures are illustrative, not actual provider prices.
def task_cost(in_tokens, out_tokens, p_in=1.0, p_out=2.0,hit_rate=0.0, cache_discount=0.98):billable_in = in_tokens * (1 - hit_rate * cache_discount)return (billable_in * p_in + out_tokens * p_out) / 1e6# Long context with a high cache hit rateprint(task_cost(20000, 800, hit_rate=0.9)) # Approximately CNY 0.00396# The same context without cachingprint(task_cost(20000, 800, hit_rate=0.0)) # Approximately CNY 0.0216
In this example, caching reduces the cost of the same task by more than fivefold. The lowest listed token price does not necessarily produce the lowest task cost. What matters is the total expense of completing a business task end to end.
3. Reuse Cached Prefixes
Prefix caching is one of the highest-return engineering optimizations. Cache reuse depends on an identical request prefix, so the basic rule is: put stable content first and variable content last.
- Keep system prompts, role definitions, and output requirements unchanged. Do not insert timestamps, random IDs, usernames, or other frequently changing fields into the stable prefix.
- Place long reusable content—such as few-shot examples, knowledge-base excerpts, and tool definitions—near the beginning, with a consistent ordering.
- Put the current user input and changing portions of retrieval results toward the end.
- Avoid repeatedly rewriting the prefix within a conversation. Append new turns incrementally rather than rebuilding the entire history.
A stable prompt structure might look like this:
[Fixed] System role and constraints[Fixed] Tool/function definitions in a consistent order[Fixed] Few-shot examples[Semi-fixed] Retrieved document excerpts in a stable order[Variable] Current user input
Stable ordering alone does not make changing content cacheable. Keep genuinely reusable material ahead of sections that vary between requests.
4. Control Output Tokens
Output tokens are often an overlooked source of cost. Their higher unit price makes unnecessary generation expensive, and longer outputs increase total response time. Time to first token should also be monitored as a separate latency measure.
Common causes of excessive output include:
- Failing to set
max_tokens. - Asking for a “detailed explanation” without a length constraint.
- Having reasoning or chain-of-thought tokens counted toward billed output, depending on the API.
- Allowing unrestricted fields in structured responses.
To keep output under control:
- Specify length and format. Use JSON Schema or enumerated values to restrict fields and reduce unnecessary generation.
- Request results only for bounded tasks. For classification, extraction, and rewriting, explicitly ask for the result without an explanation.
- Generate long documents in sections. This limits the cost of retrying a failed, unusually long response.
- Bound retries and timeouts. Prevent failed requests from repeatedly adding to the bill.
5. Manage the Cost of Multi-Turn Agents
Agent workloads can consume an order of magnitude more tokens than conventional question answering. Each tool-use round may carry the accumulated conversation history, and a single task can trigger a dozen or more model requests.
Useful controls include:
- Context compression: Summarize earlier tool results, retaining conclusions and key fields.
- Tool-result trimming: Truncate lengthy logs and return structured summaries instead of raw payloads.
- Separate planning from execution: Use smaller models for planning and parameter filling, reserving larger models for critical reasoning.
- Early termination: Set maximum iteration counts and task budgets to prevent unproductive loops.
For agent applications, the unit of cost should be the completed task—not an individual API call.
6. Use Tiered Routing and Batch Processing
Routing requests by difficulty is one of the most effective architectural approaches to cost optimization.
Lightweight models or rule engines can handle intent detection, format conversion, field extraction, and simple questions. More capable models can handle complex reasoning, long-form writing, and code refactoring.
The routing layer can use a lightweight classifier or rule matching. Keep operator-configurable controls for staged rollouts so routing changes can be introduced gradually.
For offline workloads, prioritize asynchronous batch APIs and queue-based processing to smooth peak demand. For online workloads, streaming can improve perceived responsiveness, while elastic scaling on a container platform can help control infrastructure costs.
7. Make Costs Observable and Governable
Optimization requires measurement. A practical minimum feedback loop includes four elements:
- End-to-end instrumentation: Record input and output token counts, cache usage, model identifiers, and business tags for every call.
- Separate logs from metrics: Store detailed records in a logging service for investigation. Send aggregated metrics to monitoring and alerting systems for trend analysis and budget alerts.
- Cost attribution: Tag usage by business line, tenant, and endpoint to identify the largest sources of spending.
- Regular regression testing: Use a fixed evaluation set to compare quality and cost across configurations, ensuring that savings do not come at the expense of acceptable results.
This makes it possible to connect billing changes to specific workloads and verify whether an optimization actually improves task-level economics.
8. Common Mistakes
Avoid these recurring pitfalls:
- Comparing token prices without accounting for task-level cost, cache reuse, and output length.
- Placing frequently changing information inside a supposedly fixed prefix, undermining cache reuse and making prompt structure harder to manage.
- Allowing unlimited retries without budget cutoffs, causing spending to escalate during failures.
- Sending every request to the most capable model without tiered routing or fallback strategies.
9. Conclusion
As model capabilities converge, cost engineering is becoming a core requirement for production LLM applications.
Five steps provide a practical foundation:
- Understand the billing model.
- Improve cache reuse.
- Control output length.
- Route requests by difficulty.
- Implement measurement and budget alerts.
Together, these measures can often deliver several-fold cost improvements while keeping task quality broadly unchanged.
For organizations building this capability in a managed environment, the source architecture can be implemented using general-purpose cloud components such as object storage, message queues, container platforms, logging, monitoring, and alerting. Baidu AI Cloud is one platform referenced for this approach; service availability should be checked for the intended deployment region. The architecture does not require coupling to a particular model API.
