LLM Token Efficiency: Measuring, Compressing, and Optimizing in Practice
This article explains what token efficiency means for LLM applications and why it should be measured against task success rate, not token counts alone. It covers how tokenizers and pricing affect cost, then reviews practical ways to reduce input and output tokens, including prompt trimming, retrieval, history compression, caching, and model routing. It ends with metrics to track and steps for rolling out changes safely.
1. Why Token Efficiency Deserves Separate Attention
A token is the basic unit a model uses to process text. Models bill based on input and output token counts, inference latency grows with token count, and a model’s context length is also measured in tokens. As a result, completing the same feature with fewer tokens usually means lower cost, faster responses, and a more stable user experience.
Token efficiency can be defined as the total number of tokens consumed to complete one valid task. A “valid task” here means an output that passes quality checks. If saving tokens causes frequent errors and forces repeated retries, the actual cost goes up. Token efficiency must therefore be measured together with task success rate.
Online claims such as “Scheme X ranks first in token efficiency” often lack consistent test conditions. Results vary widely across tasks, models, and prompt structures. Teams should benchmark with their own business data instead of relying on published rankings.
2. Understanding How Tokens Are Counted
Before optimizing, you need to understand how tokens are calculated.
- Tokenizer differences: Different models use different tokenizers, so the same text can produce different token counts. English words are usually split into larger chunks, while Chinese text is often split by character or by word group. Symbols, code, and whitespace also consume tokens.
- Input and output are priced separately: Most services bill input and output tokens at different rates, and output is usually more expensive. Controlling output length often affects cost more directly than compressing input.
- Repeated counting in multi-turn conversations: Each request usually includes the conversation history. Without management, longer conversations send more input tokens on every turn, so cost grows cumulatively.
- Prefix reuse: Some platforms cache content that shares the same prefix, so repeated portions can be billed at a lower rate or processed faster. Placing stable system instructions at the start of a request improves the chance of a cache hit.
In engineering work, use the target model’s own tokenizer for exact counts, and wrap the counting logic in a standalone function. The example below is a rough estimate for quick checks only. It does not replace exact counting.
def estimate_tokens(text: str) -> int:"""Roughly estimate tokens: about 1 token per CJK character and about 1 token per 4 other characters."""cjk = sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")other = len(text) - cjkreturn cjk + (other + 3) // 4
3. Five Ways to Reduce Input Tokens
3.1 Trim the System Prompt
The system prompt repeats in every request. Even a few dozen extra tokens add up quickly when multiplied by the number of calls. When trimming, follow these principles:
- Remove repeated wording, and state each rule only once.
- Replace long paragraphs with short, structured sentences.
- Move rules that apply only to specific scenarios out of the base prompt, and inject them on demand.
After trimming, run the evaluation set to confirm that key constraints still hold.
3.2 Retrieve On Demand Instead of Including Everything
In knowledge-based Q&A applications, a common mistake is putting an entire document into the context. A better approach is to split the document into chunks, use vector or keyword search to find the passages most relevant to the question, and include only those passages in the prompt.
Chunk size involves a trade-off. Chunks that are too small lose context, and chunks that are too large waste tokens. Usually, you can split by heading level, keep each chunk within a few hundred tokens, and add a small overlap so key information is not cut off.
3.3 Compress Conversation History
Handle multi-turn history in layers:
- Keep the most recent turns verbatim to maintain coherence.
- Replace older content with summaries.
- Store the user’s preferences, constraints, and confirmed facts as structured state, and inject that state into every request.
The code below keeps as much recent conversation as a token budget allows.
from typing import List, Dictdef trim_history(messages: List[Dict[str, str]], budget: int) -> List[Dict[str, str]]:"""Walk backward from the newest message and keep as much history as the budget allows."""kept, used = [], 0for msg in reversed(messages):cost = estimate_tokens(msg["content"])if used + cost > budget:breakkept.append(msg)used += costreturn list(reversed(kept))
In real projects, always keep the system message and the current user question, and trim only the middle history.
3.4 Remove Irrelevant Content
Logs, stack traces, raw web HTML, repeated whitespace, and formatting symbols often enter prompts by accident. Cleaning the input before assembling a request removes content unrelated to the task and can significantly reduce input size. For example, when passing code, include only the relevant functions instead of the entire file.
3.5 Apply Semantic Compression to Input
For long text, you can first summarize it with a smaller model or with rule-based methods, then pass the summary to the main model. This adds an extra call, so it suits only cases where the input is very long and some information loss is acceptable. Compare the compressed content with the original by sampling, and confirm that key facts were not dropped or altered.
4. Control Output Tokens
Output is usually the main source of cost, and controlling it often pays off faster than compressing input.
- Set a reasonable maximum output length. Set the limit based on the use case. For example, if a classification task needs only one label, do not allow a long explanation.
- Request structured output. Ask the model to return JSON or tables with fixed fields. This avoids greetings, restating the question, and lengthy introductions or conclusions.
- State length requirements explicitly. Specifying a word count or item count in the prompt is more reliable than leaving the decision to the model.
- Generate in stages. For complex tasks, have the model write an outline first, then expand each section. Each step’s output is more focused and easier to check midway.
Forcibly truncating output can leave the structure incomplete. Set the limit somewhat above the normal required length, and check in your code whether the output is complete.
5. Use Caching and Reuse
Caching works at several levels:
- Prefix caching: Place unchanging system instructions and examples at the start of the request so that multiple requests share the same prefix.
- Result caching: Return existing results for identical or highly similar requests. This works well for factual, low-randomness Q&A.
- Intermediate result reuse: Document summaries, vector indexes, and tool call results are recomputed only when their source content changes.
Result caching requires handling expiration. When the underlying data changes, related cache entries must be invalidated, or the system will return stale content. Cache keys typically combine the task type, model version, a hash of the prompt template, and a hash of the input content.
6. Route Requests by Model Tier
Not every request needs the strongest model. You can group tasks by difficulty:
- Simple tasks, such as classification, keyword extraction, and format conversion, go to a small model.
- Medium tasks, such as general Q&A and text rewriting, use a standard model.
- Complex tasks, such as multi-step reasoning and long-document analysis, use a high-capability model.
Routing can be rule-based, for example by task type or input length. It can also use a small model to assess difficulty first, then decide which path to take. Routing adds its own overhead, so confirm that the savings exceed the scheduling cost.
7. Build a Measurement System
Without measurement, you cannot tell whether an optimization works. Track at least the following metrics:
| Metric | Definition | Purpose |
|---|---|---|
| Average tokens per task | Mean of input plus output tokens | Measure overall consumption |
| Task success rate | Share of outputs that pass quality checks | Prevent sacrificing quality to save tokens |
| Cost per successful task | Total cost divided by the number of successful tasks | Evaluate overall efficiency |
| Time to first token and total latency | Response speed metrics | Assess user experience |
| Cache hit rate | Share of requests served from cache | Evaluate reuse effectiveness |
The code below calculates token consumption per successful task.
from dataclasses import dataclass@dataclassclass TaskRecord:input_tokens: intoutput_tokens: intpassed: booldef token_efficiency(records: list[TaskRecord]) -> float:"""Return the average number of tokens consumed per successful task. Tokens used by failed tasks are included in the total."""total = sum(r.input_tokens + r.output_tokens for r in records)success = sum(1 for r in records if r.passed)if success == 0:return float("inf")return total / success
The evaluation set should cover typical requests and edge cases from real business use. Run it automatically whenever you change prompts, trimming strategies, or models. Saved tokens count as a gain only if the pass rate does not drop.
8. Avoid Common Pitfalls
- Over-compression: Deleting key constraints or examples to save tokens can push the model’s behavior away from what you expect.
- Looking only at per-call cost: Ignoring the cost of failed retries and manual correction can make overall efficiency worse.
- Overlooking hidden tokens: Tool descriptions, function signatures, and retrieval metadata also count as input.
- One-time optimization: Business requirements and models keep changing, so token efficiency needs ongoing monitoring rather than a single pass.
9. Follow a Rollout Plan
- Measure the current state. Record average input and output tokens for each feature module, and identify the largest sources of consumption.
- Set a baseline. Build an evaluation set for core scenarios, and record current quality and cost baselines.
- Prioritize by return. Start with clear waste, such as overly long outputs, unbounded history growth, and repeated injection of large text blocks.
- Validate in small steps. Change one strategy at a time, compare evaluation results, and then move to the next.
- Monitor continuously. Set alert thresholds for cost and success rate in production so that unusual changes surface early.
Token efficiency has no single shortcut. Teams need to weigh cost, quality, and latency against their own business needs, and keep verifying the results with data.
