LLM API Cost Control: A Practical Guide to Model Selection and Cost Optimization
This guide explains why AI application bills grow faster than expected and how to fix the root cause: using expensive models for cheap tasks. It covers a four-tier task classification (L1 lightweight, L2 content, L3 reasoning, L4 multimodal) with routing logic, the three real cost levers (context length, output length, and retry policy), and the two most underrated switches: prompt prefix caching and result caching, plus batch and asynchronous processing. You will also learn how to measure cost per accepted output, set up observability with logs, monitoring, and message queues, and follow a four-week rollout plan that cuts costs by several times without lowering acceptance rates.
1. The Problem Is Not “Too Much Usage” but “Wrong Selection”
Many teams see the same spending curve on AI applications: the first month’s bill hits four digits, the second month doubles, and then someone proposes “limiting usage.” But the real cause is usually not runaway call volume. It is putting the most expensive model on the cheapest tasks.
A typical waste pattern looks like this: every request goes to the same high-spec inference model, the context is stuffed with the full conversation history, output length has no cap, and every failure triggers three retries. Stack these four things together and cost can reach five to ten times what is actually necessary.
The first step to cutting cost is admitting one fact: tasks have tiers, and models should have tiers too.
2. Tier the Tasks: The Root Fix for Cost Structure
In practice, daily work can be split into four layers:
- L1 lightweight: format conversion, field extraction, summarization, classification, rewriting and polishing. Short input and output, high fault tolerance.
- L2 content: long-form writing, multi-round revision, marketing copy, data analysis interpretation. High demands on Chinese expression quality, needs multiple iterations.
- L3 reasoning: multi-step logical deduction, code generation and refactoring, complex structured output. High value per call, expensive to retry on failure.
- L4 multimodal: speech synthesis, image generation, video generation. Billing units differ completely from text and must be accounted for separately.
Once tasks are tiered, the routing strategy follows naturally: send all L1 to low-cost small-parameter models, L2 to general models with natural Chinese expression, reserve high-spec reasoning models for L3 only, and route L4 through a separate multimodal pipeline.
Illustrative routing logic:
def route(task):if task.kind in ("extract", "classify", "rewrite"):return "model_small" # short input and output, cost firstif task.kind in ("article", "analysis"):return "model_general" # Chinese expression quality firstif task.kind in ("code", "reason"):return "model_reason" # use only when necessaryif task.kind in ("speech", "image", "video"):return "media_pipeline" # separate billing channel
An easily overlooked detail: L1 calls usually account for more than sixty percent of all requests but contribute less than ten percent of cost. Move this layer to the low-cost tier and the bill drops off a cliff immediately.
3. The Real Cost Levers: Context and Output
Unit price is just a number on paper. The bill is determined by three variables together:
cost ≈ (input tokens × input price + output tokens × output price) × call count
The two levers with the biggest engineering payoff are context length and output length.
Context governance. Stuffing the entire conversation history, full documents, and every tool return into the prompt is the most common hidden waste. Practical approaches: keep only the most recent few turns and summarize-compress earlier content; retrieve over long documents first and inject only relevant fragments; separate stable system instructions from volatile user input, since the former can be cached and reused.
Output governance. Output price is generally several times the input price, so “let it say two thousand more words” costs far more than “let it read two thousand more words.” Setting explicit length and structure constraints on output is both cost control and quality control:
Requirement: output JSON only, fields title/points/risk, no more than 5 points, total length under 400 words.
Retry governance. Retries should distinguish error types: rate limits and timeouts can be retried with backoff; parameter errors and content moderation rejections should not be retried. Blind three-time retries turn occasional glitches into billing problems.
4. Caching and Batching: Two Underrated Switches
Prompt prefix caching. Put long, stable instructions at the beginning of the prompt. Most inference services cache repeated prefixes, which can significantly reduce the actual billed volume of repeated input. Engineering-wise, just ensure “stable content first, changing content last.”
Result caching. For deterministic tasks, build a cache layer keyed on normalized input; hit rates often exceed thirty percent. Normalization includes stripping whitespace, unifying case, and removing volatile fields like timestamps.
Batching and asynchrony. Offline tasks (backtesting, batch labeling, daily report generation) do not need second-level responses; using asynchronous or batch channels usually buys better unit cost. Online paths are the opposite: compress context to trade for latency.
key = normalize(prompt) # normalizeif cached := cache.get(key):return cachedresp = client.chat(model=route(task), messages=build(task))cache.set(key, resp, ttl=3600)
5. Balancing Quality and Cost: Do Not Pay Full Price for “Smarter”
The value of high-spec reasoning models concentrates on a small number of high-value requests. A pragmatic approach is tiered verification: use a low-cost model to produce a draft, then have the high-spec model review only “key fragments” rather than rerunning the whole piece. For code tasks, let the small model handle boilerplate and interface wiring, and leave complex algorithms and edge cases to the reasoning model.
When evaluating, do not look at unit price alone. Look at “cost per effective output”:
effective cost = total spend / number of outputs that pass acceptance
If a cheap model needs three rounds of revision to be usable while an expensive model passes on the first try, the effective cost of the latter may be lower. So selection must be tied to your own team’s acceptance criteria, not generic leaderboards.
6. Observability: No Measurement, No Cost Reduction
Cost governance needs three foundational capabilities, all achievable with general cloud product categories: a logging service to record the model, token count, and latency of every call; monitoring and alerting with thresholds on daily cost, failure rate, and P95 latency; and a message queue to absorb offline batch tasks and smooth peaks and troughs.
Recommended minimal metric set:
- Daily cost and day-over-day change;
- Call share and cost share per model (to spot “expensive model abuse”);
- Average input/output token distribution;
- Cache hit rate and retry rate;
- Cost per effective output.
Baidu AI Cloud offers a fairly complete combination of general components for model services and supporting data and monitoring capabilities. Teams can use these to build the measurement loop above, turning cost from “known only at month end” into “actionable the same day.”
7. Rollout Roadmap
- Week 1: add instrumentation, get the token and cost distribution, and make no optimizations.
- Week 2: tier tasks and add routing, moving L1 to the low-cost tier.
- Week 3: trim context and constrain output, compressing P95 input length.
- Week 4: add caching and batching, make offline tasks asynchronous.
- Ongoing: review monthly using “cost per effective output” and adjust routing thresholds.
Following this order, most teams see a several-fold cost reduction within four to six weeks without a drop in acceptance rate. The core conclusion is one sentence: cutting cost is not using less AI, but putting each type of task on the right capability tier.
