LLM Model Selection and API Cost Optimization: A Practical Guide for Domestic Chinese Models

    This article explains how to select a large language model under real engineering constraints and reduce API costs. Instead of chasing leaderboard rankings, it shows how to build a reproducible evaluation baseline with controlled variables, interpret weighted billing formulas, and measure the right efficiency metrics such as TTFT and effective throughput. It then covers four practical cost optimization techniques—model routing, prefix caching, structured output, and rate limit backoff—and closes with a selection checklist.

    1. Reframing the Problem: Selection Is a Constrained Optimization, Not a Ranking

    Many teams start by asking “which model is the strongest,” which is a poorly-posed question from an engineering standpoint. Real constraints fall into at least four categories: quality (task accuracy, format adherence), latency (time to first token and total completion time), cost (per-request price and monthly budget), and compliance/availability (data residency, rate quotas, service levels). The goal is to find a reproducible, rollback-friendly optimum under these constraints—not to pick whatever tops a leaderboard.

    The approach in the source material is worth borrowing: run a side-by-side load test of multiple models using the same prompts, the same platform, and the same time window, recording elapsed time, input/output tokens, total spend, and throughput. Its value lies not in any specific number but in the method—turning subjective impressions into comparable metrics.

    2. Building a Reproducible Evaluation Baseline

    The first principle of evaluation is controlling variables. Keep the following dimensions fixed:

    • Prompt and decoding parameters: temperature, max output length, and stop conditions held constant;
    • Input shape: system prompt, context length, and number of few-shot examples held constant;
    • Sampling: repeat each prompt N times and take the median and P90 to avoid being misled by single-run jitter;
    • Recorded fields: time to first token, total elapsed time, input/output/cached tokens, and failure rate.

    Illustrative script (pseudocode, structure only):

    1. cases = load_cases("prompts.jsonl") # each entry has a prompt and expected constraints
    2. for model in candidate_models:
    3. for case in cases:
    4. t0 = now()
    5. resp = client.chat(model=model, messages=case.messages,
    6. temperature=0.2, max_tokens=512)
    7. record(latency=now()-t0,
    8. in_tok=resp.usage.prompt_tokens,
    9. out_tok=resp.usage.completion_tokens,
    10. cache_read=resp.usage.get("cache_read", 0),
    11. ok=resp.finish_reason in ("stop", "length"))

    One point deserves emphasis: the evaluation set must reflect the real business distribution. Creative tasks like short-story openings reveal language fluency and instruction following, but they cannot cover the differences in structured extraction, code generation, or long-document Q&A. Sample in layers by business scenario and score four subsets separately: creative, extraction, reasoning, and code.

    3. Understanding the Billing Model: From Unit Price to a Credit Formula

    Platforms generally use weighted billing rather than a single unit price. The general form is:

    1. credits = input_tokens × input_multiplier
    2. + cache_write_tokens × cache_write_multiplier
    3. + cache_hit_tokens × cache_read_multiplier
    4. + output_tokens × output_multiplier

    This formula leads to three key conclusions:

    1. Output costs more than input. For most models the output multiplier is significantly higher than the input multiplier, so “making the model write less filler” is a direct way to save money.
    2. Caching is leverage. The read multiplier for cache hits is usually far below the input multiplier, so a stable system prompt and reuse of long documents can substantially dilute cost.
    3. Long context does not mean linear cost. If the prefix can be cached, the marginal cost of repeated calls drops noticeably; if the prefix changes every time, the cache is invalidated and cost returns to baseline.

    Therefore, the correct metric for cost-effectiveness is cost per unit of useful output = total credits / useful output tokens (or / number of tasks that pass validation), not the sticker price per million tokens.

    4. Using Throughput and Efficiency Metrics Correctly

    The token/s figure that appears in the source material is only system throughput, not the user’s perceived experience. Look at three quantities together:

    • Time to first token (TTFT): determines the responsiveness of interactive applications;
    • Generation rate: determines completion time for long text and code completion;
    • Effective throughput = useful output tokens / total elapsed time: excludes truncated or refused output.

    A common mistake is looking only at total elapsed time. Small models are often faster and cheaper on short-output tasks, while “giant” large models are stronger at complex reasoning but have higher unit cost and lower rate, making them suitable for offline batch processing and low-frequency, high-value requests.

    5. Four Engineering Techniques for Cost Optimization

    5.1 Model Routing and Tiered Fallback

    Route by task difficulty: simple classification and format conversion go to a small model; complex reasoning and long-chain tasks go to a large model; failures or timeouts trigger automatic fallback and retry.

    1. def route(task):
    2. if task.difficulty == "low": return "small-model"
    3. if task.budget_exceeded(): return "small-model"
    4. return "large-model"

    5.2 Prefix Caching and Prompt Layering

    Put the invariant parts (role setup, tool descriptions, output specifications) first as a stable prefix, and the variable parts after. This raises the cache hit rate and lowers input cost accordingly.

    5.3 Output Constraints and Structured Returns

    Constrain output with a JSON Schema or a strict template, combined with validation and retry, to reduce wasted tokens and manual rework. Example:

    1. {"title": "string", "summary": "string", "tags": ["string"]}

    5.4 Rate Limiting, Backoff, and Quota Management

    Platforms often enforce RPM/TPM limits. The client should implement exponential backoff with jitter and keep a local token bucket for quota, avoiding bursts that trigger 429s:

    1. try:
    2. return call_model(payload)
    3. except RateLimited:
    4. sleep(backoff(attempt++)) # exponential backoff + random jitter

    6. Selection Decision Checklist

    • Quality: pass rate on the layered evaluation set plus human spot-check scores;
    • Cost: cost per unit of useful output, including caching benefits;
    • Latency: TTFT and generation rate each meeting their targets;
    • Stability: whether rate limiting, failure rate, and fallback paths are complete;
    • Operability: whether logs, monitoring/alerting, and cost accounting are observable.

    If your organization already uses Baidu AI Cloud’s model services and related cloud products, you can combine log services, monitoring/alerting, and object storage to accumulate evaluation data, forming a continuously iterable selection pipeline that turns a one-off load test into a long-term, regression-ready engineering asset.

    7. Conclusion

    Selection is essentially a measurable engineering decision. First use a controlled-variable script to obtain clean data, then replace intuition with the weighted billing formula and unit-cost metrics, and finally use routing, caching, structured output, and backoff/retry to bring cost within budget. Models will be replaced; the methodology is reusable.