LLM Cost Optimization in Practice: Completing the Same Task with Fewer Tokens

    When several LLMs produce equally correct answers to the same task, their bills can still differ by several times. This article explains why token consumption varies so much across models and calling strategies, how to make cost measurable through structured evaluation, and which practical techniques—prompt streamlining, context management, model tiering, caching, and batching—can cut token usage without sacrificing quality. It also covers how to sustain these gains through cost dashboards, regression testing, and canary/A/B validation. The goal is simple: when quality is tied, whoever delivers the same result with fewer tokens wins on cost competitiveness.

    1. A Warning Sign: Equal Quality, Widening Cost Gaps

    In real-world evaluations of LLM applications, a familiar pattern often appears. Faced with the same task—say, generating a structured table file from a set of requirements—models across different capability tiers all produce perfect answers, and their output fully satisfies the predefined criteria. From a “can it get the answer right?” standpoint, they are nearly indistinguishable.

    But the moment you line up the bills, the differences surface. Producing the same high-quality output, different models and different calling methods can consume several times as many tokens, and the final cost gaps widen accordingly.

    This points to a fact that is easy to overlook: meeting the capability bar is only the passing line. What truly determines long-term cost is token efficiency per task. For products that call models at high frequency and serve large user bases, that gap quickly amplifies into a substantial cost burden.

    2. Where the Cost Differences Come From: Breaking Down Token Billing

    To optimize cost, you first need to understand how cost is generated. Mainstream LLM services commonly adopt a “pay per token” model, and the cost is made up of the following parts:

    • Input tokens (prompt): All the text you send to the model, including system instructions, conversation history, retrieved context, and the user’s question.
    • Output tokens (completion): The content the model generates.
    • Reasoning tokens (thinking): Some reasoning-oriented models generate an internal reasoning process before the final answer, and these tokens count toward usage as well.

    The key takeaway: output tokens are usually more expensive than input tokens, and the presence of reasoning tokens means “thinking” calls incur extra overhead. As a result, a verbose output or an unnecessary deep-reasoning pass will directly drive up the bill.

    Beyond the billing model itself, there are several frequently ignored sources of difference:

    1. Different tokenizers: The same passage of Chinese text, code, or structured data gets split into different numbers of tokens under different models’ tokenization rules, directly causing “the same work, different charges.”
    2. Context length: Stuffing large amounts of irrelevant material into the context significantly increases input tokens.
    3. Output redundancy: Verbose, repetitive answers that lack formatting constraints often spend a few extra tenths of tokens compared to concise ones.

    3. Build Evaluation First, Then Optimize: Make Cost Measurable

    Optimization cannot rely on gut feeling; you first need a quantifiable, comparable evaluation method.

    1. Construct a representative evaluation set: Choose samples that cover real business scenarios, including both simple and complex tasks, and avoid testing only the “easiest” cases.
    2. Score on quality dimensions: Rate outputs across multiple dimensions, such as correctness, completeness, format compliance, and readability. Only when quality is tied does the cost comparison become meaningful.
    3. Measure on the cost dimension: Record the input tokens, output tokens, and unit price for each sample, and calculate the “overall cost of completing a single task”—not just the per-1K-token price.

    Here is some sample code for tracking the usage of a single call:

    1. def run_task(client, prompt, price_in_per_1k, price_out_per_1k):
    2. response = client.chat(
    3. model="general-purpose-model",
    4. messages=[{"role": "user", "content": prompt}],
    5. max_tokens=1024, # Cap output length to prevent runaway generation
    6. temperature=0.2, # Low temperature for structured tasks to reduce noise
    7. )
    8. usage = response.usage # Typically includes input_tokens / output_tokens
    9. cost = (
    10. usage.input_tokens / 1000 * price_in_per_1k
    11. + usage.output_tokens / 1000 * price_out_per_1k
    12. )
    13. return response.content, {
    14. "input_tokens": usage.input_tokens,
    15. "output_tokens": usage.output_tokens,
    16. "cost": cost,
    17. }

    With this measurement in place, you can turn “which model or which strategy saves more” from a subjective impression into objective data.

    4. Actionable Cost-Reduction Strategies

    Given quality is tied, you can systematically reduce token consumption from several directions.

    1. Prompt Streamlining and Structured Constraints

    • Remove redundant, repetitive, or conflicting instructions, and replace lengthy prose with clear role and task descriptions.
    • Require structured output (such as tables with fixed fields, or JSON) and explicitly cap the length, which can significantly reduce output tokens.
    • Use a few high-quality examples (few-shot) instead of long, wordy explanations to strike a balance between effectiveness and cost.

    2. Context Management

    • When using retrieval-augmented generation (RAG), retrieve only the genuinely relevant snippets and avoid “throwing everything in.”
    • For very long conversation histories, apply summary compression or a sliding window to keep the key information and discard the noise.
    • Place stable, unchanging parts (such as the system prompt) in a fixed position to enable cache reuse later.

    3. Model Tiering and Routing

    Matching tasks of different difficulty to models of different capability tiers is the most direct way to cut costs. Hand simple, templated tasks to lightweight models, and reserve high-capability models for complex reasoning tasks.

    1. def route_and_call(task, call_model, estimate_complexity):
    2. level = estimate_complexity(task) # Assess difficulty by length, keywords, historical success rate
    3. if level == "simple":
    4. return call_model("lightweight-model", task) # Lightweight model, low cost
    5. else:
    6. return call_model("high-capability-model", task) # High-capability model, preserve quality

    4. Cache Reuse

    • Enable prompt caching: cache the fixed prefix (system prompt, background knowledge) so that on repeated calls this portion of input can be reused, lowering input cost.
    • Result caching: for high-frequency, enumerable questions (such as FAQs), hit existing results directly and avoid repeatedly calling the model.

    5. Batching and Streaming Control

    • For non-real-time scenarios, use the batch API, which is usually more cost-effective than online calls.
    • For generation tasks, enable streaming output so you can terminate early once the requirement is met and avoid generating excess content.

    5. Turning Optimization into Continuous Operations

    Cost optimization is not a one-time effort but an ongoing operational process.

    • Build a cost dashboard: Bring call volume, token consumption, cost per task, and cache hit rate into monitoring. With the logging and monitoring/alerting capabilities offered by cloud platforms (for example, the general-purpose logging and monitoring services offered by Baidu AI Cloud), you can alert on abnormal consumption promptly.
    • Run regular regression evaluations: Every time you adjust a prompt or switch models, run the evaluation set again to confirm that “cost went down without quality dropping.”
    • Canary and A/B validation: Validate new strategies on a small traffic slice first, and let the data decide whether to roll them out fully.

    6. Conclusion

    The same high-quality output can come from either an expensive call or a carefully optimized one; the two are no different in terms of “getting the answer right,” and the gap shows up only in efficiency and the bill. Truly mature teams do not fixate on model capability alone—they treat token efficiency as a first-class citizen: first establish a measurable evaluation, then systematically optimize across prompts, context, model routing, caching, and batching, and finally preserve the gains over the long term through monitoring and regression. When quality is tied, whoever delivers the same result with fewer tokens holds the cost advantage.