How to Evaluate Large Language Models: A Practical Framework from Model Selection to Production
This article presents a practical, reproducible framework for evaluating large language models. It explains how to define measurable criteria such as accuracy, instruction following, stability, latency, and cost; how to build your own evaluation dataset from real business logs; how to design scoring methods with automated rules, reference answers, and human or model-assisted review; and how to interpret results statistically. It also covers cost and latency estimation, a reference architecture for the evaluation pipeline, rollout and continuous regression strategies, and common pitfalls to avoid when selecting and deploying an LLM.
Step 1: Define the Problem — What Does “Good” Actually Mean?
“Which model is better?” is a common question, but it lacks a comparison target and comparison conditions. The same model may perform reliably in customer service Q&A yet fail frequently on complex code generation. The same budget spent on a high-concurrency scenario versus a low-frequency analytics scenario will lead to entirely different conclusions. Before discussing model capability, “good” must be broken down into measurable dimensions.
Drawing conclusions from personal impressions is risky — they are easily influenced by the most recent experience, the interface style, or marketing claims. A more reliable approach for engineering teams is to compare candidate models side by side using a unified dataset, unified prompts, and unified scoring criteria.
Step 2: Break Requirements Down into Measurable Metrics
Common evaluation dimensions include:
- Task accuracy: Whether the output is factually correct and whether structured results can be parsed directly by programs.
- Instruction following: Whether the model strictly complies with format, length, tone, and step requirements.
- Stability: Whether results remain within an acceptable range when the same input is run multiple times.
- Response latency: Time to first token and total completion time. Focus on percentiles such as P95 rather than averages alone.
- Cost per call: The per-request cost calculated from input and output tokens, and the monthly cost at your target business volume.
- Compliance and data security: Whether data may cross borders, whether industry regulations are met, and whether log retention policies comply with internal rules.
Every metric needs a clear threshold, such as “structured output parse success rate of at least 98%” or “P95 latency under 3 seconds.” Thresholds should come from business requirements, not from a public leaderboard.
Step 3: Build Your Own Evaluation Set
The evaluation set is the foundation of the entire process, and its quality directly determines whether your conclusions are trustworthy.
- Data source: Sample from real business logs and preserve users’ original phrasing. Avoid hand-crafted “ideal questions.”
- Coverage: Use stratified sampling across task type, difficulty, input length, and language to ensure edge cases are included.
- Annotation standards: Provide a reference answer or judgment rule for every sample. For open-ended questions, specify scoring dimensions such as completeness, factuality, and tone.
- Sample size: At least 200 samples per task category is recommended. With too few samples, random variation in a single run may mask real differences.
- Isolation principle: Evaluation samples must never appear in prompt-tuning or fine-tuning data; otherwise, results will be inflated.
The evaluation set should be version-controlled, with the reason recorded for every addition or modification to support later review. An example data format:
{"id": "faq-0012", "task": "order_status", "prompt": "Why hasn't my order shipped yet?", "rule": "Must include the estimated shipping time", "difficulty": "medium"}
Step 4: Design the Scoring Methods
Scoring methods fall into three broad categories, and real projects typically combine them.
- Automated rule-based scoring: Suitable for structured outputs. You can check whether the JSON parses, whether required fields are present, and whether values fall within reasonable ranges. This type of check is low-cost and reproducible.
- Reference answer comparison: Suitable for tasks with a single correct answer, such as classification, information extraction, and arithmetic. Normalize before comparing — for example, trim leading/trailing whitespace and unify full-width and half-width characters.
- Human or model-assisted review: Suitable for open-ended responses. If you use an LLM as a judge, watch out for self-preference bias and position bias. Randomly shuffle the order of candidate answers and calibrate the review results with human spot checks.
Below is a minimal evaluation loop. The model_fn is provided by the caller — it takes a prompt and returns text, and which service it connects to is up to the engineering team.
import statisticsfrom dataclasses import dataclassfrom typing import Callable@dataclassclass Case:prompt: strexpected: strdef normalize(text: str) -> str:return " ".join(text.strip().split())def evaluate(model_fn: Callable[[str], str], cases: list[Case], runs: int = 3) -> dict:per_case = []for case in cases:hits = [normalize(model_fn(case.prompt)) == normalize(case.expected)for _ in range(runs)]per_case.append(sum(hits) / runs)return {"accuracy_mean": statistics.mean(per_case),"accuracy_min": min(per_case),"unstable_cases": sum(1 for s in per_case if 0 < s < 1),}
This code outputs three results: average accuracy, the worst-performing sample’s score, and the number of unstable cases that are “sometimes right, sometimes wrong.” The third metric is often more telling than the average, because it directly reflects how reliable the output is.
Step 5: Aggregate and Interpret Results Statistically
Evaluation results need statistical treatment before they can support decisions.
- Multiple runs: Run each sample at least three times and record the fluctuation range of the pass rate.
- Per-task aggregation: A single overall score can hide obvious weaknesses in one task category, so report results by task type.
- Confidence intervals: When the gap between two candidates is small, compute confidence intervals. If the intervals overlap, the difference may just be random noise and should not drive a conclusion.
- Failure attribution: Classify failed samples into comprehension errors, format errors, factual errors, and refusals. Different failure types require different fixes.
Step 6: Factor Cost and Latency into the Decision
The most accurate option is not necessarily the best option. Per-call cost can be estimated with this formula:
Cost per call = input tokens × input price + output tokens × output price
Use the prices published by the service provider, noting that they change over time. Base estimates on the real average input and output lengths of your business, not idealized short texts.
Latency must be quantified as well. For user-facing real-time scenarios, track both time to first token and total completion time. For offline batch processing, focus on throughput and total job duration.
Step 7: A Reference Architecture for Engineering Implementation
If you build the evaluation and invocation pipeline on Baidu AI Cloud, you can organize it by general capabilities: store evaluation samples and results in object storage, schedule batch evaluation jobs through a message queue, write run logs and metrics to a logging service, and cover failure rate and latency anomalies with monitoring and alerting. This layered approach is vendor-agnostic — migrating to another cloud environment only requires swapping the corresponding infrastructure components.
Step 8: Selection Decisions and Continuous Regression
After completing the evaluation, follow these steps to make a decision:
- Filter with hard constraints first — eliminate any option that fails compliance or latency requirements.
- Compare quality against cost among the remaining options and organize the results into a trade-off table for team discussion.
- Roll out to a small percentage of traffic (canary release) and compare real business metrics, such as human acceptance rate and handoff-to-human rate.
- Keep a rollback path so you can quickly switch back to the previous option if anomalies occur.
Model versions get updated and business data changes, so evaluation is not a one-time effort. Integrate the evaluation set into your CI pipeline, run automatic regression on every model upgrade or prompt change, and compare results against the historical baseline.
Common Pitfalls
- Treating public leaderboard scores as business performance. Leaderboard distributions often differ from real workloads.
- Drawing conclusions from a handful of impressive or failed examples. Individual samples cannot represent the whole.
- Using different prompts for different candidates, which makes the comparison unfair.
- Ignoring evaluation data leakage, which inflates results above the true level.
- Focusing only on accuracy without calculating cost and latency, forcing the selection to be overturned at launch time.
Summary
The key to judging whether an LLM is “good” is to first define what “good” means, run reproducible evaluations on your own data, and then make a decision that weighs cost, latency, and compliance together. The same workflow can be reused whenever a new model appears, helping the team make reliable choices on an ongoing basis.
