Engineering Practices for Reducing LLM Token Consumption

    This article explains how to cut token usage in large language model applications without hurting task success rates. It shows why tokens get wasted along the execution path of agents and coding assistants, then lays out six principles: separating value tokens from process tokens, slicing prompts by task, treating the context window as expensive memory, offloading deterministic work to programs, using caching and batching, and gating cost reduction with task success metrics. It closes with a practical checklist and deployment notes. Readers will learn which tokens create value, which context can be made incremental, and which results can be reused instead of recomputed.

    In LLM applications, tokens often determine cost, latency, and throughput all at once. A single request counts tokens on both the input side (system prompts, conversation history, retrieved snippets, tool returns) and the output side (reasoning traces, intermediate code, logs, retries). Many teams fixate on “switching to a smaller model” while overlooking the large amount of deletable, parallelizable, and cacheable work along the execution path. Sustainable cost reduction starts by separating “which tokens create value” from the rest, then systematically compressing everything else.

    Why Tokens Get Wasted Along the Execution Path

    A typical agent or coding assistant is not a simple “ask once, answer once” loop. It usually involves understanding the task, retrieving material, planning steps, calling tools, reading back results, fixing errors, and re-executing. Each step can stuff verbose intermediate text back into the context. Common sources of waste include:

    • Overly long system prompts carried in full on every call, much of which is irrelevant to the current task.
    • Untrimmed conversation history that preserves early trial-and-error, repeated errors, and debug output verbatim.
    • Un-summarized tool returns that feed complete logs, stack traces, and directory trees straight back to the model.
    • Over-detailed planning: handing loops, validation, and formatting that a program could do to the model to “think through” step by step.
    • Retries after failure without state reuse, regenerating nearly identical plans from scratch each time.
    • During evaluation or batch processing, running every sample through a full “explain + demonstrate + self-check” chain when the task only needs a short answer.

    So the key question for cost reduction is not “will the model save words,” but: which work can move from generation to deterministic computation, which context can move from full to incremental, and which results can move from recomputation to reuse.

    Principle 1: Separate Value Tokens from Process Tokens in Your Accounting

    Tag each call at the gateway or orchestration layer with: task type, input length, output length, tool rounds, cache hits, and whether it was a retry. Without this breakdown, optimization easily becomes “it feels like we said a bit less.” At minimum, distinguish:

    1. Necessary input: the current question, constraints, key code snippets, or structured state.
    2. Compressible input: long documents, history, raw tool output.
    3. Omittable output: step-by-step reasoning, stylistic pleasantries, restating the question.
    4. Work that should be externalized: compilation, unit tests, static checks, formatting, retrieval ranking.

    Many teams find that a drop in success rate is often not because they “generated less reasoning,” but because they deleted a key constraint along with it. The right move is to compress the process, not the specification.

    Principle 2: Slice Prompts by Task, Not One Giant Constitution

    The system prompt should be modular: identity and safety baselines stay resident; domain rules load per task type; examples are retrieved by similarity with only 1–2 included; the output schema is fixed with a short template. Practical suggestions:

    • Replace prose rules with structured fields (for example, “output JSON: status, files, command”).
    • Turn “never do X” rules into tool-side interception, reducing the model’s repeated self-reminders.
    • For coding tasks, provide only symbols and interfaces relevant to the current file, not a dump of the whole repository.
    • For Q&A tasks, deduplicate, truncate, and number citations in retrieved results first, avoiding multiple near-duplicate passages.

    Every thousand tokens removed from the input side saves money and reduces the risk of attention being diluted by noise, which is especially noticeable for small-parameter execution models.

    Principle 3: Govern the Context Window Like Expensive Memory

    History messages should have a clear lifecycle:

    • Keep: the user’s goal, confirmed decisions, a summary of the current workspace, and a minimal reproduction of unresolved errors.
    • Fold: merge multiple rounds of trial-and-error into “tried approaches A/B and why they failed.”
    • Discard: pure small talk, repeated pastes, complete compilation logs.

    Use a “state object” instead of a chat log: for example, goal, constraints, repo_map, last_error, next_action. Each round serializes only that object into the prompt, keeping length bounded and testable. Tool returns should be forced through summarization: for a test failure, keep only the failing case name, the assertion diff, and the relevant top of the stack; for command output, keep only the exit code and key lines.

    Principle 4: If a Program Can Run It, Don’t Make the Model Play Computer Step by Step

    This is the highest-leverage category of change for cost reduction. Models are good at decisions and drafting, not at being interpreters. Move loops, bulk replacements, syntax checks, unit tests, coverage, and dependency resolution into the orchestrator or a sandbox, and have the model produce only:

    • Patch intent or structured edits for which files to change;
    • Which command to run;
    • The next-hop decision after a failure, based on the summarized error.

    The execution loop should cap rounds and per-round output, and set early stopping: stop explaining once tests are green; on repeated same-type failures, switch strategy rather than retrying the same prompt. For code-generation evaluations or batch tasks, disable the default style of “write a long analysis first, then answer” and switch to a short patch plus automated verification. In public code evaluations, industry practice generally shows that, while keeping the automated test pass rate intact, compressing intermediate monologue and repeated planning often significantly reduces per-task tokens, and success rate depends mainly on whether the verification loop is complete, not on how long the explanation is. Specific reductions vary by model, task set, and orchestration implementation, so a single set of experimental numbers should not be extrapolated into a universal conclusion.

    Principle 5: Caching, Batching, and Speculative Execution

    The same system prompt, the same retrieved snippets, and the same tool schema should use prefix caching or semantic caching at the gateway. During batch evaluation, a fixed prefix can greatly improve cache hit rates. For high-concurrency online services:

    • Merge independent sub-problems that can run in parallel, avoiding serial multi-round calls.
    • Use a smaller execution model for highly deterministic short answers, and route complex cases to a stronger model.
    • Pair streaming output with a maximum token limit and stop words to prevent the model from continuing to “summarize the summary” after finishing the answer.

    Note: what you cache is reusable computation, not stale business data pinned permanently in the context.

    Principle 6: Gate Cost Reduction on Task Success Rate, Not on Gut Feeling

    Optimization must be tied to evaluation: the same task set, the same execution model tier, the same timeout and tool permissions. Track:

    • Average input/output tokens per task;
    • Tool rounds and retry rate;
    • Automated verification pass rate (unit tests, formatting, constraint satisfaction);
    • Tail latency.

    If the pass rate drops, first check whether you accidentally removed a constraint, a test command, or a key file snippet, rather than immediately adding the prompt back. Ablation experiments should disable only one category of waste at a time (for example, only long reasoning, or only tool summarization); otherwise you cannot tell “which work was actually removed.”

    Implementation Checklist

    • Is the system prompt split by task type, with a length cap?
    • Is history folded into state, and is tool output forced through summarization?
    • Are compilation, testing, and formatting executed outside the model?
    • Are rounds, output limits, and no-progress early stopping enforced?
    • Is caching applied to prefixes and high-frequency retrieval?
    • Does the same evaluation set track both tokens and success rate?

    When deploying in the cloud, you can place these capabilities in a unified inference gateway with logging and monitoring: object storage holds long context and artifacts, a logging service records the token breakdown, and monitoring alerts watch for abnormally long requests. Container, gateway, and observability components on cloud platforms such as Baidu AI Cloud are suited to hosting this kind of orchestration, rather than scattering governance logic across every business service.

    Conclusion

    Reducing token consumption is essentially reducing the repetitive work the model does on behalf of the system. Slicing prompts, turning context into state, handing execution to programs, and making results cacheable and verifiable is how you bring down cost and latency without the success rate slipping. More important than chasing a particular set of paper numbers is being clear about whether what you deleted was process noise or evidence the task genuinely cannot do without.