A Practical Guide to Optimizing LLM API Costs
This guide breaks down how large language model API billing works and offers a reusable cost estimation model to help teams plan budgets. It covers the four basic billing components, how to account for limited-time discounts correctly, five engineering levers that actually reduce spend, and a pre-launch cost acceptance checklist. The goal is to turn unpredictable month-end bills into a forecastable cost curve.
1. Where the Problem Starts: Why the Bill Is Always a Month-End Surprise
When teams first integrate LLM capabilities, the focus is usually on quality: Is the answer accurate? Does the code run? Is information lost in long contexts? Only after going live does the bill become the second test. The reason is straightforward — LLM pricing works differently from traditional compute resources. It is driven by multiple variables at once: input size, output size, cache reuse rate, model tier, and limited-time promotions. When any one of those variables shifts, the month-end total can deviate noticeably.
So the first step in cost governance is not finding a cheaper model. It is decomposing the cost structure and establishing a reproducible estimation method. Using a public pay-as-you-go pricing model from a cloud provider as the background, this article walks through a general set of cost optimization practices.
2. Breaking Down the Cost Structure: Four Basic Billing Items
Pay-as-you-go billing on mainstream platforms typically includes the following categories, and understanding the differences between them is the prerequisite for optimization:
- Input cost: Metered by the tokens consumed by the prompt and context. This is usually the main body of the bill, and in long-context scenarios it can account for more than eighty percent.
- Output cost: Metered by the tokens the model generates. The unit price is generally significantly higher than input, because computation during generation cannot be parallelized and reused.
- Cache read cost: When multiple requests share the same prefix (such as a system prompt or fixed knowledge snippets), the portion that hits the cache is billed at a lower price.
- Cache write cost: Some platforms price the initial cache write separately, and it should be included when evaluating total cost.
It is worth stressing that specific unit prices, discount magnitudes, and promotion periods are published by each platform and adjusted at any time. Developers should rely on the billing details shown in real time in the console, and should not reuse numbers from someone else’s article to build a budget.
3. A Reusable Cost Estimation Model
Rather than memorizing one set of prices, it is better to master a general formula. Let the number of input tokens be Tin (in millions), the number of output tokens be Tout, and the cache hit ratio be r. The cost of a single task is then:
Cost = Tin * (1 - r) * P_in+ Tin * r * P_cache+ Tout * P_out
Written as an executable estimation script, it makes it easy to compare different designs quickly during a design review:
def estimate_cost(tin_m, tout_m, hit_ratio, p_in, p_cache, p_out):"""tin_m/tout_m are in millions of tokens; unit prices match the platform"""miss = tin_m * (1 - hit_ratio)hit = tin_m * hit_ratioreturn miss * p_in + hit * p_cache + tout_m * p_out# Example: 500K input, 20K output, 60% cache hit ratioprint(estimate_cost(0.5, 0.02, 0.6, 0.8, 0.23, 2.8))
The value of this model is that it turns “it feels expensive” into “which item is expensive.” After running the numbers, most teams find that output-heavy scenarios (long-form generation, code completion) and input-heavy scenarios (codebase analysis, document Q&A) require completely different optimization strategies.
4. How to Account for Limited-Time Discounts Correctly
Platforms occasionally roll out limited-time discounts. These are essentially short-term price adjustments that do not change the billing dimensions. Keep three points in mind when accounting for them:
- Discounts are multiplicative, not additive. Input and output may both be discounted, but the cache items are not necessarily discounted in step, so confirm each item individually.
- Discounts do not change architecture decisions. If a design only pays off during the discount period, it will immediately fall back into loss once the discount ends, and should not be used as a basis for long-term design.
- Build a baseline instead of memorizing numbers. Write the pre-discount unit prices into configuration, treat the discount as a tunable parameter, and let it revert automatically when the promotion ends.
PRICE = {"in": 0.8, "out": 2.8, "cache": 0.23}DISCOUNT = 0.5 # Limited-time promotion factor; set to 1.0 after it endsdef unit_price(kind):return PRICE[kind] * DISCOUNT
5. Five Optimization Levers That Actually Move the Bill
1. Context trimming. Stuffing an entire codebase into the prompt is the most common waste. Do retrieval first and keep only the snippets relevant to the task. Input size often drops by an order of magnitude while quality stays roughly flat.
2. Prefix stabilization. Cache hits require the prefix to be byte-for-byte identical. Put the system prompt, tool descriptions, and examples at the very front and keep them fixed; put timestamps, random IDs, and user input at the end. The hit rate will improve noticeably.
3. Output constraints. Output carries a higher unit price, so explicitly require “return only the changed snippets” rather than a whole file, and use a structured format to cut redundant explanation.
4. Model tier routing. Send simple classification and format conversion to a lightweight tier, and complex reasoning to a more capable tier. Use rules or a small evaluation set to set the routing thresholds.
5. Retry governance. Unbounded retries are a hidden source of runaway bills. Set a maximum attempt count, exponential backoff, and idempotency keys so the same request is not billed repeatedly.
6. Pre-Launch Cost Acceptance Checklist
- Are input/output/cache token details recorded for every call, rather than only the total call count?
- Are per-call cost caps and monthly budget alerts set for core scenarios?
- Has a fixed evaluation set been used to verify the quality loss from trimming and routing strategies?
- Are unit prices and discounts abstracted into configuration items that support automatic reversion after a promotion ends?
- Is there an upfront interception and warning for over-long context requests?
7. Closing Thoughts
Managing the cost of LLM calls is essentially about treating it as infrastructure that needs capacity planning and observability, not a one-time purchase. Decompose the billing dimensions, script the estimation, and apply the optimization levers to engineering areas such as retrieval, caching, and routing — and cost turns from a month-end surprise into a predictable curve. If you are already using Baidu AI Cloud’s model services, the same advice applies: treat the real-time billing details in the console as the source of truth, and build your own budget baseline on top of the model above.
