Optimizing LLM Token Consumption: From Cost Evaluation to Usage Control
This article explains how to evaluate large language model spend by cost per accepted task rather than list price alone. It covers unit-task cost, context and prompt reduction, reasoning-level selection, speed tradeoffs, controlled comparisons, and data boundaries.
1. Background: Why Token Consumption Matters
Large language models are billed by tokens. Both the input and the output of every call count toward usage. As model capability increases, the unit price of a new flagship model is often higher than that of the previous generation, and some ultra-flagship models can cost several times as much. When evaluating options, teams often look only at unit price and overlook two other variables: how many tokens a task actually consumes, and whether the task can be completed in one pass.
Cost evaluation should answer one question: how much does it cost to finish one valid task? A higher unit price does not necessarily mean a higher total cost, and a lower unit price does not necessarily save money.
2. Calculate Unit Cost per Successful Task First
Use the following formula:
Cost per successful task = total cost ÷ number of tasks that pass acceptance
“Pass acceptance” must be defined by the business. Examples include code that passes tests, documents that pass review, or issues that are correctly resolved. Counting calls or generated words alone does not reflect real output.
Illustrative code:
def cost_per_successful_task(total_cost: float, tasks_passed: int) -> float:"""Cost per accepted task. Returns infinity when none pass, so reports can flag it."""if tasks_passed == 0:return float("inf")return total_cost / tasks_passed# Example: 120 spent in a week, 30 tasks acceptedprint(round(cost_per_successful_task(120.0, 30), 2)) # prints 4.0
This metric reflects unit price, token usage, and rework rate together. A more expensive model can still have a lower unit cost if it needs far fewer retries.
3. Context Management: Keep What Matters, Cut Repeated Input
Long tasks often span many turns. Each turn may resend the full history, so input tokens accumulate quickly. A common approach is to write key facts to an external note and send only a summary plus the latest messages on each turn.
3.1 External Notes
Record confirmed conclusions, interface agreements, open items, and important error messages in a separate file. The next request should refer to the note instead of pasting long logs again.
3.2 Trim History and Tool Results
Long tool output, such as full logs or large file contents, usually only needs the fragments relevant to the current problem. Keep a fixed number of recent items and replace the rest with a summary.
Illustrative code:
def build_context(notes: list[str], recent_messages: list[dict], max_recent: int = 10) -> list[dict]:"""Build context: notes first as a summary, then only the latest messages."""summary = "\n".join(f"- {item}" for item in notes[-20:])system_block = {"role": "system", "content": "Task notes:\n" + summary}return [system_block] + recent_messages[-max_recent:]
3.3 Caveats
Cross-window memory usually applies only within the same task. It does not automatically retrieve every past conversation. Confirm the memory scope of the platform you use, and do not assume that content from old sessions will be carried in. When notes include sensitive data, store them under the appropriate access rules and clean them up on a schedule.
4. Slim Down Instruction Files and Prompts
Project docs, skill descriptions, and system prompts are read on every call, so they are a fixed overhead. As teams keep adding rules, these files often accumulate duplicate entries and long trigger descriptions.
Ways to reduce them:
- Merge duplicate rules. Keep each constraint in one place. Do not restate the same requirement in multiple files.
- Shorten trigger descriptions. Use brief keywords for when a rule applies, and drop unrelated context.
- Store by layer. Put general standards in a global file, project-specific rules in the project directory, and submodule rules where they are loaded only when needed.
- Review on a schedule. Check instruction files about once a quarter and remove rules that no longer apply.
Before and after trimming, compare token usage and pass rate on the same task set, and confirm that quality has not dropped.
5. Match Reasoning Level to Task Complexity
Most large language models offer different reasoning strengths or thinking budgets. A higher setting uses more internal reasoning tokens before the answer, so a single call costs more, but accuracy on hard problems may be higher.
A practical tiering strategy:
| Task type | Suggested level | Notes |
|---|---|---|
| Format conversion, simple Q&A, single-file edits | Low to medium | Favor speed and cost |
| Routine feature work, common bug fixes | Medium to high | Balance quality and cost |
| Cross-module refactors, complex debugging | High to very high | Reduce rework |
| A few especially hard problems | Highest | Use only after lower levels fail repeatedly |
Base the tiers on historical data, not on impression. Record pass rate and average token use for each level on each task type, then update the policy from those numbers.
6. Trading Response Speed Against Cost
Some platforms offer different response-speed options. A faster mode usually means higher resource use or a higher unit price, but shorter wait time. Whether it is worth it depends on whether the task needs immediate feedback.
A conclusion from a single run is unreliable. Differences in output speed can also come from network conditions, queue time, and the length of the task itself. Test several times under the same conditions before choosing a default.
7. Run Controlled Comparisons
To avoid subjective judgment, compare configurations as follows:
- Prepare a task set. Select 20 to 50 representative tasks covering both everyday and complex cases.
- Hold variables fixed. Each configuration should use the same task description and the same starting code or document.
- Record metrics. Include input and output tokens, elapsed time, whether the result passed acceptance, and the number of retries.
- Compute unit cost. Aggregate results with the formula in section 2.
- Compare and decide. Look at cost and quality together. If cost falls but the pass rate drops sharply, do not adopt that configuration.
Illustrative records:
records = [{"config": "A", "input_tokens": 52000, "output_tokens": 8000, "passed": True},{"config": "A", "input_tokens": 61000, "output_tokens": 9500, "passed": False},{"config": "B", "input_tokens": 38000, "output_tokens": 7200, "passed": True},]def summarize(records: list[dict], config: str) -> dict:rows = [r for r in records if r["config"] == config]passed = sum(r["passed"] for r in rows)tokens = sum(r["input_tokens"] + r["output_tokens"] for r in rows)return {"config": config, "pass_rate": passed / len(rows), "tokens_per_task": tokens / len(rows)}
8. Security and Data Boundaries
During evaluation and optimization, use redacted data or a test environment. Do not connect directly to a production database or production configuration just to recreate a real scenario. That can leak data or change production by mistake. For accounts, keys, and internal documents, follow least privilege and check the provider’s data-handling policy.
9. Summary
Token cost is about spend per successful task, not the list price by itself. In practice, optimize in this order: set up controlled comparisons, then slim context and instruction files, then assign reasoning levels by task complexity, and finally choose speed settings from the data. Every change should be checked for both cost and pass rate. Keep a configuration only when both meet expectations.
