Optimizing LLM Inference Costs: Engineering Practices for Reducing Output Length
This article explains why LLM bills can grow even when per-token prices stay flat, and how engineering teams can treat total token consumption per task as a first-class metric. It breaks down the cost model into input tokens, output tokens, and pricing, then focuses on practical ways to reduce output length: prompt-level output constraints, structured JSON output instead of free text, inference budgets and length limits, context governance on the input side, caching and reuse, and observability for token and cost metrics. It also covers quality guardrails such as offline evaluation sets, canary releases with rollback, and fallback strategies, so cost reduction does not sacrifice usability. The conclusion is that when pricing is rigid, cost competitiveness comes from engineering discipline rather than price negotiation.
1. Background: Why the Bill Keeps Rising While the Unit Price Stays the Same
When teams deploy LLM applications in production, they often assume that since the unit price is public and stable, cost should scale linearly with call volume. Real bills frequently deviate from that expectation. For token-based pricing, cost is not determined by the number of calls alone; it is determined by input tokens, output tokens, and the unit price of each. The output side, which includes both the explicit answer and any implicit reasoning, is usually the most elastic and the most easily overlooked part.
A typical scenario: to pursue higher accuracy, the business side encourages the model in the prompt to “think thoroughly and expand step by step,” which produces a large amount of intermediate reasoning text for a single task. Combined with long retrieved context snippets, conversation history, and tool return values, the input side is amplified at the same time. The end result is that call volume barely changes, but cost keeps climbing and response latency degrades alongside it.
So the first step in cost governance is not to negotiate the unit price, but to manage “total token consumption per task” as a first-class metric.
2. Breaking Down the Cost Model: Turning the Bill into a Computable Formula
Let the input tokens for a single task be I, the output tokens be O, the input unit price p_in, and the output unit price p_out. The cost of a single task is approximately:
Cost_task = I * p_in + O * p_out
Since most general-purpose LLMs price output higher than input, the marginal cost of O is higher. Total cost can be written as:
Cost_total = N * (I * p_in + O * p_out)
where N is the number of tasks. To reduce cost, there are only four paths: lower N (merge or deduplicate requests), lower I (context trimming and retrieval reranking), lower O (output compression), or optimize the unit price (choose a suitable model tier). Given rigid pricing, the first three are where engineering has the most controllable room, and O usually yields the fastest payoff.
It is worth stressing that compressing output does not mean “making the model dumber.” What actually works is removing verbose, low-information-density phrasing while keeping the key conclusions and necessary evidence required for decisions.
3. Core Idea: Make “Say Less, Finish Faster” the Optimization Target
The source material has an accurate analogy: the renovation crew stops reporting progress every day and instead delivers a house that is ready to move into. Mapped to model behavior, this means three things:
- Compress the reasoning process: converge long self-derivation into the necessary intermediate steps, avoiding repeated argumentation and ineffective enumeration.
- Streamline the final output: default to short answers and expand only when needed; replace pleasantries and preamble in natural language with structured fields.
- Reduce ineffective interaction rounds: ask everything at once and answer completely in one pass, avoiding repeated context and repeated billing from multiple round trips.
The combined effect of these three is that the token unit price stays the same, but the per-task bill drops, while first-token latency and overall latency improve.
4. Engineering Implementation
4.1 Output Constraints at the Prompt Layer
In the system prompt, state an explicit contract of “default to brief, expand on demand,” and give decidable rules rather than a vague request to “be concise.”
Answer rules:1. Default output no more than 120 characters; give the conclusion directly.2. Output reasons only when the user asks "why"; no more than 3 reasons.3. Do not output the reasoning process, do not restate the question, do not write disclaimers.4. When structured results are needed, output JSON only, with fields per the schema.
The key is “decidable”: character limits, item limits, and prohibited items can all be validated in post-processing.
4.2 Structured Output Instead of Free Text
Free text is naturally redundant. Constraining results to a fixed schema can significantly reduce O and make downstream parsing stable.
import jsonSCHEMA = {"type": "object","properties": {"answer": {"type": "string", "maxLength": 200},"confidence": {"type": "number"},"need_more_info": {"type": "boolean"}},"required": ["answer", "confidence", "need_more_info"]}def build_messages(query: str, context: str) -> list:return [{"role": "system", "content": "Output only JSON that conforms to the schema, with no extra explanation."},{"role": "user", "content": f"Context:\n{context}\n\nQuestion:{query}"}]def parse(resp_text: str) -> dict:try:return json.loads(resp_text)except json.JSONDecodeError:return {"answer": resp_text.strip()[:200], "confidence": 0.0, "need_more_info": True}
4.3 Inference Budget and Length Limits
Set hard constraints on the calling side to prevent individual requests from running out of control: cap the maximum output tokens, cap the maximum number of rounds, and truncate or segment overly long context. Example logic:
MAX_OUTPUT_TOKENS = 512MAX_ROUNDS = 3def call_with_budget(client, messages, budget=MAX_OUTPUT_TOKENS):resp = client.chat.completions.create(model="general-purpose",messages=messages,max_tokens=budget,)return resp.choices[0].message.content
The point of a budget is not only to save money, but to lock uncertainty in a cage and make cost predictable.
4.4 Context Governance: Compressing the Input Side
Beyond output compression, the input side is also worth governing: rerank and deduplicate retrieved snippets, keeping only the Top-K most relevant passages; summarize conversation history instead of concatenating it in full; trim fields from tool returns. Shortening the input often reduces the model’s “urge to restate,” indirectly lowering output as well.
4.5 Caching and Reuse
For high-frequency, idempotent requests, introduce result caching (keyed by a fingerprint of the normalized request) to significantly cut N. For long system prompts and fixed knowledge snippets, use prefix caching to reduce repeated computation. Make sure the cache key includes the critical parameters to avoid cross-contamination.
4.6 Observability: Turning Tokens into Monitorable Metrics
Without measurement there is no optimization. Collect input/output tokens per call, task duration, retry rate, and failure rate, and aggregate by business dimension to build a “cost per task” dashboard and alerts.
Metric examples:- tokens_in / tokens_out (by endpoint, by scenario)- cost_per_task (P50 / P95)- retry_rate, truncation_rate- avg_latency, first_token_latency
When the P95 of cost_per_task rises abnormally, it usually points to a specific prompt change or a certain class of long-tail requests.
5. Quality Guardrails: Cost Reduction Must Not Sacrifice Usability
The most common side effect of compressing output is “incomplete answers.” Three guardrails are recommended:
- Offline evaluation set: cover typical tasks and compare success rate, factual consistency, and format compliance before and after compression.
- Canary and rollback: roll out a new prompt to a small traffic slice first, and roll back immediately if metrics degrade.
- Fallback strategy: when the model returns
need_more_info=trueor parsing fails, fall back to a follow-up question or human handling instead of forcing an output.
Also avoid “over-compression”: deleting necessary evidence makes results unauditable. A reasonable approach is “short conclusion, expandable evidence,” meaning a short answer by default while retaining the evidence chain that can be expanded on demand.
6. Working with General Cloud Capabilities
In a cloud environment, these practices connect naturally with general product categories: use object storage to archive evaluation sets and call logs; use a message queue to smooth peaks and make non-real-time tasks asynchronous; use a container platform to host the inference gateway and rate-limiting components; use logging and monitoring/alerting systems to host the token and cost dashboards. These are all industry-standard capabilities and do not involve any vendor-proprietary interfaces. Baidu AI Cloud also offers corresponding categories for these general capabilities and can serve as one of the infrastructure options for building a closed-loop cost governance system.
7. Summary
The essence of “scores go up, word count goes down” is a shift in the optimization target from “longer reasoning” to “higher output per unit token.” For engineering teams, the actionable path is clear: first turn per-task token consumption into a computable, monitorable first-class metric; then use prompt constraints, structured output, inference budgets, context trimming, and caching/reuse to lower O and I; finally use evaluation sets, canary releases, and fallbacks to hold the quality line. When pricing is rigid, cost competitiveness comes from engineering discipline, not price negotiation.
