Engineering Practices for Reducing LLM Token Costs

    This article breaks down where LLM token consumption actually comes from and presents five practical optimization paths: context governance, prompt and output constraints, caching and reuse, model routing, and batching with streaming. It also covers token-centric observability and a phased rollout plan, helping teams balance output quality, latency, and cost while treating unit cost per successful task as the core metric.

    1. Background: Why a Single Conversation Can Consume Hundreds or Thousands of Tokens

    In intelligent coding assistants, customer service bots, document Q&A, and task-oriented dialogues such as food ordering, users typically perceive only a simple exchange: one question, one answer. Underneath, however, the model receives a single concatenated block of text. A seemingly simple interaction may include system instructions, tool definitions, multi-turn conversation history, retrieved knowledge snippets, and the user’s current input on the input side, while the output includes reasoning steps, structured call parameters, and the final reply. Combined, a single request consuming several hundred or even several thousand tokens is the norm.

    A token is the basic unit by which a model measures text. In Chinese, one character usually maps to roughly one to two tokens, while English words, punctuation, and code symbols are split into varying numbers of tokens. Understanding this is the prerequisite for cost governance: cost is not determined by “how many characters the user typed,” but jointly by total context length + generation length.

    2. Cost Breakdown: Where the Money Goes

    Breaking down the bill, token consumption mainly comes from five sources:

    1. System prompts and role settings: To keep output style and safety boundaries stable, system prompts tend to be long and must be carried on every request.
    2. Tool and API definitions: Task-oriented dialogues require the model to understand available capabilities, and tool descriptions plus parameter schemas consume a large number of input tokens.
    3. Accumulated conversation history: In multi-turn scenarios, history grows linearly, and the input of the tenth turn can be more than ten times that of the first.
    4. Retrieval-augmented snippets: Knowledge snippets injected to improve accuracy can easily “sacrifice cost for recall” if they are not trimmed and reranked.
    5. Redundant output: Models tend to produce explanatory text, repeated conclusions, and unnecessary formatting.

    A simplified model can approximate the cost:

    1. cost per request ≈ (system prompt + tool definitions + history + retrieved snippets + user input) × input price
    2. + generation length × output price

    Since the output price is usually higher than the input price, controlling generation length often delivers more immediate results than compressing the input.

    3. Optimization Path 1: Context Governance

    Context governance offers the highest return with the lowest risk, and its core principle is “carry only necessary information.”

    • Layered prompts: Fix invariant rules at the system layer and place scenario-specific constraints at the session layer, avoiding stuffing long documents into the system prompt.
    • History compression: Summarize history that exceeds the window, keeping decision conclusions and key parameters while discarding pleasantries and repeated confirmations.
    1. def build_context(system, tools, history, retrieved, query, max_tokens=6000):
    2. # 1) Always keep the fixed layer first
    3. ctx = [{"role": "system", "content": system}]
    4. # 2) Trim tool definitions on demand, keeping only capabilities likely needed this turn
    5. ctx.append({"role": "system", "content": select_tools(tools, query)})
    6. # 3) Replace raw history with a summary
    7. ctx.append({"role": "system", "content": summarize(history)})
    8. # 4) Rerank and truncate retrieved snippets
    9. ctx.extend(rerank_and_truncate(retrieved, budget=max_tokens // 3))
    10. ctx.append({"role": "user", "content": query})
    11. return fit_budget(ctx, max_tokens)
    • Retrieval budgeting: Set a token budget for retrieved snippets and use a reranker or rules to place the few most relevant snippets first instead of concatenating everything.
    • Structure instead of long text: When information can be expressed as fields, avoid natural-language paragraphs. Passing addresses, specifications, and times as key-value pairs can significantly shorten the context.

    4. Optimization Path 2: Prompt and Output Constraints

    • Define an explicit output contract: Stating “return JSON only, no explanations” in the prompt can cut generation length by 30% to 50%.
    • Keep few-shot examples lean: More examples are not always better; two or three that cover the key branches are enough.
    • Externalize chain-of-thought: When complex reasoning is needed, write intermediate steps into a scratchpad or tool call parameters rather than outputting all of them to the user.
    1. {"action": "create_order", "items": [{"sku": "A1", "qty": 1}], "constraints": {"no_extra_text": true}}

    5. Optimization Path 3: Caching and Reuse

    Caching is the “compound interest” of cost governance.

    • Prefix caching: Place the system prompt and tool definitions at the very front of the request and keep them byte-for-byte stable, so the underlying system can reuse computation results, reducing repeated billing and time to first token.
    • Semantic caching: Build a vector index for high-frequency similar questions and return historical answers directly on a hit, which suits customer service and knowledge Q&A.
    • Tiered result caching: Exact hits go through a key-value cache, fuzzy hits go through the semantic cache, and only misses reach the model.
    1. def answer(q):
    2. if (hit := exact_cache.get(q)): return hit
    3. if (hit := semantic_cache.search(q, threshold=0.92)): return hit
    4. out = llm(build_context(...))
    5. exact_cache.set(q, out, ttl=3600)
    6. return out

    6. Optimization Path 4: Model Routing and Tiering

    Not every request needs the most capable model. Requests can be tiered by intent complexity: simple factual lookups, format conversion, and field extraction go to lightweight models, while multi-step reasoning, code generation, and complex planning go to higher-capability models. Routing can be implemented with rules, a small classification model, or confidence thresholds, with an “escalation path” preserved so that requests are automatically upgraded when a lightweight model’s confidence is insufficient, balancing cost and quality.

    7. Optimization Path 5: Batching and Streaming Strategies

    • Asynchronous batching: Merge requests for offline summarization, bulk labeling, and similar tasks to improve throughput and dilute unit cost.
    • Streaming output: This does not change the total token count but significantly improves perceived latency and reduces the likelihood of users asking again, indirectly cutting consumption.
    • Timeout and retry governance: Unbounded retries are a hidden cost sink; exponential backoff and a maximum retry count should be configured.

    8. Observability: No Measurement, No Optimization

    Build an observability system centered on tokens, collecting at least: input/output tokens per request, cache hit rate, routing distribution, cumulative consumption per session, and success rate per task. With this data, you can tell whether an optimization “actually saves money” or “sacrifices quality.”

    1. Example metrics dashboard
    2. - tokens_in / tokens_out trends
    3. - cache_hit_rate, route_ratio(light/heavy)
    4. - cost_per_successful_task <- key north star metric

    Note that the core metric should be cost per successful task rather than raw total token volume; otherwise, you can fall into the trap of “the more you save, the less accurate it gets.”

    Phase one focuses on “low risk, high return”: output contracts, history summarization, and retrieval budgets. Phase two introduces caching and routing. Phase three builds an evaluation set and dashboards to close the loop. Each phase should retain A/B evaluation, using an offline evaluation set to verify that quality does not regress.

    10. Conclusion

    Token cost is not a financial problem but an architectural one. Managing context as a limited budget, treating models as a tiered, schedulable resource pool, and treating caching and observability as infrastructure allows a stable balance among quality, latency, and cost. For teams that need to implement this governance in their own environments, the container platform, message queue, object storage, log service, and monitoring and alerting capabilities offered by Baidu AI Cloud can be used to build a unified model gateway and observability pipeline, turning cost optimization from a one-off initiative into a sustainable engineering capability.