LLM Selection and Cost Governance: A Practical Guide

    Large language models differ in capability, pricing, and behavior—and both change frequently. This guide explains how to turn model selection from a one-time decision into a continuous engineering process: build your own evaluation dataset, score candidates across quality, format compliance, latency, and cost, route requests across multiple models with fallback logic, and govern spending through token metering, caching, and budget alerts. It also covers rollout practices and common pitfalls to avoid.

    Why Model Selection Is an Engineering Problem

    LLM capabilities evolve rapidly. Different models excel at different tasks: reasoning, code generation, multimodal understanding, or long-context processing. Public benchmarks reflect performance on specific test sets, which may not match your business data. Prices can also change several times within a few months. For these reasons, teams should treat “which model to use” as an ongoing engineering process rather than a one-time decision.

    Common problems in real-world projects include:

    • Depending on a single model provider with no fallback when service is disrupted;
    • Output format or tone changing after a model upgrade, breaking downstream parsers;
    • Token consumption not tracked per project, with overspending only discovered when the monthly bill arrives;
    • High-spec models used for trivial tasks, wasting both compute and money.

    None of these issues are tied to a specific product; they are generic challenges of calling LLM services. The solutions are equally generic: use data for evaluation, architecture for isolation, and metrics for governance.

    Building Your Own Evaluation Dataset

    Public benchmarks are only useful for initial screening. The evaluation data with real reference value comes from representative samples extracted from your production request logs.

    Build your evaluation set as follows:

    1. Classify by business scenario—for example, text summarization, intent classification, code generation, structured information extraction, and multi-turn customer support.
    2. Extract 100–300 real requests per scenario and save them after anonymization. Remove sensitive fields such as phone numbers, ID numbers, and internal system addresses.
    3. Define a judging method for each sample. For tasks with ground-truth answers, use exact matching or rule-based validation; for open-ended tasks, use human review or score with another model, but spot-check with human review to reduce the scoring model’s own bias.
    4. Fix evaluation parameters—sampling temperature, maximum output length, and system prompt version—so results are comparable across models.

    Pseudo-code for the evaluation flow:

    1. for model in candidate_models:
    2. for case in eval_set:
    3. resp = call_model(model, case.prompt, params=FIXED_PARAMS)
    4. record.quality = judge(resp, case.reference) # rule-based or judged
    5. record.format_ok = validate_schema(resp) # output format compliance
    6. record.latency_ms = resp.elapsed_ms
    7. record.cost = input_tokens * in_price[model] + output_tokens * out_price[model]
    8. save(record)
    9. report = aggregate(records, group_by=["model", "scenario"])

    Evaluation results should cover at least the following dimensions:

    • Quality score: accuracy or judged score per scenario;
    • Format compliance rate: whether structured output can be parsed directly downstream;
    • Latency: P50 and P95 response times, with special attention to tail latency;
    • Unit cost: average cost per completed task;
    • Refusal rate: how often the model declines due to safety policies or misinterpretation.

    Setting Scenario-Specific Weights

    Different business scenarios weigh these dimensions differently. Offline batch summarization cares most about unit cost; real-time support cares most about latency and stability; automated data extraction requires near-100% format compliance.

    Define weights per scenario first, then compute a composite score. For example, a real-time conversation scenario might use quality 40%, latency 30%, cost 20%, and stability 10%. Confirm the weights with business owners and adjust them periodically as priorities change.

    One easily overlooked issue: a model with high quality scores but frequent format errors can actually cost more in automated pipelines, because failed outputs need retries or manual fixes. Factor retry cost into total cost when evaluating.

    Multi-Model Routing and Fallback Architecture

    To avoid single-provider dependency, production systems typically add an abstraction layer between the application and model services. Its main responsibilities:

    • Unified access layer: hides differences in request parameters, streaming output, and tool-calling formats across providers, so business code faces a single interface;
    • Routing layer: selects a model based on scenario, cost, and latency requirements;
    • Fallback layer: automatically switches to an alternative model when the primary one times out, gets rate-limited, or returns malformed output;
    • Observability layer: logs calls, latency, and cost, with alerting.

    Manage routing rules in a configuration center so changes don’t require redeployment. Store long inputs and outputs in object storage; use request queues to absorb asynchronous tasks and traffic spikes. Connect logs and metrics to your logging and monitoring/alerting systems for easier troubleshooting.

    Example fallback logic:

    1. def route(task):
    2. policy = routing_config[task.scenario]
    3. for model in [policy.primary, *policy.fallbacks]:
    4. try:
    5. result = call_with_timeout(model, task, timeout_ms=policy.timeout_ms)
    6. if not validate_schema(result):
    7. raise FormatError(model)
    8. return result
    9. except (TimeoutError, RateLimitError, FormatError):
    10. metrics.increment("fallback_triggered", tags={"model": model})
    11. continue
    12. raise AllModelsUnavailable(task.id)

    Two points deserve attention. First, include format validation in the fallback condition—otherwise a model returning an invalid structure will be mistaken for success. Second, validate fallback models with the same evaluation set, so a major quality drop after a failover doesn’t go unnoticed.

    Key Cost Governance Measures

    LLM fees are usually based on input and output token counts. Per-call cost can be estimated as:

    Per-call cost = input tokens × input price + output tokens × output price

    For example, a call with 2,000 input tokens and 500 output tokens, at input price 0.002 yuan per 1K tokens and output price 0.008 yuan per 1K tokens, costs 2 × 0.002 + 0.5 × 0.008 = 0.008 yuan. These prices are only for illustration; actual charges depend on your provider’s pricing documentation.

    Based on this formula, control costs in the following ways:

    1. Usage metering: record input and output tokens by project, user, and scenario, and build a cost dashboard. Metering is the prerequisite for all optimization.
    2. Tiered invocation: use smaller models for simple tasks like classification and keyword extraction; reserve high-spec models for complex reasoning.
    3. Result caching: reuse historical results for identical or highly similar requests, with reasonable expiration. Content involving user private data should not be cached across users.
    4. Prompt slimming: remove repeated instructions and trim irrelevant conversation history, keeping only the context needed for the current task. Long system prompts are billed on every call, so slimming them often yields significant savings.
    5. Output length limits: set a maximum output token count per scenario to prevent verbose responses.
    6. Batch processing: consolidate offline tasks into batches to reduce scheduling overhead and repeated system-prompt costs.
    7. Budget alerts: set daily and monthly cost thresholds; notify owners or automatically switch to a cheaper model when exceeded.

    Rollout and Continuous Evaluation

    Model selection is never a one-time task. Model versions, prompts, and business data all change, so continuous evaluation is required.

    • Canary rollout: route a small share of traffic (e.g., 5%) to a new model or routing rule, compare quality, latency, and cost, then gradually expand if nothing looks wrong.
    • Regression testing: rerun the full evaluation set whenever you change a model version or prompts; only ship if results meet the bar.
    • Version records: keep mappings between model versions, prompt versions, and evaluation results. Providers may silently update models under the same name—version records help trace the cause of output changes.
    • Regular reviews: monthly, adjust routing strategy and weights based on cost reports and quality data.

    Common Pitfalls

    • Relying solely on benchmark rankings while ignoring fit with your own business data;
    • Treating price reduction as the only optimization goal while ignoring rework and labor costs caused by quality regressions;
    • Having no fallback plan, betting the availability of all business functions on a single service;
    • Frequently tweaking prompts without version records, making problems impossible to trace.

    Implementation Checklist

    • Evaluation datasets built per scenario and anonymized;
    • Judging criteria defined for quality, format compliance, latency, and unit cost;
    • Routing and fallback rules designed, with fallback models configured for each scenario;
    • Token metering, cost dashboard, and budget alerts in place;
    • Canary rollout and regression testing processes established;
    • Model versions and prompt versions recorded.