A Practical Guide to LLM API Cost Optimization: Focus on Cost Per Task, Not Token Price
This article explains why cost per task matters more than per-token pricing when optimizing LLM API spend. It breaks down the three billing tiers—input, output, and cache-hit tokens—shows how prompt caching and multi-turn tool calls affect total cost, and presents four practical techniques: stabilizing the prompt prefix, slimming context, controlling output length, and tiered model routing. It also covers cost observability metrics and model selection testing to help engineering teams reduce expenses in a reproducible way.
1. Why Cost Per Task Matters More Than Price Per Token
In real engineering work, teams often compare models by the price per million tokens. However, what actually drives the bill is the total number of tokens consumed to complete a single business task. A model with a low unit price can end up costing several times more per task if it produces verbose reasoning, triggers frequent retries, or repeatedly resends context. A more practical approach is to push cost measurement down to the task level: define the input context length, output length, number of turns, and retry policy for each task, calculate the cost of a single run, and then multiply by the daily call volume to estimate a budget range.
Public technical disclosures offer a useful example. A lightweight inference model released by a cloud provider topped the call rankings on a model aggregation and routing platform on its first day. Its reported cost per task was about RMB 0.26—roughly 1/13 of the preview version in the same series, 1/20 of the standard version, and 1/8 of another model in a higher-load tier. The real takeaway is not the specific numbers but the derivation: the cost advantage comes from combining a low unit price, a short request chain, and high cache reuse—not from a price cut in a single dimension.
2. Breaking Down the Billing Model: Input, Output, and Cache Tiers
Standard usage-based billing typically has three components:
- Input tokens: system prompts, conversation history, retrieved knowledge snippets, and the user question.
- Output tokens: content generated by the model, usually priced higher than input.
- Cache-hit tokens: when a request prefix exactly matches a recent request, the already-computed intermediate results can be reused at a significantly lower price than regular input.
A simplified formula:
Cost per call = input_tokens/1e6 * P_in+ cache_hit_tokens/1e6 * P_cache+ output_tokens/1e6 * P_outCost per task = sum(cost of each turn) + retry cost
Using publicly disclosed tiers as an example—input at about RMB 0.5 per million tokens, output at about RMB 2 per million tokens, and cache hits at about RMB 0.02 per million tokens—consider a typical task: 6,000 input tokens (4,800 of them cache hits) and 800 output tokens. The cost is roughly 0.003 + 0.000096 + 0.0016 ≈ RMB 0.0047. If the task involves multiple tool-calling turns plus one retry, accumulating to the RMB 0.26 range is entirely possible. This shows that the focus of cost optimization should be reducing the number of turns and improving the cache hit rate.
3. Four Optimization Techniques You Can Apply Immediately
- Keep the prefix stable to maximize cache benefits. Place the system prompt, tool definitions, and a few examples at the very front of the request and keep them byte-for-byte identical. Move timestamps, random IDs, and user-specific information to the end. Any change to the prefix invalidates the cache.
- Slim down the context. Apply rolling summaries to conversation history, and rerank and truncate retrieval results to keep only snippets relevant to the current question. Avoid stuffing an entire document into every turn.
- Control output length. Specify the output structure explicitly (for example, JSON fields and a maximum item count), and cut unnecessary pleasantries and repeated explanations. Since output tokens cost more, reducing them yields direct savings.
- Use tiered routing. Route high-frequency, simple tasks such as classification, extraction, and rewriting to a lightweight model, and escalate to a stronger model only for complex reasoning. Set timeout and retry limits to prevent long-tail requests from inflating the average.
def build_messages(system, history, docs, query):# Fixed prefix improves cache hit rateprefix = {"role": "system", "content": system}ctx = summarize(history, max_tokens=1500) # Compress historyctx += rerank_and_truncate(docs, top_k=5) # Trim retrieval resultsreturn [prefix, {"role": "user", "content": ctx + "\n" + query}]
4. Cost Observability: Turning the Bill into Actionable Metrics
Instrument the client-side call layer to log input, output, and cache-hit token counts, the model tier, latency, and whether a retry occurred for every request. Aggregate these by business scenario into three core metrics—cost per task, cache hit rate, and average number of turns—and feed them into monitoring, alerting, and logging services to build trend dashboards. Alerting when the cache hit rate drops or the average turn count rises is often more effective than reviewing the bill at month-end.
5. Model Selection and Load Testing Recommendations
Do not look only at unit price or leaderboard rankings. Build an evaluation set from real business samples and weigh task success rate, latency, and cost per task together in a three-way tradeoff. Run a small-traffic canary for candidate models and check whether the cache hit rate and retry rate meet expectations. If you use model services from Baidu AI Cloud, the same recommendation applies: adopt task-level cost accounting and canary rollout as your launch criteria.
6. Conclusion
Low cost is fundamentally an engineering problem: stabilize the prefix to improve cache reuse, trim context and output, route by task difficulty, and make cost observable and testable at the task level. Build these practices into your call layer, and a tenfold cost reduction becomes a reproducible result rather than a one-time promotional windfall.
