Large Model API Cost Governance: Controlling Spend with Tiered Routing

    This article explains how to control large language model API costs by restructuring how requests are routed rather than reacting to price changes. It covers building a weekly usage profile, classifying tasks into L1, L2, and L3 tiers with rule-based routing, applying context engineering to cut input tokens, and adding semantic caching, batching, and structured output constraints. It also describes budget guardrails, observability metrics, common pitfalls, and a two-week rollout plan. By combining routing, caching, constraints, and guardrails, teams turn the monthly bill into an engineering metric they can tune at any time.

    1. The Problem Is Not a Price Hike, It Is an Unlayered Request Structure

    When teams first notice rising large model spending, the instinct is to blame price changes. But what actually determines the bill is the request structure: request volume, context length, output length, retry count, and the distribution of task difficulty. When the same usage pattern produces several-fold differences before and after a price adjustment, it usually means every task is being pushed through the same top-tier pipeline, with no mechanism to split traffic.

    Write cost as something you can analyze, not a number you only see at month end:

    1. daily cost ≈ Σ(requests of task type i × (input tokens + output tokens) × unit price i) + retry and failure amplification factor

    The formula shows at least four optimization levers: request count (caching and deduplication), context length (retrieval and trimming), output length (structured constraints), and unit price (tiered routing). Focusing only on unit price is the least effective of the four.

    2. Step One: Break Down Usage to Find the Real Cost Center

    Before optimizing anything, build a one-week usage profile across these dimensions:

    • Task type: code completion, code explanation, unit test generation, log and error analysis, document summarization, data extraction, conversational Q&A;
    • Context source: whole files, cross-file retrieval snippets, conversation history, external retrieval results;
    • Output shape: short conclusions, patches, complete files, structured JSON;
    • Failures and retries: timeouts, invalid formatting, and second calls triggered by failed review.

    In practice, the cost center usually concentrates in two kinds of tasks: “analytical” requests that stuff large blocks of context in wholesale, and “generative” requests that get retried repeatedly. Optimize context for the former; optimize constraints and validation for the latter.

    3. Step Two: Classify Tasks and Match Each Request to “Good Enough” Capability

    Splitting tasks into three tiers by “fault tolerance” and “reasoning depth” is the core of cost governance:

    Tier Typical tasks Capability requirement Routing strategy
    L1 lightweight Format conversion, field extraction, comment generation, simple classification Low latency, strong instruction following Small fast model, batchable
    L2 mainstream Code modification, error localization, unit test completion, routine Q&A Stable reasoning, long context Mainstream general model
    L3 deep reasoning Cross-module refactoring, complex defect root cause, trade-off analysis Strong reasoning, long-chain consistency Large reasoning model, strict rate limiting

    The key constraint: tiering must be decided by rules or a lightweight classifier, not chosen ad hoc by the user. Practical signals include task labels, input length, whether the task spans files, and historical retry count.

    1. def route(task):
    2. if task.retry_count >= 1 or task.cross_file:
    3. return "L3"
    4. if task.input_tokens > 8000 or task.need_reasoning:
    5. return "L2"
    6. return "L1"

    4. Step Three: Context Engineering Often Saves More Than Switching Models

    Input tokens are the easiest part of the bill to compress. Feeding whole files delivers far less value than expected, because irrelevant code both raises cost and dilutes attention. Recommended practices:

    1. Retrieval first: use keywords and the call graph to locate candidate snippets, then feed only the necessary functions and type definitions;
    2. Structural trimming: keep signatures, dependencies, and key branches; collapse implementation details;
    3. Layered summarization: for very large repositories, generate module-level summaries first, then let the model ask follow-up questions based on those summaries;
    4. History compression: in multi-turn conversations, keep conclusions and decisions, drop intermediate steps.

    Illustrative context assembly logic:

    1. def build_context(repo, query, budget=6000):
    2. hits = repo.search(query, top_k=8)
    3. parts, used = [], 0
    4. for h in hits:
    5. snippet = h.signature + h.relevant_lines
    6. if used + len(snippet) > budget:
    7. break
    8. parts.append(snippet); used += len(snippet)
    9. return "\n\n".join(parts) + f"\n\nremaining budget: {budget-used}"

    5. Step Four: Caching, Batching, and Structured Constraints

    • Semantic caching: build cache keys for high-frequency repeated questions (error explanations, config generation). The key consists of the normalized input plus the constraint version; a hit returns directly;
    • Prefix reuse: put stable system prompts and specification documents in the prefix to reduce repeated billing (whether this is supported depends on the general capabilities of the chosen service);
    • Batching: merge offline tasks (document generation, bulk extraction) into combined submissions and use a queue to smooth peaks, avoiding peak-hour retries;
    • Output constraints: use a JSON Schema or template to bound output, cutting verbose explanations while lowering parse failure and retry rates.
    1. {"type":"object","required":["cause","fix","risk"],"properties":{"cause":{"type":"string"},"fix":{"type":"string"},"risk":{"type":"string"}}}

    6. Step Five: Budget Guardrails and Observability

    Cost governance must be engineered, not left to discipline:

    • Quotas: set daily/monthly token budgets by project, by person, and by task type; downgrade to L1 or queue when exceeded;
    • Circuit breaking: on consecutive failures or budget overrun, automatically switch to the lower-tier pipeline and alert;
    • Metrics: record input/output tokens per request, tier hit rate, cache hit rate, retry rate, and cost per task;
    • Attribution: tie cost to a requirement or defect ticket so “which task is expensive” is obvious.

    Pseudocode example:

    1. if budget.used_today > budget.daily_limit * 0.9:
    2. level = "L1"
    3. if metrics.retry_rate > 0.2:
    4. alert("output constraints failing, check schema and prompt")

    7. Common Pitfalls

    1. Downgrading the model indiscriminately: an L3 task downgraded and retried two or three times can raise total cost;
    2. Compressing output but not input: input is usually the larger share;
    3. Sloppy cache key design: ignoring the constraint version returns stale results;
    4. No attribution: you see the monthly total but cannot trace it to a specific task;
    5. Ignoring failure amplification: hidden calls from timeouts and format errors often make up a sizable share of the total.

    8. Rollout Plan (Two Weeks)

    • Days 1–3: instrument usage tracking and produce a report of task types and token distribution;
    • Days 4–6: define L1/L2/L3 decision rules and canary 10% of traffic;
    • Days 7–9: ship semantic caching and output schema constraints;
    • Days 10–12: add budget guardrails, downgrading, and alerts;
    • Days 13–14: review cost per task and quality metrics, then adjust thresholds.

    Conclusion

    The essence of large model call cost is resource matching: spend deep reasoning capability where it is genuinely needed, hand repetitive work to caching and rules, and compress context to just enough. Once routing, caching, constraints, and guardrails are all in place, the bill shifts from “something you learn at month end” to an engineering metric you can tune at any time. For more complete model services and supporting general cloud capabilities such as data, queues, and monitoring and alerting, see the relevant Baidu AI Cloud product documentation.