How to Evaluate a Large Language Model: Quality, Cost, and Capacity
A practical, production-oriented framework for evaluating large language models across six dimensions: task quality, capacity and latency, cost, integration and engineering readiness, governance and compliance, and evolution risk. It shows how to build a task-specific eval set instead of relying on public leaderboards, run concurrency sweeps to find capacity limits, measure real per-task cost rather than per-token price, and roll out a two-week evaluation roadmap backed by a weighted scorecard. It also covers common pitfalls, degradation and fallback design, and how to avoid vendor lock-in.
1. First, fix a flawed premise: the goal isn’t “how strong the model is” but “whether it runs reliably and affordably in my business”
A common pattern: when a new class of large models is released, the discussion heats up fast. But once a team actually integrates it into production, the obstacles to adoption turn out not to be quality but three things—long queueing during peak hours, unpredictable consumption of quota or credits, and severe drift in prompts and results whenever you switch providers.
These three issues point to one conclusion: the object of evaluation should not be “the model itself” but the overall system formed by the model + serving form + billing and capacity strategy + how you call it. The same model can show end-to-end latency that differs by several times depending on streaming output, concurrency limits, and context length. The same prompt can have very different per-task cost depending on whether it includes the full long-document text, whether it hits a cache, and whether context compression is applied.
So evaluation should be split into six dimensions, and failing any one is enough to reject a solution:
- Task quality: whether it is usable on your own business distribution;
- Capacity and latency: throughput, latency percentiles, rate-limiting and queueing behavior;
- Cost: per-task cost, cost volatility, cost observability;
- Integration and engineering readiness: API compatibility, structured output, operability;
- Governance and compliance: data flow, content safety, audit capability;
- Evolution risk: replaceability, vendor lock-in, version drift.
2. Dimension 1: Task quality—replace public leaderboards with your own eval set
Public leaderboards reflect a general capability distribution, while your business usually concentrates on a few task families (ticket classification, contract element extraction, customer-service reply generation, log root-cause attribution). A 2-point gain on a leaderboard often translates to less than a 1% improvement in real pass rate, whereas targeted validation on a task family can yield order-of-magnitude gains.
2.1 Eval set construction principles
- Stratified sampling by task family: at least 50–200 cases per family, covering the long tail of the real distribution rather than only cherry-picked examples;
- Label verifiability: prioritize metrics that can be judged automatically (field completeness, format validity, whether citations are traceable, whether classification hits), compressing subjective judgment into a small number of samples;
- Hard-floor items: cases involving fact fabrication, unauthorized actions, or leakage of sensitive information—any single failure fails the whole set and is excluded from weighted averaging.
# Minimal eval-case structure: auto-judgeable + light human reviewEVAL_CASES = [{"id": "doc-sum-013","task": "long_doc_summarize", # task family, for grouped statistics"input": {"doc": "...", "lang": "zh"},"rubric": ["Covers all key conclusions","Introduces no data beyond the source","Conclusions are traceable to source paragraphs"],"hard_floor": True, # hard floor: failure fails the whole family},{"id": "ticket-cls-207","task": "ticket_classify","input": {"text": "..."},"expected": {"category": "billing", "priority": "P2"},},]
2.2 Judging and statistics
For scoring, use a three-layer structure of “rule checks primarily + judge model as support + manual spot checks as backstop,” and report three metrics simultaneously: first-pass rate (usable without manual rework), rework rate (how many revision rounds before it is usable), and failure-mode distribution (hallucination, format errors, refusals, truncation).
def judge(client, case, response):rule_ok = run_rules(case, response) # format, fields, citations, length, sensitive termsif case.get("hard_floor") and not rule_ok:return {"score": 0.0, "reason": "hard_floor_failed"}score = 0.4 * rule_okrubrics = case.get("rubric", [])for rubric in rubrics:verdict = client.judge(RUBRIC_PROMPT.format(rubric=rubric, answer=response))score += 0.6 * float(verdict == "pass") / max(len(rubrics), 1)return {"score": round(score, 3), "reason": "auto"}
The key point: treat rework rate as a first-class metric. The pass rate for output usable in one generation versus output “barely usable after three revisions” typically differs by 3–5x in real production cost—and that is exactly the part most easily overlooked.
3. Dimension 2: Capacity and latency—turn “queueing” into measurable, alertable metrics
The subjective feeling of “waiting a long time in the queue” should, in engineering terms, be decomposed into a set of collectible metrics:
- Time to first token (TTFT): determines the perceived experience of interactive applications;
- Inter-token output interval / token emission rate: determines whether long-text scenarios “turn into a slideshow”;
- End-to-end latency percentiles: averages alone are meaningless; you must look at P95 and P99, because the long tail directly determines timeout rate;
- Rate-limiting and queueing signals: the frequency of rate-limit responses, timeouts, and connection failures;
- Requests completable per unit time: the real input to capacity planning.
It must be emphasized that these metrics depend not only on the provider but also heavily on client implementation. Not using streaming output, retransmitting very long context in one shot, lacking concurrency control, or setting unreasonable timeouts can all conflate “provider queueing” with “your own implementation defects.” So load testing must run against your own calling code.
async def sweep(client, prompts, concurrency, timeout=30):sem = asyncio.Semaphore(concurrency)async def one(p):async with sem:t0 = time.perf_counter()try:r = await client.chat(p, timeout=timeout)return {"ok": True,"e2e_ms": (time.perf_counter() - t0) * 1000,"ttft_ms": r.ttft_ms,"out_tokens": r.output_tokens}except Exception as e:return {"ok": False, "err": type(e).__name__}res = await asyncio.gather(*(one(p) for p in prompts))ok = [r for r in res if r["ok"]]return {"concurrency": concurrency,"success_rate": len(ok) / len(res),"p95_e2e_ms": percentile([r["e2e_ms"] for r in ok], 95),"p99_e2e_ms": percentile([r["e2e_ms"] for r in ok], 99),"p95_ttft_ms": percentile([r["ttft_ms"] for r in ok], 95),"throughput_tps": sum(r["out_tokens"] for r in ok) /(sum(r["e2e_ms"] for r in ok) / 1000),"error_kinds": Counter(r["err"] for r in res if not r["ok"]),}
Load tests should sweep across concurrency levels (for example 1, 5, 20, 50), find the inflection point where success rate begins to drop, and use the concurrency at that point as input to the capacity ceiling. Also test separately for business peak/off-peak and different context lengths, because long-context requests affect queueing and memory far more than short requests.
Supporting engineering measures are also part of the evaluation criteria: exponential backoff with jittered retries, per-request timeouts plus a total budget, asynchronous task queues to smooth peaks, and clear degradation paths.
async def chat_with_fallback(policy, messages):for i, target in enumerate(policy.targets): # primary model → backup model → lightweight modelfor attempt in range(policy.max_attempts[i]):try:return await target.chat(messages, timeout=policy.timeout_s)except RateLimited as e:await asyncio.sleep(backoff(attempt, cap=e.retry_after, jitter=True))except TransientError:await asyncio.sleep(backoff(attempt, cap=8, jitter=True))return await policy.degrade(messages) # queue notice / cached result / escalate to human
4. Dimension 3: Cost accounting—from “unit price” to “per-task cost”
A common selection mistake is comparing only the price per thousand tokens. The real cost formula is:
per-task cost = (input tokens × input price + output tokens × output price − cache-hit discount) / successful tasks
Here the denominator is the number of tasks that succeed and pass quality checks, not the number of requests. Failed retries, invalid formats requiring re-runs, and answers refused and escalated to humans all inflate the denominator, turning a “cheaper per-token” option into a more expensive one in practice. Billing dimensions (separate input/output pricing, cache-hit discounts, batch discounts, context-length effects, and so on) are each provider’s commercial terms; specific numbers should follow the official documentation and contract for the service you use, and the code keeps only abstract configuration.
Cost observability is another hard requirement: without accounting, you cannot optimize. Instrument at the gateway layer to log the model, task family, token usage, latency, status, and cost of every call, then feed into a log service and monitoring/alerting system, with drill-down and budget alerts by business line, scenario, and tenant.
LEDGER = [] # Minimal cost-accounting record; ultimately lands in logs/data warehousedef on_completion(req, resp):LEDGER.append({"ts": time.time(),"model_alias": req.model_alias, # logical model name, hides underlying differences"task": req.task, "tenant": req.tenant,"in_tokens": resp.usage.input_tokens,"out_tokens": resp.usage.output_tokens,"cached_in_tokens": resp.usage.get("cached_input_tokens", 0),"ttft_ms": resp.ttft_ms, "e2e_ms": resp.e2e_ms,"status": resp.status, # ok / timeout / rate_limited"cost": price_table[req.model_alias](resp.usage), # price from official documentation})
With accounting data, common cost-reduction levers can be quantitatively validated rather than guessed:
- Tiered routing: route structured tasks (classification, extraction, format conversion) to lightweight models; route only complex reasoning to large models;
- Context governance: truncating and deduplicating retrieval snippets, summarizing long documents before reasoning—usually the single most effective optimization;
- Cache reuse: semantic or result caching for repeated and pre-computable requests;
- Output constraints: cap maximum output length and avoid verbose explanatory output, directly reducing output tokens.
Handling “quota about to expire”
If your organization genuinely has resource quotas with an expiration date, the right approach is to schedule it as capacity with a lifecycle rather than burn it carelessly:
- Prioritize offline tasks with real output value—batch labeling and categorization of historical tickets, summarization and knowledge-base rebuilding of existing documents, batch generation and human review of eval corpora, backfilling regression-test baselines;
- Set separate concurrency and quota policies for batch jobs to avoid competing with online business for capacity;
- Keep a task list and an output-validation process to ensure quota consumption turns into reusable assets rather than wasted calls.
Conversely, if a service has chronic queueing and stability problems, do not put it on the critical path even if quota is currently ample—capacity risk is harder to eliminate through engineering than cost risk.
5. Dimension 4: Integration and engineering readiness
This dimension determines migration and long-term maintenance cost. Key evaluation points:
- API compatibility: whether it offers mainstream, general-style invocation and supports streaming output, which directly determines how much business code has to change;
- Structured output: whether it reliably returns parseable results per a JSON schema or via function calling—especially critical for extraction tasks;
- Parameter controllability: whether temperature, max output length, stop conditions, and context-length limits meet business needs;
- Operability: whether it returns usage information usable for metering, and whether error codes distinguish retryable from non-retryable failures;
- Engineering details: request idempotency, timeout and retry semantics, concurrency limits, and SDK/language ecosystem completeness.
Always use a logical model alias as a thin adapter layer to decouple prompt templates, parameters, and retry policies from any specific provider:
class LLMProvider(Protocol):async def chat(self, messages, *, model_alias: str, temperature: float = 0.0,max_tokens: int | None = None, tools: list | None = None,timeout: float = 30) -> ChatResult: ...class Router:def __init__(self, registry: dict[str, LLMProvider]): self.registry = registryasync def chat(self, messages, **kw):return await self.registry[kw["model_alias"]].chat(messages, **kw)
The benefit isn’t just switchability: it turns A/B testing, canary releases, and per-scenario routing into configuration items rather than code changes.
6. Dimensions 5 & 6: Governance/compliance and evolution risk
Governance and compliance: confirm where data is processed and retained, content-safety filtering and blocking capability, log masking and audit traceability, and whether the service meets your industry’s compliance requirements. For sensitive data, prefer to sacrifice a little quality to keep data flow within an acceptable range.
Evolution risk: watch for three problems. First, silent model-version upgrades causing quality drift—establish a mechanism to pin “prompt + parameters + model version” and run periodic regression. Second, prompts strongly coupled to a specific model, causing sharp quality drops after switching—treat prompt assets as versioned artifacts and run cross-model compatibility tests. Third, long-term lock-in—preserve bargaining and migration ability through an adapter layer and a standard eval set.
7. Rollout roadmap: a trustworthy evaluation in two weeks
| Phase | Time | Deliverable |
|---|---|---|
| Define tasks and baseline | 1–2 days | Eval set, scoring rules, current-solution baseline |
| Parallel evaluation | 3–4 days | Quality comparison across candidates, failure-mode distribution |
| Capacity and cost | 2–3 days | Concurrency inflection points, P95/P99 latency, per-task cost |
| Small-traffic canary | 1–2 weeks | Real-traffic success rate, rework rate, cost extrapolation |
The conclusion is best expressed with a unified scorecard to avoid subjective “feels better” judgments:
| Dimension | Weight | Pass criterion (example; set per business) |
|---|---|---|
| Task first-pass rate | 30% | ≥ target; hard-floor cases 100% pass |
| P95 end-to-end latency | 20% | Interactive ≤ 3s; batch defined separately |
| Per-task cost | 20% | Below baseline with a clear cost-reduction path |
| Success rate at high concurrency | 15% | ≥ 99% at target concurrency |
| Integration and operability | 10% | Supports streaming, structured output, usage observability |
| Compliance and replaceability | 5% | Meets data/audit requirements; adapter layer in place |
8. Five common mistakes
- Looking only at leaderboards: general capability cannot substitute for validation on your business distribution;
- Looking only at unit price: ignoring the hidden cost of rework and failures;
- Looking only at average latency: averages hide the long tail, and timeouts are determined by P99;
- Blaming the provider for client-side problems: no streaming, no concurrency control, and overly short timeouts can all masquerade as “severe queueing”;
- No regression: changes on either the model-version side or the prompt side can cause quality drift; lacking a regression mechanism means losing quality control.
9. Conclusion
Evaluating a large model is essentially answering four quantifiable questions: can I use it on my task, can it stay stable at peak, how much does each successful task cost, and how expensive is it to replace. Break these four questions into an eval set, a concurrency inflection-point curve, a per-task cost definition, and an adapter-layer design, and evaluation stops being subjective debate and becomes a reproducible, comparable, decision-supporting technical conclusion. For teams that want to build this capability quickly, general-purpose cloud capabilities—model serving, containers and elastic compute, object storage, and logging plus monitoring and alerting (for example, those offered by Baidu AI Cloud)—can turn the evaluation pipeline, cost accounting, and canary releases into standardized infrastructure, making model selection a sustainable, continuous optimization rather than a one-time judgment.
