LLM Selection: How to Scientifically Evaluate Capability, Cost, and Stability
Choosing a large language model (LLM) is a multi-objective engineering problem, yet teams often reduce it to leaderboard scores, a few casual chat tests, or the lowest price per token. This article presents a practical framework for evaluating LLMs across three dimensions—capability, cost, and stability—using quantifiable, reproducible, and continuously updatable methods. It explains how to break business tasks into capability dimensions, build layered private evaluation sets, and design measurable scoring with automated metrics, rule checks, and model-as-judge. It then introduces a cost model based on cost per 1,000 effective calls that accounts for hidden expenses such as retries and invalid outputs, along with stability testing through load testing, canary releases, and provider abstraction. The article closes with engineering governance practices and common evaluation pitfalls to avoid.
Introduction: Selection Shouldn’t Rely on Gut Feeling
As generative AI moves into large-scale production, more and more teams face the same question: LLM services keep iterating, with different version names, capability positioning, and pricing models—so which one should we choose?
The question looks simple, but in practice it often gets reduced to a few shortcuts:
- Referencing public leaderboard scores;
- Casually trying a few prompts in a chat interface;
- Picking whichever vendor advertises the most features at the lowest price.
None of these are worthless, but each has clear limitations:
- Public leaderboards reflect general capability, which may not match the real distribution of your business scenarios;
- Subjective impressions are easily swayed by a few “highlight” answers and are hard to compare across candidates;
- Comparing unit prices alone ignores hidden costs and capacity bottlenecks.
Many teams have run into an awkward situation: a paid subscription service becomes heavily queued, so to use up the remaining quota, they force it into production as a fallback model, reserved for low-value “filler” tasks. This is exactly the point—without clear evaluation criteria, model selection easily degenerates into passive adaptation to bundles, credits, or freebies, rather than serving business goals.
This article evaluates no specific product. Instead, it addresses a general engineering problem: how to build a quantifiable, reproducible, and continuously improvable LLM evaluation system. Starting from three dimensions—capability, cost, and stability—it lays out complete evaluation methods, code examples, and implementation recommendations.
1. Three Evaluation Dimensions: Capability, Cost, and Stability
Model selection is essentially multi-objective trade-off, and evaluation should cover at least the following three dimensions:
| Dimension | Core Question | Example Key Metrics |
|---|---|---|
| Capability | Can the model complete business tasks accurately? | Task pass rate, output quality score, structured-output compliance rate, hallucination rate |
| Cost | What does it cost to produce one unit of business output? | Average input/output length, cost per 1K calls, share of invalid calls, overall cost-effectiveness |
| Stability & Engineering | Can it stay available under high concurrency and integrate smoothly? | Time-to-first-token latency (P95), output throughput, rate limiting and error rate, protocol compatibility |
Tension often exists among these three. Larger models usually perform better but have higher latency and cost more per call; models with strong long-context ability handle long documents more easily but push up costs when you “stuff everything into the context.” So the goal of evaluation isn’t to find the “strongest model,” but to find the model with the best overall performance under given business constraints.
2. Capability Evaluation: From Gut Feeling to Quantifiable Metrics
2.1 Break Down Business Tasks and Define Capability Dimensions
General-purpose LLM capability can be broken into several foundational dimensions and mapped to concrete business needs:
- Language understanding and generation: semantic understanding, summarization, rewriting, multilingual processing;
- Reasoning: logical reasoning, numerical computation, multi-step problem decomposition;
- Long-context handling: locating information in long documents, integrating information across sections, retaining information in very long conversations;
- Instruction following: strictly obeying format, length, tone, and constraint requirements;
- Structured output: validity of JSON, tables, and other structured results, and completeness of fields;
- Tool calling and code ability: generating function parameters, code generation and completion, error localization.
Take a customer-service scenario: intent recognition tests understanding and short-text classification; answer generation tests factual accuracy (i.e., hallucination control); ticket creation tests structured output; order lookup tests tool calling. Different dimensions place different demands on the model, so selection should prioritize the steps in the business flow with the highest weight and lowest fault tolerance.
2.2 Build a Layered Private Evaluation Set
Public evaluation sets are only a reference; the real value lies in a business-oriented private evaluation set, which I recommend building in three layers:
- Core layer (gold set): 100–300 high-frequency, typical samples with clear reference answers, used for fast regression;
- Extended layer: samples covering long-tail scenarios, edge conditions, and multi-turn conversations, used to uncover capability gaps;
- Adversarial layer: deliberately designed trap questions—ambiguous instructions, extremely long inputs, leading questions, conflicting constraints—used to test robustness.
When building the set, keep three points in mind:
- Real samples: drawn directly from anonymized production logs or real business tickets, to avoid artificially “authored” questions that drift from the real distribution;
- Judgeable labels: each sample comes with a reference answer or clear scoring rules, reducing subjective disagreement;
- Continuous updates: as model versions and business change, the set should keep growing from accumulated production issues.
2.3 Design a Quantifiable Scoring Method
Evaluation methods can combine these three approaches:
- Automated metric comparison: for tasks with definite answers and fixed formats (classification, extraction, transformation, etc.), use metrics like accuracy, F1, and exact-match rate directly—low cost and repeatable;
- Rule-based checks: use programs to verify whether output meets constraints, e.g., whether JSON parses, whether fields are complete, whether enum values are valid, whether length is within limits;
- Model-as-judge: for open-ended text, a stronger model that is independent of the candidate models can act as a “judge” and score against predefined criteria. Because this method’s scoring has some variance, it’s advisable to sample multiple times and average, and periodically validate consistency against human-labeled results.
All evaluations should follow the same reproducible protocol:
- Fix the random seed;
- Set sampling temperature to 0 or close to 0;
- Fix the system prompt and maximum generation length;
- Define pagination or character-truncation strategy explicitly;
- Fully record model name and version, call time, and token consumption at each stage.
2.4 A Reusable Evaluation Code Example
The example below uses Python and the common requests library to provide a reusable evaluation framework skeleton. The service address and key are placeholders; the interface follows a generic chat-completion style, so you only need to adjust it to the target platform’s documentation when integrating.
import timeimport jsonimport requestsBASE_URL = "https://<service-url>/v1" # Placeholder; replace with the actual service URLAPI_KEY = "<your-api-key>" # Placeholder; inject via environment variables when possibledef call_model(model: str, messages: list, temperature: float = 0.0,max_tokens: int = 1024, retry: int = 2) -> dict:"""Unified model-call wrapper; returns text and key metrics."""payload = {"model": model, # Model name/version"messages": messages,"temperature": temperature, # Set to 0 for evaluation to ensure reproducibility"max_tokens": max_tokens,}for attempt in range(retry + 1):start = time.perf_counter()try:resp = requests.post(f"{BASE_URL}/chat/completions",headers={"Authorization": f"Bearer {API_KEY}"},json=payload, timeout=60,)resp.raise_for_status()data = resp.json()return {"text": data["choices"][0]["message"]["content"],"ttft": time.perf_counter() - start, # Approximate time to first token"usage": data.get("usage", {}),}except Exception:if attempt == retry:raisedef evaluate(model: str, dataset: list) -> dict:"""Run a single model on the evaluation set and return aggregated metrics."""total = {"passed": 0, "prompt_tokens": 0, "completion_tokens": 0}latencies = []for case in dataset:messages = [{"role": "system", "content": case.get("system", "You are a rigorous assistant.")},{"role": "user", "content": case["prompt"]},]result = call_model(model, messages)passed = case["check"](result["text"]) # Business-defined check functiontotal["passed"] += int(passed)usage = result["usage"]total["prompt_tokens"] += usage.get("prompt_tokens", 0)total["completion_tokens"] += usage.get("completion_tokens", 0)latencies.append(result["ttft"])print(f"{model} | case={case['id']} | pass={passed} | ttft={result['ttft']:.2f}s")n = len(dataset)latencies.sort()return {"model": model,"pass_rate": round(total["passed"] / n, 4),"avg_prompt_tokens": round(total["prompt_tokens"] / n, 1),"avg_output_tokens": round(total["completion_tokens"] / n, 1),"p95_ttft": round(latencies[int(n * 0.95) - 1], 2),"avg_cost": round((total["prompt_tokens"] * PRICE_IN+ total["completion_tokens"] * PRICE_OUT) / n / 1000, 4),}
Note:
PRICE_INandPRICE_OUTrepresent the input and output unit prices per 1K tokens, which should follow the provider’s current official pricing;case["check"]is the check function configured for each sample—it can be an exact match, a rule check, or a model-as-judge.
With this framework, you can put candidate models through the same evaluation set for a side-by-side comparison, output a unified metrics table, and provide an objective basis for the decision.
3. Cost Evaluation: From “Quota Consumption” to “Cost per Unit of Effective Output”
3.1 Understand the Billing Dimensions
LLM service billing generally revolves around tokens, and while the exact accounting differs slightly across providers, it typically includes the following dimensions:
- Input tokens and output tokens are priced separately, with output usually costing more than input;
- Some models price long-context or specific capabilities separately;
- Resources are distributed as bundles, vouchers, or free quotas, usually with validity periods and scope of use.
Many teams lose control of cost not because unit prices are high, but because they lack a sense of token consumption. In Chinese, roughly one character corresponds to more than one token after tokenization, though the exact number varies by tokenizer. An input that includes a system prompt, business rules, reference documents, and conversation history can reach thousands of tokens; passing all of it on every call makes costs add up fast.
3.2 Identify Hidden Costs
Beyond the visible call fees, evaluation should also account for the following hidden costs:
- Queuing and retry costs: waiting in line during peak hours, plus retries triggered by timeouts and rate limits, all generate extra calls and extra fees;
- Invalid-output costs: output that violates the format, gets truncated, or misses the point is still billed but produces no business value;
- Sunk credit costs: low-value calls scheduled just to “use up remaining quota” consume allocation and team attention without delivering proportional returns;
- Migration and rework costs: different models differ in interface protocol, parameter semantics, and context-length limits, so switching models often requires reworking code and prompts;
- Operations and governance costs: supporting work such as logging, monitoring, evaluation, and data anonymization all require ongoing investment.
3.3 Build a Cost Model
When evaluating cost, I recommend replacing “price per 1K tokens” with “cost per 1K effective calls,” calculated as follows:
cost per effective call = (avg input tokens × input price + avg output tokens × output price) × (1 + retry factor)────────────────────────────────────────────────────────────────────────────task success ratecost per 1K effective calls = cost per effective call × 1000
Where:
- retry factor = number of retries ÷ number of first calls, obtainable from load testing or production statistics;
- task success rate = calls passing quality checks ÷ total calls.
This metric unifies “quality” and “cost” under the same measure: a model with a low success rate may look cheaper per token, but its effective cost is actually higher.
The following uses a set of hypothetical values to illustrate the calculation (not data from any real product):
Assume a simple text-processing task averages 500 input tokens and 200 output tokens, and candidates A and B perform as follows:
| Candidate | Input price ($/1K tokens) | Output price ($/1K tokens) | Task success rate | Retry factor | Cost per effective call ($) |
|---|---|---|---|---|---|
| A | 0.001 | 0.002 | 95% | 0.10 | ~0.00079 |
| B | 0.004 | 0.008 | 99% | 0.03 | ~0.00284 |
Model A is clearly cheaper per call and suits large-scale, low-fault-tolerance scenarios; Model B is more expensive but has a higher success rate and fewer retries, making it suitable for steps with strict result requirements. In real selection, you can fully adopt a “lightweight model for simple tasks, stronger model for critical tasks” tiered-routing strategy that balances cost and quality.
3.4 Cost Optimization Practices
Once the cost model is clear, you can optimize in several ways:
- Context governance: inject only the needed knowledge snippets rather than full documents, summarize and compress conversation history, and fix stable system prompts to avoid repeated transmission;
- Prompt trimming: remove redundant examples and duplicate instructions, cutting both input tokens and the chance of the model being distracted by irrelevant information;
- Limiting output length: set the maximum generation length reasonably based on business needs, avoiding verbose answers that raise output costs;
- Tiered routing: assign requests to models of different sizes based on task complexity and importance;
- Structured caching: build a cache for high-frequency, deterministic queries and return directly on a hit to reduce repeated calls;
- Resource-expiry management: keep a ledger for time-limited resources such as credits, vouchers, and free quotas, with clear validity periods and applicable scenarios, and use them only where they genuinely match business needs—avoid consuming quota for the sake of consuming quota.
4. Stability Evaluation: Real Performance Under High Concurrency
Many teams have a good experience during testing, only to find the service “unusable” at peak after launch. The cause is often that test traffic is far below real traffic. Stability evaluation should cover:
- Latency: track the percentiles (e.g., P95, P99) of time to first token and end-to-end latency, not just the average;
- Throughput: requests handled per unit of time, and whether it can support the business peak;
- Error behavior: how often errors like rate limiting, timeouts, and service unavailability occur, and how they recover;
- Quota mechanisms: whether per-minute request limits, concurrency caps, daily token limits, etc., meet the business plan;
- Version consistency: whether output drifts after a model upgrade, and whether you can pin a specific version to keep results stable.
For validation, I recommend first running progressive load tests with a local script at a fraction of the business peak, observing how latency and error rate change as concurrency rises; after launch, pair it with a canary release that shifts a small amount of real traffic to the new model, continuously monitor core metrics, and then scale up gradually.
import concurrent.futuresdef stress_probe(model: str, concurrency: int = 20, rounds: int = 3) -> None:"""Run a small-scale load test at a given concurrency and report the error rate."""probe = [{"role": "user", "content": "Explain what a database index is in one sentence."}]errors = 0with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:futures = [pool.submit(call_model, model, probe) for _ in range(concurrency * rounds)]for f in concurrent.futures.as_completed(futures):try:f.result()except Exception as e:errors += 1print("request failed:", type(e).__name__)total = concurrency * roundsprint(f"model={model} | concurrency={concurrency} | total requests={total} | "f"failed={errors} | success rate={1 - errors / total:.2%}")
In addition, considering vendor lock-in risk, the integration layer should provide abstraction and isolation: wrap model calls behind a unified internal gateway and consolidate differences in model names, parameters, and protocols into a configuration layer. This way, switching models requires no changes to business code, and it also reduces the business risk when a single vendor faces capacity constraints or policy changes.
5. Engineering Governance: Keeping Evaluation Effective Over Time
LLM capabilities iterate quickly, and the conclusions of a one-off evaluation soon become outdated, so evaluation needs to become a continuously running engineering process:
- Evaluation automation: plug the core evaluation set into a continuous-integration pipeline, automatically trigger regression tests when a model version changes, and output quality-metric comparison reports;
- Effect monitoring: after launch, continuously track success rate, retry rate, user feedback, average token consumption, etc., and alert promptly when quality degrades;
- Data flywheel: feed low-quality production samples, user downvotes, and human-correction results back into the evaluation set, forming a closed loop of “evaluate—improve—re-evaluate”;
- Data security and compliance: anonymize or minimize transmission of sensitive information before calls, define data-use and retention policies, and choose providers with proper compliance credentials.
If you use a one-stop LLM platform such as Baidu AI Cloud Qianfan, you can also access multiple models through a unified interface on the same platform, complete side-by-side comparisons with the same evaluation set, and use the platform’s monitoring and logging capabilities to track call quality and cost over time. This simplifies multi-model integration while making it easier to accumulate evaluation data and experience over the long term.
6. Common Evaluation Pitfalls
- Blindly trusting leaderboard scores: when leaderboard tasks don’t match the business distribution, a high score doesn’t mean it works well;
- Looking only at input unit price: the overhead from output tokens, retries, and context expansion is often the real cost driver;
- Ignoring the latency distribution: averages hide the long-tail latency at peak, and experience problems often show up at P95 and P99;
- Too few or static evaluation samples: a few dozen samples can’t reflect the real distribution, and never updating them disconnects the set from the business;
- Evaluating once and deciding for good: model versions and business needs both change, so a regression mechanism is essential;
- Calling just to use up quota: remaining or gifted quota is essentially a sunk resource and should not be the basis for a technical decision.
Conclusion
LLM selection is an engineering effort requiring ongoing investment, not a one-off procurement decision. A reliable evaluation system should include three elements:
- Capability: replace subjective impressions with a business-relevant private evaluation set and quantitative scoring;
- Cost: use “cost per unit of effective output” as the core measure, accounting for both visible and hidden expenses;
- Stability: use load testing, canary releases, and abstraction/isolation to safeguard the production experience and reduce vendor lock-in risk.
When selection is built on reproducible, trackable data, teams can truly turn LLMs into a stable, controllable productivity tool—rather than passive users led around by bundles, credits, or queues.
