LLM Evaluation and Selection Methodology: From Task Quality to Cost Governance
Most LLM evaluation still relies on public benchmark rankings or subjective hands-on impressions, leaving developers to deal with problems like "task completion is acceptable, but quota drains too fast and latency spikes at peak hours." This article presents a practical framework that covers quality, stability, and cost: validate effectiveness with a purpose-built, scenario-specific evaluation set and paired comparisons; handle queuing and rate limiting with load testing and retry backoff; control cost through context compression, cache reuse, budget guardrails, and tiered routing; and continuously recalibrate through an evaluation pipeline, canary releases, and observability. The goal is to help developers make verifiable, auditable engineering decisions during both selection and deployment.
Introduction: It Starts With “Burning Through Your Quota”
Picture a typical scenario. You have a balance of short-term credits that are about to expire. At peak hours your API calls keep getting queued, so the experience is sluggish. You decide to spend the credits on one or two complex tasks, and the balance is gone almost immediately.
This looks like a personal habit, but it captures three common problems in real-world LLM adoption:
- Cost: Call costs grow linearly or even faster with context length, call count, and output length. Without budget constraints, spending can spiral out of control easily.
- Capacity: Inference service capacity is limited. During peak hours, requests queue up, get rate-limited, or even time out, directly hurting availability.
- Evaluation: “Can it do the job” and “is it worth doing” are two different questions. With only subjective impressions and no quantifiable evaluation, it is easy to overestimate capability during selection and only discover uncontrollable costs at deployment.
So answering “how do you evaluate a large language model” should not stop at surface-level impressions like “is the answer fluent” or “is the writing elegant.” Instead, build a quantifiable evaluation system covering task quality, service stability, and resource consumption, and embed it into both selection and day-to-day operations. This article follows that line of thinking across six areas: metric design, evaluation methods, stability validation, cost governance, tiered routing, and engineering implementation.
1. Building the Evaluation Foundation: Metric Design
1.1 A Four-Dimensional Metric System
Design metrics across four dimensions. For each metric, define the calculation method, the collection point, and the aggregation period to avoid “same name, different meaning”:
| Dimension | Core question | Representative metrics | Collection method |
|---|---|---|---|
| Quality | Is the task done correctly and well? | Task success rate, key-field accuracy, first-pass rate, human preference win rate | Offline evaluation set + online business metrics + manual spot checks |
| Stability | Can it stay available at peak load? | Request success rate, error rate, time to first token, end-to-end latency (P50/P95/P99) | Load testing + production monitoring |
| Cost | How much does it cost to complete one unit of work? | Input/output tokens per task, cache hit rate, cost per task, cost variance rate | Usage log aggregation |
| Controllability | Is behavior predictable and constrainable? | Structured-output compliance rate, timeout rate, rate-limit trigger rate, guardrail block rate | Gateway logs + output validation |
One point deserves special emphasis: task success rate should be measured alongside cost. Looking at “Model A has a higher success rate” in isolation may simply reflect that its average output length is twice that of Model B. A more reasonable comparison is “task success rate per unit cost” — that is, cost-effectiveness.
1.2 First-Pass Rate: Distinguishing “Interactive Calls” From “Machine-Consumed Calls”
Different call patterns define quality differently:
- Interactive calls (such as a chat assistant): Users face a continuous multi-turn conversation and care about the overall experience and context coherence. A single badly broken turn can make a user abandon the entire session.
- Machine-consumed calls (such as batch structured-data generation or tool calls): Results must be parsed and used directly by a program, and any single failure can break the downstream flow.
Therefore, for interactive scenarios, prioritize session-level success rate; for machine-consumed scenarios, make first-pass rate (pass@1) the core metric. Be careful here: if the evaluation allows the same request to be retried multiple times and counts it as success as long as one attempt passes, it will significantly overstate real-world performance. Unless the business itself implements an automatic retry mechanism, first-pass rate is the right standard.
2. Quality Evaluation: From “Feels Good” to Verifiable
2.1 Building a Scenario-Specific Evaluation Set
Public leaderboards use generic questions whose distribution often differs greatly from your real business tasks. Build your evaluation set on these principles:
- Scenario fit: Questions come from real business requests and cover the main intent categories seen in production.
- Stratified sampling: Sample across task types (Q&A, summarization, extraction, classification, code generation, tool calls, etc.) and difficulty levels (easy, medium, hard), with each stratum’s sample size roughly matching its share of live traffic.
- Reasonable difficulty mix: When every question is easy, most models score near the top and the evaluation loses discriminative power. Deliberately keep a certain proportion of long-tail, ambiguous, and counterintuitive cases.
- Labeling standards first: For each question, provide the input, a reference answer or scoring rubric, and the scoring dimensions. For open-ended questions, use a scoring rubric rather than a single reference answer.
- Version control: Put the evaluation set under version control with version numbers and change notes. Also maintain a held-out set that is not used for day-to-day tuning, to prevent overfitting to the evaluation set.
- Continuous expansion: Feed desensitized production failure cases back into the set, forming a “discover problem — add sample — regression-verify” loop.
2.2 Paired Comparisons and Statistical Significance
When comparing models, a common mistake is to “run it once and compare total scores.” Prefer paired comparisons, following these steps:
- Feed the same set of evaluation questions to different models, keeping run parameters as consistent as possible (temperature, maximum output length, and prompt template).
- For each question, compute a difference value (such as the accuracy gap) and record each model’s score sequence.
- Use a paired test (such as the sign test or the Wilcoxon signed-rank test) to determine whether the difference is statistically significant, and report a confidence interval.
- If the difference is not significant, do not draw conclusions from just one or two high-scoring cases.
Sample size matters too. If two models differ by only a few percentage points in true accuracy, you need a large enough evaluation set to distinguish them reliably. As a rough estimate, treating the compared accuracy as an estimate of the population proportion, the sample size needed for about ±5% margin of error at a 95% confidence level is roughly:
n ≈ 1.96² × p × (1 - p) / 0.05²Example (illustrative only, not real evaluation data):p = 0.5, n ≈ 384p = 0.8, n ≈ 246p = 0.9, n ≈ 138
In practice, add some headroom on top of this and reserve samples for stratified analysis.
2.3 Using a Model as Judge: It Works, but Calibrate It
For open-ended tasks that are hard to score automatically, you can let a model act as a judge, scoring dimensions such as correctness, completeness, and format compliance one by one. But keep in mind:
- Judge consistency: The same content may score differently across repeated judgments. Fix the judge prompt, and if needed, run multiple judgments and take the median or majority vote.
- Same-family bias: If the judged model and the judge model come from the same model family, the results may show a systematic preference. Choose a judge model from a different source than the models being judged.
- Position bias: In pairwise comparison, the judge may prefer answers placed first or last (especially longer ones). Randomly swap the A/B order and correct for length differences.
- Manual spot-check calibration: Periodically have humans review a sample and compute the agreement rate between the judge and human judgments. When agreement is low, fix the judge prompt first rather than trusting the judge’s results directly.
2.4 Capability-Boundary Tests
Beyond general performance, run targeted tests on capabilities that tend to “break”:
- Long context: Embed key information in a long document and test whether the model can locate and cite it accurately. Watch whether quality drops noticeably as context approaches the limit.
- Multi-step reasoning: Design calculation and logic problems that require multiple reasoning steps, and ask for intermediate steps so you can pinpoint where it goes wrong.
- Instruction following and constraint satisfaction: Set multiple constraints in the prompt (word limits, output format, forbidden content, etc.) and measure the proportion of cases where all constraints are met at once.
- Structured output: Require JSON that conforms to an agreed schema, and measure parse success rate and field completeness. When the model supports structured-output constraints, enforce validation at the gateway; responses that fail validation should not be passed straight through to the business.
- Tool calling: Verify parameter-extraction accuracy, coherence of context across multi-turn calls, and recovery ability after a failed call.
- Robustness and safety: Add perturbation samples such as typos, colloquial phrasing, and injection attacks (e.g., embedding “ignore the above instructions” in user input), and verify output stability and the effectiveness of safety guardrails.
2.5 Qualitative Dimensions: Human Evaluation Is Still Essential
Some quality dimensions are hard to measure automatically, such as whether the tone is appropriate, whether explanations are easy to understand, and whether the output follows brand-expression guidelines. Here you can use pairwise comparison or a five-level Likert scale with a clear scoring standard. For example:
- 5: Fully correct and complete, clearly expressed, meets all constraints;
- 4: Overall correct, with minor redundancy or small flaws;
- 3: Partially correct, with key information missing or off;
- 2: Contains obvious errors and needs substantial human correction;
- 1: Seriously wrong or unusable.
To reduce subjective variance between annotators: run unified training with examples before labeling; use a two-person independent-labeling scheme with arbitration for disagreements; and periodically measure inter-annotator agreement.
3. Stability Evaluation: Queuing, Rate Limiting, and Retries
3.1 Use Load Testing to Reproduce Real Capacity
You should not wait until after launch to discover peak-hour queuing. Before launch, design a load-testing plan based on the live traffic profile (request volume, concurrency, input/output length distribution):
- Gradual ramp-up: Increase concurrency in steps as a fraction of the expected peak, and observe the turning points in latency, error rate, and throughput.
- Long-input load testing: Test long-context requests separately, since their memory footprint and processing time are typically much higher than short requests.
- Burst traffic: Simulate traffic spikes to verify that rate limiting and queuing behave as intended.
- Capacity planning: Using a constraint that P95 or P99 latency stays within the business threshold, work backward to the required concurrency quota or instance count, with a safety margin.
At the same time, quality may degrade under load. Evaluation and load testing should cover both “low load” and “high load” states, avoiding validation only under ideal conditions.
3.2 Error Classification: Retryable vs. Non-Retryable
Faced with rate limiting and timeouts, a naive “retry on any failure” can worsen congestion. The right approach is to classify errors first:
- Retryable: Rate limiting (e.g., HTTP 429), transient server errors (e.g., HTTP 5xx), network timeouts;
- Non-retryable: Parameter errors (e.g., HTTP 400), content-safety blocks, exhausted quota, and so on. Retrying these only wastes quota and amplifies the impact of the failure.
3.3 Exponential Backoff, Jitter, and a Retry Budget
For retryable errors, use “exponential backoff plus random jitter” to avoid many clients retrying at the same moment and creating a second wave of load. Illustrative pseudocode:
# Illustrative pseudocode expressing retry and fallback logic; no dependency on any specific platform APIdef call_with_fallback(request, budget, logger):models = select_models(request) # Choose candidate models by task type and complexityfor model in models:base, cap, max_attempts = 0.5, 8.0, 3for attempt in range(max_attempts):if not budget.allow(model):logger.warn("Budget too low, skipping model", model)breaktry:resp = llm_client.chat(model=model,messages=build_messages(request),temperature=0.2,)if not validate_output(resp):raise OutputInvalidError("Structured output validation failed")return respexcept (RateLimitError, TimeoutError, ServerError) as e:# Retry only on recoverable errors; raise others directlyif attempt == max_attempts - 1:logger.error("Retries exhausted, switching to next candidate model", extra={"error": str(e)})break# Exponential backoff + random jitter to avoid a retry stormdelay = min(cap, base * (2 ** attempt)) * random.uniform(0.5, 1.0)time.sleep(delay)raise AllModelsFailedError("All candidate models are unavailable")
In practice, also note:
- Retry budget: Set a global cap on the number of retries and the tokens spent retrying, to prevent cost from spiraling during an outage.
- Timeout settings: Timeouts should not be too short. Long-output and reasoning-intensive tasks need more processing time.
- Graceful degradation: When all candidate models are unavailable, return a predefined fallback (such as a rule-based answer, a templated response, or a cached result) so the request does not hang indefinitely.
4. Cost Evaluation: Make Every Credit Count
4.1 What Makes Up the Cost
LLM call costs are usually composed of input tokens and output tokens separately, and some models also account for reasoning (thinking) tokens separately. Simplified:
Cost per task = input tokens × input price + output tokens × output priceMonthly total ≈ Σ(cost per task) + extra spend from retries, failed requests, and timed-out requests
Two often-overlooked facts:
- Output tokens are usually more “expensive” than input tokens: The exact multiplier depends on pricing, but the engineering conclusion holds: controlling output length is often more directly effective than compressing input.
- Failed requests still consume quota: Timeouts, retries after rate limiting, and resends after format-validation failures all incur real cost.
4.2 Why Quota “Burns” So Fast
Building on the typical scenario above, quota usually drains too fast for these reasons:
- Unbounded context growth: Every turn splices the full history into the prompt. As the conversation grows, input cost grows roughly with the square of the number of turns.
- Bloated prompts: Including many examples and explanations irrelevant to the current task, re-transmitted every turn.
- No output cap: Without a maximum output length, the model tends to generate verbose answers or emit many filler fields in structured output.
- Retry amplification: When peak-hour rate limiting and timeouts are frequent, failed retries consume quota repeatedly.
- Task mismatch: Using an expensive model for simple tasks such as intent recognition, format conversion, or simple classification.
4.3 Five Cost-Governance Techniques
(1) Context compression
Do not blindly concatenate the full history. Use a layered strategy:
- Roll earlier turns into a running summary that keeps only conclusions and key facts;
- Keep the most recent few turns verbatim;
- Run a budget check before each call, and compress further when a threshold is exceeded;
- For long documents, do retrieval or extraction first, sending only relevant snippets to the model.
# Illustrative pseudocode: build context under a token budgetdef build_context(system_prompt, history, query, budget_tokens):# 1. Reserve room for the current question and the outputreserved = estimate_tokens(query) + MAX_OUTPUT_TOKENSavailable = budget_tokens - estimate_tokens(system_prompt) - reserved# 2. Keep the most recent N turns verbatimrecent = history[-RECENT_KEEP:]older = history[:-RECENT_KEEP]# 3. Rolling summary for earlier turnssummary = summarize(older) if older else ""context = [system_prompt]if summary:context.append({"role": "system", "content": "History summary: " + summary})# 4. Fill from old to new, stop when over budget (prioritize keeping the summary)used = estimate_tokens(summary)for msg in recent:cost = estimate_tokens(msg["content"])if used + cost > available:breakcontext.append(msg)used += costcontext.append({"role": "user", "content": query})return context
(2) Cache reuse
- Identical-request caching: For tasks with high determinism (such as summarizing a fixed document or standard Q&A), reuse the result directly for the same input, with a sensible expiry.
- Prefix reuse: Many platforms offer a caching mechanism for a common prefix in the prompt to reduce repeated computation. In engineering terms, put stable content such as the system prompt and few-shot examples at the front of the prompt, and dynamic content after it.
- In-session reuse: Intermediate results already generated within a session (such as a document summary) should be persisted, not recomputed every subsequent turn.
(3) Output constraints and length control
- Set a reasonable maximum output length;
- Specify the output format and length requirements in the prompt;
- Enforce schema validation on structured output; on failure, retry with the error information attached, so invalid output never enters the business flow.
(4) Budget guardrails
- Set daily/monthly quota caps by user, tenant, application, model, and other dimensions;
- Set a per-request token limit and a maximum number of call turns;
- Automatically downgrade to a low-cost model or cache when usage hits a threshold;
- When quota is about to expire, plan batch jobs ahead of time to avoid wasted spend near expiry.
(5) Scenario-based selection
Not every task needs an expensive model. Relatively deterministic tasks such as intent recognition, information extraction, and format conversion can be handled by a lightweight model or rules, reserving complex reasoning and creative generation for high-capability models. Concretely, build a task-to-model mapping matrix and select dynamically at runtime via routing (see Chapter 6).
5. Tiered Routing: Balancing Quality and Cost With a Cascade Strategy
“Solve everything with one model” often means paying the highest cost for every request. A more sensible approach is to build a model matrix and select dynamically by task complexity:
| Task characteristics | Recommended strategy | Example scenarios |
|---|---|---|
| Solvable by rules | Rules/templates first | Fixed-format validation, keyword classification |
| Simple, high concurrency | Lightweight model | Intent recognition, short-text classification, format conversion |
| Medium complexity | General-purpose model | Document summarization, multi-turn Q&A |
| Complex reasoning, long context | High-capability model | Complex code generation, multi-step analysis, long-document understanding |
| Uncertain results | Cascade validation: generate with a lightweight model, then check with a verifier/rules, and escalate if it fails | Structured-data extraction, code generation |
The core of cascade routing is “cheap first, expensive later”: handle the request with a low-cost approach first, and call the high-cost approach only when upgrade conditions are met. A simplified illustration:
# Illustrative pseudocode: choose model tier by complexity scoredef route(task):score = 0score += 2 if task.needs_multi_step_reasoning else 0score += 2 if estimate_tokens(task.context) > LONG_CONTEXT_THRESHOLD else 0score += 1 if task.output_schema else 0score += 1 if task.domain_sensitive else 0if score >= 4:return "strong_model"if score >= 2:return "general_model"return "light_model"
After the routing strategy goes live, continuously evaluate its payoff using online metrics (success rate, cost, latency) and adjust the scoring thresholds accordingly. Also keep a fraction of traffic routed through multiple models simultaneously (shadow traffic) to compare quality and cost.
6. Engineering Implementation: Evaluation Pipelines, Canary Releases, and Observability
6.1 Embed Evaluation Into the Development Workflow
- Evaluate on commit: Wire the evaluation set into the CI pipeline so that changes to model configuration, prompts, or routing strategy automatically trigger regression evaluation, and block the release if core metrics fall below baseline;
- Prompt versioning: Manage prompts in the code repository so that, together with model configuration, they form a reproducible release unit;
- Canary and shadow traffic: Roll out a new model to a small fraction of traffic first, or run it in shadow mode (record results only, without affecting live responses), and ramp up gradually once it proves stable;
- Offline replay: Save desensitized live requests and replay them offline before a new version ships, comparing before-and-after differences.
6.2 Observability: Making Cost and Quality “Visible”
Log every call with structured records including at least: request ID, model ID and version, input/output token counts, time to first token, total latency, whether the cache was hit, retry count, error type, business result, and user feedback. On top of these logs, build monitoring dashboards and set alert thresholds for key metrics:
- Abnormal rises in average cost per task or daily total cost;
- Error rate or rate-limit rate exceeding thresholds;
- P95 latency trending up persistently;
- A noticeable drop in cache hit rate.
In LLM applications, common anomaly types such as “request fails because input is too long,” “output is truncated,” and “structured-output validation fails” should be tracked separately and alerted on.
6.3 Building a Closed Loop With General Cloud Capabilities
An evaluation pipeline typically needs to batch-store datasets and results, run load tests asynchronously, and accumulate logs and monitoring. These needs can be met with a cloud platform’s existing general capabilities. For example, on Baidu AI Cloud you can combine services such as object storage, message queues, a container platform, log services, and monitoring/alerting to build an evaluation and operations loop. This lets the team focus on model selection and prompt engineering rather than rebuilding infrastructure.
6.4 Data Compliance and Privacy
Evaluation data and live logs may contain sensitive information. Follow the principle of least necessity:
- Desensitize evaluation data;
- Define data-retention periods and access permissions clearly;
- For scenarios involving personal information or business-sensitive data, prefer private deployment or compliant data-handling solutions.
7. Common Pitfalls and Best Practices
| Common pitfall | What’s wrong | Recommended approach |
|---|---|---|
| Judging only by leaderboard rank | Evaluation questions don’t match your business distribution | Build a scenario-specific set and rely on business metrics |
| Judging only by average score | Masks long-tail failures and variance | Stratify your statistics; watch the worst percentiles and failure cases |
| Judging only by model capability | Ignores queuing, rate limiting, and cost | Evaluate across all dimensions; compare capability and cost together |
| Blindly concatenating context | Cost grows with the square of turns | Rolling summary + recent-turn retention + budget control |
| Retrying on every failure | Worsens congestion and amplifies cost | Error classification + exponential backoff + retry budget |
| One model for everything | Simple tasks pay a high price | Tiered routing + cascade validation |
8. Implementation Roadmap
Proceed in four phases:
- Baseline phase (1–2 weeks): Map the core scenarios and build a first evaluation set (no fewer than a few hundred items, covering the main task types with difficulty stratification); establish baseline metrics for quality and cost.
- Optimization phase (2–4 weeks): Improve prompts and context strategy for the weak spots, introduce caching and budget guardrails, and complete at least one round of paired comparison and statistical testing.
- Consolidation phase: Embed evaluation into the CI pipeline, set up a canary-release mechanism, and design and launch the routing strategy.
- Operations phase: Establish an observability system and a regular review cadence, keep adding failure cases, and re-evaluate the model matrix and routing thresholds quarterly.
9. Conclusion
Evaluating a large language model is fundamentally about finding the balance point between quality, stability, and cost that fits your own business. Leaderboard scores can serve as a first-pass filter, but truly reliable decisions come from scenario-specific evaluation sets, paired comparisons, and statistical tests; queuing and rate-limiting problems need to be tackled systematically through capacity load testing, error classification, and backoff retries; and fast quota drain usually stems from context bloat, uncontrolled output, and task mismatch, which require a combined approach of compression, caching, guardrails, and tiered routing. By tying the evaluation system together with an evaluation pipeline, canary releases, and observability, a team can move from “choosing models by feel” to “data-driven decisions,” achieving a sustainable balance among quality, cost, and stability.
