LLM Model Selection and Cost Optimization: A Practical Guide

    This guide explains why cost becomes the main variable once large language models reach a usable capability level, and how engineering teams can control it. It covers building a trustworthy evaluation baseline, replacing one-size-fits-all model calls with tiered routing, compressing input and output tokens, batching and retry governance, and treating cost as a first-class observability metric. It closes with a four-stage rollout path and the goal of a repeatable cost engineering system rather than simply the cheapest model.

    1. The Real Issue: When Capabilities Converge, Cost Becomes the Main Variable

    A common pattern shows up in practical engineering evaluations. The same structured table generation task is given to several different large language models. The outputs all meet requirements for field completeness, format compliance, and content accuracy, and the scores are identical. Yet when the bill arrives, consumption can differ by several times.

    This means that once basic capability crosses the “usable line,” the real differentiator is no longer whether a model can do the job, but how much resource cost it takes to do it.

    The difference is not mysterious. It comes mainly from four factors:

    • Different parameter sizes and inference path lengths across models
    • Different default output lengths and degrees of chain-of-thought expansion
    • Different context window filling strategies
    • Different invocation modes (streaming vs. non-streaming, batch vs. real-time)

    Understanding these four points is the prerequisite for every optimization technique that follows.

    2. Build a Trustworthy Evaluation Baseline Before Optimizing

    For many teams, the root of their cost problem is the absence of a baseline. Without one, there is no way to tell whether “savings” are genuine optimization or a regression in output quality. The recommended steps for building an evaluation set are:

    1. Task tiering: split business requests into five categories — extraction, rewriting, generation, reasoning, and code. Prepare 30–100 real samples per category, covering edge cases such as long text, multi-field inputs, and ambiguous input.
    2. Metric definition: on the quality side, use field accuracy, format compliance rate, and manual spot-check pass rate; on the cost side, use average input tokens, average output tokens, total consumption per task, and P95 latency.
    3. Dual-track recording: log the quality score and the consumption value together for every evaluation run. Only a two-dimensional distribution plot makes the “cost-performance inflection point” visible.

    A simplified structure for evaluation records looks like this:

    1. {
    2. "task_type": "structured_extraction",
    3. "model_profile": "mid_size_fast",
    4. "input_tokens": 1840,
    5. "output_tokens": 620,
    6. "accuracy": 0.98,
    7. "latency_ms_p95": 2100
    8. }

    Here model_profile uses abstract tiers (small/medium/large, fast/accurate) instead of concrete model names, so the evaluation criteria stay stable when the underlying model is swapped.

    3. Replace One-Size-Fits-All With Tiered Routing

    One of the core cost optimization techniques is to send simple requests down a lightweight path and escalate only complex ones. Strategies that can be implemented include:

    • Rules first: whatever can be handled by regular expressions, templates, or database queries never enters a model call. In table tasks, header mapping, unit conversion, and date normalization all fall into this category.
    • Confidence routing: a lightweight model produces a result with a self-assessed confidence score; if the score falls below a threshold, the request is handed to a higher-capability model for review.
    • Semantic caching: for high-frequency similar requests, use vector recall; when a similar sample is hit, reuse the historical result and run field-level validation.
    1. def route(req):
    2. if req.rule_hit:
    3. return rule_engine.solve(req)
    4. r = light_model.invoke(req)
    5. if r.confidence < 0.75:
    6. return strong_model.invoke(req, hint=r.draft)
    7. return r

    This structure typically keeps most traffic on the low-cost path without sacrificing accuracy.

    4. Compress Input and Output: The Most Direct Cost Lever

    On the input side: remove redundant system prompts, merge duplicated context, and summarize long documents in segments before sending them to inference. Turn stable explanatory content into a concise template instead of repeating long passages on every call.

    On the output side: explicitly require only the necessary fields and limit explanatory text. For structured tasks, agree on a compact format first (such as compact JSON or a delimiter-separated table) to avoid extra whitespace and duplicate keys.

    1. Requirement: output JSON only, no explanation; use null for missing fields; keep two decimal places for numbers.

    A single constraint like this can noticeably reduce output tokens, and output tokens are usually the more expensive part of billing.

    5. Batching, Async Processing, and Retry Governance

    • Batching: merge deferrable tasks into batches and use the throughput advantage of batch interfaces to spread unit cost.
    • Async processing: decouple non-real-time pipelines through a message queue to smooth peaks and valleys, avoiding over-provisioning quota for peak load.
    • Retry governance: set exponential backoff and a maximum retry count for timeouts and rate limits, so failed requests do not repeatedly consume quota; intercept inputs that can be determined to fail early.

    6. Observability: Treat Cost as a First-Class Metric

    No monitoring means no optimization. Collect input/output tokens, model tier, cache hit or miss, and retry count for every call in a unified way, and set a per-task cost threshold in monitoring alerts. When the cost curve rises, investigate three issues first: prompt bloat, repeated context filling, and amplified retries from failures.

    7. Suggested Rollout Path

    Stage one: establish the baseline and instrumentation. Stage two: add rules-first handling and output constraints. Stage three: introduce tiered routing and semantic caching. Stage four: apply batching and quota governance. Baidu AI Cloud can support the engineering components required by each stage through general capabilities such as model services, container platforms, message queues, log services, and monitoring alerts, and teams can combine them freely according to their own architecture.

    The end goal is not to find the “cheapest model,” but to build a sustainable cost engineering system: measurable quality, routable paths, attributable consumption, and alertable anomalies. With these four in place, saving quota at equal quality stops being an occasional result and becomes a repeatable engineering capability.