LLM Cost Optimization: Token Reduction Practices for the Same Task
When multiple candidate models pass the quality bar on the same task, cost differences come from how the work is done, not whether it can be done. This article breaks the LLM bill into input, output, retry, and hidden costs, then walks through five practical optimization levers: versioned prompt contracts, structured output with parsing contracts to eliminate retries, routing and tiered model selection, context slimming with caching, and batching, async execution, and budget governance. It closes with a four-step rollout path for measuring baselines and driving down token spend.
1. The Problem: Four Solutions Were All “Correct,” Yet the Bills Differed by Multiples
A common pattern shows up in real model selection evaluations. You hand the same requirements and the same input material to several candidate models and ask each one to produce a structured table file. When the results come back, every candidate satisfies field completeness, formatting rules, and business definitions. Judged purely on “did it solve the task,” there is no winner. But pull the usage bills side by side and the consumption gap is obvious: some solutions use only a small fraction of the quota that others burn.
This points to a fact that is easy to miss: once capability clears the passing line, cost differences no longer come from “can it do the work” but from “how it does the work.” For the same task, a model can multiply cost several times over by taking a longer reasoning path, producing more verbose output, retrying more often, or packing more into the context. For engineering teams, selection cannot rely on quality leaderboards alone. Cost per unit of work has to be a first-class metric in the evaluation system.
2. Where the Money Actually Goes: Breaking the Bill into Optimizable Parts
LLM billing is usually tied to input tokens, output tokens, and the number of calls. Unit prices and tiered pricing differ across vendors, but the cost structure breaks down into four parts:
- Input side: system prompts, conversation history, retrieved reference material, and tool return values all count as input.
- Output side: the final answer, the reasoning trace, and the portion regenerated after truncation all count as output, and output is typically priced higher than input.
- Call side: failed retries, reruns caused by non-compliant formatting, and rework driven by human dissatisfaction all multiply the total cost.
- Hidden side: queueing, timeout retries, and rate-limit backoff bring duplicate billing plus engineering time.
A common mistake is compressing only the input while ignoring output and retries. In practice, output redundancy and retries are often the largest source of waste. A few hundred extra words of explanation from the model, or an extra block of wrapper text that the parser discards, and the cost goes straight up.
3. Optimization 1: Turn the Prompt into a Versionable Contract
A prompt is not a casual piece of text. It is an engineering asset as important as code. Put it under version control and organize it in six sections: role, task, constraints, input, output format, and failure handling. State the boundaries explicitly:
[Role] You are a data processing assistant. Output structured results only.[Task] Generate a summary table from the given line items.[Constraints] No explanations, no pleasantries, no repeating the input; fill missing fields with null.[Input] {{payload}}[Output] Strictly output JSON with fixed keys rows/total/currency.[Failure] If the input is insufficient, output {"error":"insufficient_data"}.
This yields three benefits. First, regression testing: prompt changes can run through test cases like code. Second, measurability: every change can be compared on token consumption and pass rate. Third, reuse: different business lines share the same constraint templates, cutting the hidden cost of repeated trial and error.
4. Optimization 2: Eliminate Retries with Structured Output and a Parsing Contract
A large amount of quota goes to “the format was wrong, do it again.” A more reliable approach is to constrain output to a machine-parseable structure and enforce strong validation on the server side:
- Prefer constrained structured output capabilities so the model generates within a limited grammar space, which naturally cuts filler;
- Give a minimal example in the prompt (one positive example is enough), which works better than long prose descriptions;
- Apply a “repair once” policy on the server: when parsing fails, send back only the error location and the expected format instead of resending the whole thing;
- Set a maximum retry count and a fallback path; once exceeded, hand off to a human or fall back to a template.
import json, redef parse_and_repair(raw: str, max_fix: int = 1):for _ in range(max_fix + 1):try:return json.loads(raw)except json.JSONDecodeError as e:raw = f"Line {e.lineno} of the previous output was invalid. Return only the corrected full JSON: {raw[:200]}"raise ValueError("structured_output_failed")
The key point: turn “retry” from blind resending into targeted repair with diagnostic information. This usually reduces wasted calls significantly.
5. Optimization 3: Auto Mode, Routing, and Tiered Calls
The so-called “auto mode” is essentially selecting a model tier dynamically based on task difficulty. On the engineering side, you can build a routing layer and classify requests:
| Task tier | Identifying signals | Suggested strategy |
|---|---|---|
| L1 simple | Extraction, formatting, short-text rewriting | Lightweight model + strong template |
| L2 medium | Multi-field aggregation, rule validation | Mid-tier model + structured output |
| L3 complex | Long-document reasoning, cross-table joins | High-tier model + step-by-step decomposition |
Routing decisions can rely on rules (length, field count, whether a table is present), on a small model doing classification, or on a lightweight model producing a draft first with confidence deciding whether to escalate. Model services on platforms such as Baidu AI Cloud typically include different tiers and automatic selection capabilities. What the engineering side needs to do is make “which one to pick” an observable, tunable policy rather than hard-coding a single model.
6. Optimization 4: Slim the Context and Reuse Caches
Input tokens are often inflated by context that gets “tossed in” casually. Actionable slimming techniques include:
- Retrieval snippet trimming: keep only the passages highly relevant to the question, truncating at sentence-level similarity instead of stuffing in the whole document;
- History summarization: rolling summaries for long conversations, keeping conclusions and dropping the process;
- Prefix caching: put the stable system prompt and knowledge snippets in a fixed prefix, and use cache hits to lower repeated input cost;
- Semantic caching: build a vector index for high-frequency similar requests, reuse the result on a hit, and call the model only for misses.
[Fixed prefix - cacheable] Role + output contract + field dictionary[Variable part - trimmed] Current input + retrieved TopK snippets (K=3~5)
One thing to stress: caches must have an invalidation policy and a version number, so that a prompt upgrade does not keep hitting stale results and cause the reverse accident of “cost went down, quality went wrong.”
7. Optimization 5: Batching, Async, and Budget Governance
- Batching: merge non-real-time tasks into a single submission, which usually gets better throughput and unit price;
- Async: put generation tasks into a message queue and pair it with elastic scaling on a container platform to smooth peaks and fill valleys;
- Budget governance: set token quotas and alert thresholds per business line, and automatically downgrade to a lightweight model when the limit is exceeded;
- Observability: push input tokens, output tokens, retry counts, and cache hit rate to logging services and monitoring alerts to form a cost dashboard.
A simplified quota control sketch:
class Budget:def __init__(self, limit): self.limit, self.used = limit, 0def allow(self, cost):if self.used + cost > self.limit: return Falseself.used += cost; return True
8. Rollout Path: Four Steps to Bring Quota Down
- Baseline measurement: fix an evaluation set and record each solution’s pass rate, average input/output tokens, and retry rate;
- Single-point optimization: start with output constraints and structured parsing, which usually pays off fastest;
- Strategy optimization: roll out routing and auto mode, assigning tiers by difficulty;
- System optimization: run caching, batching, quota alerts, and the cost dashboard as standard practice.
9. Conclusion
“Spending 80% less quota on the same work” is not a proprietary feature of any single model. It is the combined result of prompt contractization, structured output, tiered calls, context slimming, and cache and budget governance. When several candidate solutions all meet the quality bar, real competitiveness shifts to cost per unit of work and stability. Treating cost as an observable, regression-testable, governable engineering metric is what makes a long-term balance between quality and the bill possible.
