How to Control Large Language Model Costs Without Sacrificing Quality
A practical guide to reducing LLM costs through measurable quality gates, token usage analysis, complexity-based routing, fallback strategies, prompt optimization, structured outputs, caching, and ongoing monitoring. It includes implementation examples and a pre-launch cost and quality checklist.
1. Define What “Good Enough” Means First
Before reducing costs, the team must clearly define what “acceptable quality” means. Without a measurable definition, cost reduction can easily become quality degradation—and the issue may not be discovered until users start complaining.
Common acceptance metrics fall into three categories:
- Format pass rate: Whether the model output can be correctly parsed by a program. For tasks that require JSON, this can be checked directly with a parser.
- Field completeness rate: Whether all required fields are present and non-empty.
- Sample accuracy rate: The percentage of correct items found through random manual review. This metric is the most expensive to measure, but it can reveal errors that the first two metrics miss—for example, when a field exists but contains an incorrect value.
Choose one or two metrics for each task. The following thresholds are starting points; actual values should be calibrated against business risk and historical data.
| Metric | Calculation | Example starting threshold | Suitable scenarios |
|---|---|---|---|
| Format pass rate | Parseable outputs / total outputs | At least 99% | All structured outputs |
| Field completeness rate | Outputs with all required fields / total outputs | At least 98% | Multi-field extraction |
| Sample accuracy rate | Correct sampled items / total sampled items | Defined by the business team | Amounts and compliance-related content |
These values are examples, not commitments for any model or platform. During calibration, use manual review records from the previous month to calculate the actual pass rate of the current solution, then set the threshold slightly below that baseline. If the current solution already fails to meet the required quality level, fix the quality problem before attempting to reduce costs.
The following pseudocode calculates pass rates:
def pass_rate(results: list[dict], required_fields: list[str]) -> dict:total = len(results)parsed = 0complete = 0for r in results:data = r.get("parsed") # None when parsing failsif data is None:continueparsed += 1if all(data.get(f) not in (None, "") for f in required_fields):complete += 1return {"format_pass_rate": parsed / total if total else 0.0,"field_complete_rate": complete / total if total else 0.0,}
For manual reviews, use a fixed sample size each time and record the results in a table for later comparison. A review template can include the following columns: sample ID, task type, model used, model version, reviewer, correctness, error type, and notes.
2. Understand and Measure Differences in Token Usage
Cost differences mainly come from three sources.
Tokenizers
Different models tokenize the same text differently. Some models split Chinese text, punctuation, and special characters into smaller units, causing the same content to consume more tokens.
Repeated Context Submission
In a multi-turn conversation, the client usually sends the conversation history with every request. That history counts toward input tokens. As the conversation grows, the input cost of each turn increases.
Redundant Output
Some models add explanatory text before or after the result, such as “Sure, here is the table you requested.” If the business system only needs the core data, this extra text creates unnecessary cost.
Public comparison tests show that token usage can vary significantly between models. However, such tests often do not fully disclose the sample size, model versions, or measurement methodology. They can indicate a general direction, but should not be used directly as the basis for budgeting. Teams should measure their own workloads.
For measurement, prepare a representative set of fixed inputs, run them on each candidate model, and read the input and output token counts from the usage fields returned by the API. Do not look only at the price of an individual call. Instead, measure cost per successful task:
Cost per successful task = Total cost / Number of tasks that passed acceptance checks
This metric includes the cost of failed retries and manual rework. A model with a lower per-call price but a low pass rate may ultimately cost more than a more expensive but stable model.
Billing rules also differ across platforms. For example, platforms may use different prices for input and output tokens, offer discounts for cache hits, or use different measurement units. Always consult the latest official documentation for each platform and reconcile the calculated costs against actual invoices.
3. Route Tasks by Complexity and Design Fallbacks
Sending every task to the same large model is usually the most expensive approach. A better strategy is to assess task difficulty first and then select an appropriate model. This mechanism is commonly called a routing gateway.
A practical three-level classification is:
- L1: Clearly defined tasks such as format conversion and simple field extraction.
- L2: Multi-field structured extraction and tasks that require basic reasoning.
- L3: Complex reasoning, long-document analysis, or high-risk content.
Model mappings should be stored in a configuration file rather than hard-coded. This allows the team to change models by updating configuration only. The model names below are placeholders.
The routing gateway has two core responsibilities:
- Try a smaller model first and evaluate the result with an acceptance function.
- Escalate to a stronger model when validation fails, while limiting the number of upgrades.
import jsonROUTES = {"L1": "small-model", # Replace with an actual model identifier"L2": "medium-model","L3": "large-model",}UPGRADE = {"L1": "L2", "L2": "L3", "L3": None}MAX_HOPS = 2def grade_task(task: dict) -> str:if task.get("risk") == "high" or task.get("doc_chars", 0) > 20000:return "L3"if task.get("needs_reasoning") or task.get("fields_required", 0) > 5:return "L2"return "L1"def validate(output: str, required_fields: list[str]) -> bool:try:data = json.loads(output)except json.JSONDecodeError:return Falsereturn all(data.get(f) not in (None, "") for f in required_fields)def call_model(model: str, prompt: str) -> str:raise NotImplementedError # Connect your SDK heredef run_task(task: dict, prompt: str, required_fields: list[str]) -> dict:level = grade_task(task)for _ in range(MAX_HOPS + 1):output = call_model(ROUTES[level], prompt)if validate(output, required_fields):return {"level": level, "output": output, "status": "ok"}level = UPGRADE[level]if level is None:breakreturn {"level": None, "output": None, "status": "needs_human"}
Several points require attention:
- High-risk tasks should not be automatically downgraded. The
grade_taskfunction above assigns them directly to L3, but a safer design is to provide a manual review channel for these tasks. - The number of fallback attempts must be limited. Otherwise, one failure may trigger multiple expensive calls and increase total costs.
- Routing rules should not be based on intuition alone. Adjust the classification criteria regularly using the pass rates and costs recorded in logs.
- If a model service begins returning a large number of errors, the gateway should stop routing traffic to it and switch to a backup model. This practice is known as a circuit breaker. The threshold and recovery conditions should be based on the team’s own error-rate baseline.
4. Three Cost-Reduction Techniques: Prompt Optimization, Output Constraints, and Caching
In addition to routing, three common cost-reduction techniques are prompt optimization, output constraints, and caching. Each should be used together with acceptance metrics, and the test set should be rerun after every change.
1. Optimize Prompts
The longer the prompt, the more input tokens each call consumes. A practical optimization process is:
- Identify repeated content, such as role definitions, format instructions, and prohibitions that are included in every request.
- Move stable instructions into the system prompt and keep their position stable in the request so that prefix caching can work effectively where supported.
- Keep few-shot examples only when they are genuinely needed, and limit them to one or two examples.
- After each change, compare the format pass rate and sample accuracy rate on the test set. Revert the change if the metrics decline.
2. Constrain the Output Format
The purpose of output constraints is to remove unnecessary explanations and make the result directly parseable by software.
Recommended practices include:
- Require the model to return only JSON in the specified structure.
- Use structured output or JSON mode when supported by the platform.
- Instruct the model not to include greetings or explanations.
When setting max_tokens, use the 95th percentile of historical output length as a reference and leave some additional room. Setting the limit too low may truncate the output and cause parsing failures. Check the response’s finish reason. If the output was truncated because of the length limit, record it as a failure and send it through the fallback process.
def is_truncated(response: dict) -> bool:# Field names vary by platform; update this according to the relevant documentationreturn response.get("finish_reason") == "length"
3. Reuse Cached Results
Caching generally falls into two categories and should be handled separately.
Application-Level Caching
For requests with exactly identical inputs, the application can return the previous result directly. The cache key should include the tenant, model version, and prompt version. This prevents data from being mixed between tenants and avoids returning an outdated result after a model upgrade.
import hashlibimport jsondef cache_key(tenant_id: str, model: str, prompt_version: str, payload: dict) -> str:body = json.dumps(payload, ensure_ascii=False, sort_keys=True)digest = hashlib.sha256(body.encode("utf-8")).hexdigest()return f"{tenant_id}:{model}:{prompt_version}:{digest}"
Platform-Provided Prefix Caching
Platform prefix caching applies to repeated long prefixes, and the billing rules vary by platform. Whether it is available and how much of a discount it provides must be confirmed in the official documentation and verified against actual invoices.
Several cache boundaries should be explicit:
- Caches must have an expiration time. When business data changes, old results should become invalid.
- When the prompt or model version changes, invalidate the cache as a whole.
- Requests containing personal data, identity information, or other sensitive data should not be cached by default. If caching is necessary, store the data in encrypted form and follow the applicable data-retention policy.
- Large language model output may be nondeterministic. Caching guarantees only that a previously accepted result is returned; it does not guarantee that every generation would be identical.
5. Monitoring and Risk Management
After deployment, the team should continuously monitor several metrics.
Quality metrics include format pass rate, field completeness rate, and sample accuracy rate.
Cost metrics include cost per successful task, average input tokens, and average output tokens.
Operational metrics include fallback ratio, cache hit rate, and 95th-percentile latency.
Every metric should be compared with the pre-launch baseline. The team should set thresholds based on its own baseline. If quality metrics decline significantly, roll back the routing configuration first and investigate the cause afterward. It is recommended to place routing configuration and prompt versions behind feature flags so that a rollback only requires switching a flag rather than redeploying the application.
Common risks include:
- Overly broad acceptance rules may hide real differences between models. All metrics may appear to pass while the actual production experience deteriorates.
- Incorrect routing may send complex tasks to a small model, increasing the number of fallbacks and ultimately raising total costs.
- Cache contamination may cause an incorrect result to be returned repeatedly.
- Model or prompt upgrades may change output behavior, requiring the test set to be rerun.
- Platform billing rules and prices may change, so the cost model must be updated regularly.
6. Pre-Launch Cost and Quality Checklist
Before launch, verify each of the following:
- Acceptance metrics and thresholds have been calibrated against historical data, and the data source and date have been recorded.
- The test set covers common tasks and edge cases, with the sample size documented.
- Input tokens, output tokens, and cost per successful task have been measured for every candidate model.
- The number of fallback attempts is limited, and high-risk tasks have a manual review channel.
- The cache key includes the tenant, model version…
