Engineering Practices for Lowering LLM Inference Costs

    A practical guide to reducing LLM inference costs per task. Learn how to decompose task spending across input, cached input, output, and retries, maximize prompt cache hit rates, apply tiered model routing with budget guardrails, and build evaluation and cost dashboards that reflect real end-to-end expenses.

    1. The Starting Point: Cheaper Unit Prices Do Not Guarantee Cheaper Bills

    When teams evaluate a new generation of models, the first thing they usually look at is the price per million tokens: how much input costs, how much cached input costs, and how much output costs. Yet real bills often defy intuition—unit prices drop, but monthly spending stays flat or even rises. The reason is simple: as capabilities improve, agents run more turns, call more tools, and handle longer contexts. The growth in total tokens offsets the savings from lower unit prices.

    As a result, the industry is gradually shifting the evaluation metric from “price per token” to “cost per task”—the average cost of completing one task under a fixed task set and a fixed quality bar. The score–cost curve in the original article, with the horizontal axis extended to very high values, is essentially answering one question: to reach the same score, how much do I have to pay?

    2. Breaking Down the Cost: Where the Money Goes in a Single Task

    To optimize, you first need attribution. The cost of a long-horizon task can be split into four parts:

    1. Input context: system prompts, tool definitions, conversation history, retrieved snippets;
    2. Cached input: the portion that exactly matches the previous turn’s prefix and is reused;
    3. Output: the model’s reasoning, tool call arguments, and final response;
    4. Retries and failures: repeated consumption caused by timeouts, invalid formats, or tool errors.

    The fourth item is the most easily overlooked. In long-horizon tasks, the cost of one failure is not a single call—it is a replay of the entire history.

    Illustrative cost accounting logic:

    1. def task_cost(records, price):
    2. total = 0.0
    3. for r in records:
    4. total += r["input"] * price["input"]
    5. total += r["cached"] * price["cached"]
    6. total += r["output"] * price["output"]
    7. return total

    3. Cache Hits: Capture the Largest Reduction First

    Cached input usually shows the most significant price reduction among the four categories (the original article mentions a drop from the $1 level to the $0.4 level, roughly a 60% reduction). But whether the cache is hit depends on whether the prefix is byte-for-byte stable. Engineering-wise, three things must be done:

    • Fix the prefix: put the system prompt, tool schema, and examples at the front, and avoid dynamic injections such as timestamps or random IDs;
    • Append rather than rewrite: in multi-turn conversations, only append at the end; modifying history invalidates the entire cache;
    • Segment and isolate: place volatile content (retrieved results, new user input) after the stable prefix.
    1. [Stable prefix: system prompt + tool definitions + few-shot examples] ← cacheable
    2. [Semi-stable segment: conversation summary] ← updated infrequently
    3. [Volatile segment: this turn's retrieved snippets + user input] ← not cached

    4. Tiered Routing: Not Every Step Deserves the Most Expensive Model

    After capabilities improve, a more cost-effective approach is tiering: split the task into planning, execution, and verification, and match each with a different model tier. Use the high-capability tier for planning and final verification, and a lightweight tier for mechanical execution and format conversion. The phenomenon in the original article where a certain lightweight tier got a capability upgrade at an unchanged price shows that the cost-performance of mid- and low-tier models is often underestimated.

    1. def route(step):
    2. if step.kind in ("plan", "verify"):
    3. return "high" # high-capability tier
    4. return "light" # lightweight tier

    Using it together with budget guardrails makes it more stable:

    1. if spent(task_id) > BUDGET:
    2. return escalate_or_fallback(task_id)

    5. How to Make Evaluations Convincing

    When looking at a score–cost curve, pay attention to three details; otherwise, it is easy to draw the wrong conclusion:

    • Whether outlier samples are excluded: the original article explicitly states that the comparison target’s results excluded several tasks that used a fallback model. Differences in this kind of measurement scope can significantly affect conclusions;
    • Whether a fixed quality bar is used: comparing only scores without pass rates hides the implicit cost of retries;
    • Whether end-to-end costs are counted: counting only model calls while ignoring retrieval, tool execution, and human review underestimates the cost.

    It is advisable to build a small-scale regression set, fix randomness, record the token composition and failure reasons of each task, and form a reproducible cost baseline.

    6. Implementation Checklist

    1. Build a per-task cost dashboard with attribution across four dimensions: input, cache, output, and retries;
    2. Reorder the prompt structure to put stable content first, and monitor the cache hit rate;
    3. Introduce tiered routing and budget caps; automatically downgrade or escalate to a human when the cap is exceeded;
    4. Perform root cause analysis on failed samples, prioritizing fixes to tool contracts and output format constraints;
    5. In evaluation reports, present three curves together: score, pass rate, and cost per task.

    Conclusion: unit price is only the entry ticket; what really determines the bill is the cache hit rate, routing strategy, and failure rate. Engineering these three is what makes capability improvements faithfully reflected in the cost curve. If you need elastic compute along with supporting data storage, logging, and monitoring and alerting capabilities, you can assemble them on demand from the general cloud product categories offered by Baidu AI Cloud.