LLM API Cost Governance and Token Optimization Practices

    This article breaks down where LLM API token costs come from and presents five practical optimization techniques: context layering, batching, caching, model routing, and output constraints. It also covers the observability metrics, quotas, and alerting needed to keep inference spending predictable, along with common pitfalls to avoid. The guidance is vendor-neutral and applies to any LLM-based application architecture.

    1. The Problem: Capability Leaps Come With a Rising Cost Curve

    A pattern has become common across the industry: each new generation of large models reasons better, but token consumption per request rises with it. At the same time, developer communities are busy debating high-profile compensation moves for core algorithm talent and whether companies should respond to negative press. Strip away the news framing, and the real question for engineering teams is a single one: as model capability keeps improving, how do you keep inference cost within a predictable, explainable range?

    One point of industry consensus is worth stating up front: LLMs are billed by token, with input (prompt) and output (completion) priced separately, and output usually costs more. Long context, multi-turn conversations, tool calls, and chain-of-thought reasoning all amplify token usage. So “burning more tokens” is not a defect in any particular product; it is a structural consequence of greater capability. The engineering answer is not to avoid it but to build a cost governance system.

    2. Breaking Down the Cost of a Token

    You cannot optimize cost until you can locate it. The tokens in a single call break into four segments:

    1. System prompt and tool descriptions: fixed overhead, transmitted again on every request;
    2. Retrieved and business context: grows linearly with the number of knowledge base hits and document length;
    3. Multi-turn history: accumulates with each conversation turn and is the most easily overlooked “hidden cost”;
    4. Model output: includes both the explicit answer and implicit reasoning, at the highest unit price.

    An illustrative usage calculation (pseudocode, showing the calculation method only):

    1. # Single-request cost estimate: illustrates the calculation only, not any vendor's actual pricing
    2. def estimate_cost(req, price_in, price_out):
    3. t_in = len(system_prompt) + len(req.context) + len(req.history)
    4. t_out = req.expected_output_len + req.reasoning_len
    5. return t_in * price_in + t_out * price_out

    Once the four segments are separated, optimization has clear handles: compress and reuse fixed overhead, improve retrieval precision for context, use summarization and sliding windows for history, and apply structured constraints and length caps to output.

    3. Five Practical Optimization Techniques

    3.1 Context Engineering: From “Fill It Up” to “Make It Precise”

    A larger context window does not mean you should fill it. The practical approach is layered assembly: the system layer keeps only immutable constraints; the knowledge layer retrieves only fragments strongly relevant to the current question, with a similarity threshold and a cap on the number of fragments; the conversation layer replaces raw history with a rolling summary. A reusable trimming function skeleton:

    1. def build_context(system, retrieved, history, budget=6000):
    2. # Allocate the token budget by priority, trimming from the lowest priority when over limit
    3. parts = [("system", system, 1.0), ("kb", retrieved, 0.6), ("hist", history, 0.3)]
    4. used, out = 0, []
    5. for name, text, w in sorted(parts, key=lambda x: -x[2]):
    6. keep = min(len(text), int((budget - used) * w))
    7. out.append(text[:keep]); used += keep
    8. return "\n".join(out)

    3.2 Batching and Async Processing

    Offline tasks (log classification, content moderation, batch summarization) are not latency-sensitive and can be merged into batch requests, collapsing many round trips into one large request and cutting repeated instruction overhead. For online paths, use a message queue to smooth out peaks and avoid the token waste caused by repeated retries during traffic spikes.

    3.3 Caching and Reuse: Hit Rate Is Cost Rate

    Caching has three layers: exact cache (identical requests reuse the result directly), prefix cache (the system prompt and fixed knowledge prefix stay unchanged, avoiding repeated billing), and semantic cache (similar questions map to the same answer, requiring a similarity threshold and an invalidation policy). In practice, define an explicit key design, TTL, and version number for each cache, and invalidate them all when the model or prompt changes, so stale answers do not pollute new requests.

    3.4 Tiered Model Routing

    Not every request needs the strongest model. A three-tier route works well: simple classification, extraction, and formatting tasks go to a small-parameter model; routine question answering goes to the main model; only complex reasoning and code generation escalate to a high-capability model. Routing decisions can be made with rules up front or scored by a lightweight classifier, with a manual override switch for forced escalation.

    1. def route(task):
    2. if task.type in {"classify", "extract", "format"}:
    3. return "small"
    4. if task.complexity_score > 0.75 or task.type == "code":
    5. return "large"
    6. return "mid"

    3.5 Output Constraints

    Structured output, explicit word and field limits, and a ban on restating instructions all strip out low-value output. For reasoning tasks, require the conclusion first and the supporting evidence after, so lengthy process text does not enter the billed output.

    4. Observability: No Measurement, No Governance

    Cost governance depends on a closed data loop. Collect at least four categories of metrics: input and output tokens per request, cache hit rate, routing distribution, and daily consumption per business line with period-over-period fluctuation. In practice, a common combination is application instrumentation plus log service collection plus a monitoring and alerting dashboard, with threshold alerts on abnormal spikes (for example, trigger a review when a single tenant’s day-over-day usage doubles). Also establish quotas and rate limiting, setting token budgets per tenant and per API so a single abnormal call cannot drag down the entire bill.

    5. Common Pitfalls

    • Watching unit price but not usage: falling unit prices are often cancelled out by context inflation;
    • Blindly expanding context: handing retrieval’s job to the window raises both cost and noise;
    • Caching without an invalidation policy: returning outdated conclusions after a model upgrade;
    • No tiered routing: sending every request to the highest capability tier;
    • No budget or alerts: discovering an abnormal bill at month end, when it can no longer be attributed.

    6. Conclusion

    Model capability upgrades are irreversible, and rising token consumption is a structural trend. What engineering teams can do is turn an “uncontrollable bill” into a cost item that is attributable, budgetable, and optimizable. From layered context, cache reuse, batching, and tiered routing to observability and quota alerting, this combination is independent of any specific vendor and applies to any LLM-based application architecture. If you need elastic compute along with supporting data collection and monitoring and alerting capabilities, you can assemble them on demand from the general cloud product categories offered by Baidu AI Cloud. Keeping the architecture vendor-neutral and portable is the prerequisite for long-term cost control.