LLM API Cost Optimization and Model Selection: A Practical Guide

    This guide explains why a lower price per token does not always mean lower total cost, and how engineering teams can control LLM API spending. It covers measuring cost per accepted output, tiering tasks by failure impact, understanding input/output pricing and prefix caching, scheduling non-real-time workloads into off-peak windows, and building observability around retry rates. The goal is a reusable cost structure that stays stable as model prices and promotions change.

    1. The Problem: Why “Cheap” Is Not the Same as “Cost-Effective”

    The core question is how to keep experimentation affordable while models keep improving, and how to turn occasional discount windows into a cost structure you can reuse over the long term. Two concepts that are easy to confuse need to be separated first.

    • Low unit price: a lower listed price per million tokens.
    • Low total cost: less money spent to achieve the same business outcome.

    The two often diverge. A model with a lower listed price may follow instructions poorly, require repeated retries, or need longer context fed in again and again, so the actual cost per task can end up higher. The more reliable engineering approach is to introduce a metric for cost per accepted output:

    1. cost per accepted output = (input tokens × input price + output tokens × output price) / accepted tasks

    The “accepted” part of the denominator is critical. It can be the unit test pass rate, the validation pass rate for structured output fields, or the number of samples that pass manual review. Only when retries and rework are counted in the denominator does model selection become comparable.

    2. Tier Tasks Before Choosing Models

    In most teams, runaway cost is not caused by unit price but by routing every request to the strongest model. A better approach is to tier by cost of failure rather than technical difficulty:

    Tier Typical tasks Cost of failure Suggested strategy
    L0 Text rewriting, tag extraction, format conversion Very low Small models or a rules engine as fallback
    L1 Code completion, unit test generation, document summarization Low to medium Mid-size general-purpose model, retries allowed
    L2 Cross-file refactoring, browser/frontend integration debugging Medium Multimodal and long-context models
    L3 Production incident triage, compliance review High Strongest model plus human review

    The direct payoff is that L0 and L1 usually account for the vast majority of request volume. Moving those two tiers off the flagship model reduces cost far more than shaving the unit price on L3.

    3. Break Down the Billing Structure: The Input/Output Ratio Is the Lever

    Mainstream inference services bill along two axes: by token volume, or by quota included in a plan (credits or points). Either way, three variables matter:

    1. The input-to-output price ratio. Output is usually several times the price of input, and agent-style tasks generate far more output tokens than chat scenarios.
    2. Context reuse. If the service supports a prefix caching mechanism, keeping the system prompt, tool definitions, and long documents at the front can significantly reduce repeated billing.
    3. How quota is distributed over time. Some plans split quota by cycle and unused quota does not roll over, which is effectively a price increase.

    For the second point, a portable engineering convention is to order request content by how stable it is:

    1. def build_messages(system_spec, tools, history, user_input):
    2. # More stable content goes first, which helps prefix cache hits
    3. return [
    4. {"role": "system", "content": system_spec},
    5. {"role": "system", "content": f"tools={tools}"},
    6. *history,
    7. {"role": "user", "content": user_input},
    8. ]

    Also compress the output: have the model return only a diff, or only the function bodies that need to change, instead of rewriting whole files. In agent scenarios, saving more than 30% on the output side is often more effective than switching models.

    4. Design Limited-Time Windows as a Scheduling Strategy, Not a One-Off Grab

    Night-time quota doubling and limited-time discount plans are the same phenomenon in the abstract: the provider releases spare capacity during low-demand periods. The engineering response is not to patch code temporarily, but to build a configurable off-peak queue:

    1. priority queue + time-window routing
    2. ├─ non-real-time tasks (batch refactoring, log clustering, regression case generation) → scheduled into off-peak windows
    3. ├─ real-time tasks (interactive completion, online Q&A) → regular channel
    4. └─ fallback path: automatically switch to a backup model when the primary channel is throttled, and record the degradation event

    Three guardrails are needed alongside it:

    • Budget guardrail: set token caps per day or per project, and degrade automatically at the threshold instead of hard-stopping.
    • Quality guardrail: sample and validate outputs, and roll back routing weights when the pass rate drops below baseline.
    • Elasticity guardrail: abstract a unified call layer so business code is not bound to a single interface shape.

    A minimal implementation of the unified call layer:

    1. class ModelRouter:
    2. def __init__(self, providers):
    3. self.providers = providers # each item has name/cost/quota_window
    4. def pick(self, task_level, now):
    5. for p in self.providers:
    6. if p.can_serve(task_level, now):
    7. return p
    8. raise RuntimeError("no available provider")
    9. def call(self, task_level, payload, now):
    10. p = self.pick(task_level, now)
    11. r = p.client.chat(payload)
    12. emit_metrics(task_level, p.name, r.usage) # observability
    13. return r

    With this layer in place, any limited-time promotion is just a configuration change and requires no release.

    5. Observability: No Measurement, No Optimization

    Collect at least four metrics: request volume per task category, input/output token distribution, retry rate, and cost per accepted output. Retry rate is the most easily overlooked cost sink, because it inflates both input and output consumption. If a task category has a retry rate consistently above 20%, improve the prompt and tool descriptions first rather than switching to a more expensive model.

    6. Suggested Rollout Order

    1. Week one: wire up the unified call layer and instrumentation to get the real token distribution.
    2. Week two: move L0/L1 down to cheaper models, compress output, and stabilize the prefix.
    3. Month one: build the off-peak queue and budget guardrails, and establish a monthly cost baseline.
    4. Ongoing: re-evaluate quarterly using cost per accepted output; models flow with the windows while the architecture stays unchanged.

    The conclusion is not complicated: real cost advantage comes from combining task tiering, an understanding of billing structure, and scheduling elasticity. Any single promotion is only an accelerator. Make these three things infrastructure, and the team no longer has to redo model selection every time prices move. If you already use model services on Baidu AI Cloud, the same advice applies: build the measurement and scheduling loop above on general-purpose capabilities (log service, monitoring and alerting, message queue, container platform) and keep it decoupled from any specific model.