How to Scientifically Evaluate an LLM's Capabilities and Costs
This article explains why a few casual conversations are not enough to evaluate a large language model, and presents a practical framework for assessing both capability and cost. It covers a multi-dimensional evaluation system (decidable capability metrics such as task success rate and pass@k, cost expressed as cost per 10,000 effective tasks, and engineering factors such as effective context length and explicit failure handling), how to build a private, stratified evaluation set with a unified evaluation script, and how to keep quota consumption controllable through budget guardrails, caching, retry with backoff, peak shaving, and multi-model routing. Readers will learn to turn model evaluation from subjective impressions into a quantifiable, reproducible engineering decision.
Many people form their judgment of a model from a handful of scattered conversations: some are impressed by a brilliant answer, others complain about slow responses and having to queue during peak hours, and still others only remember that their account credits or quota is nearly exhausted, so they simply stop using it. Trial credits being burned through quickly—often right when a service hits peak load—is a familiar pattern in the early days of AI coding tools and LLM services. It is a sign that user experience genuinely matters, but it is also a reminder: scattered impressions from casual chats are not a systematic evaluation, let alone a sound basis for technology selection, architecture design, or cost budgeting.
This article abstracts that situation into two general engineering problems: “how to evaluate an LLM” and “how to assess and manage the cost of LLM calls.” It lays out a practical set of methods for evaluation and governance.
1. Why “a Few Chats” Are Not Enough to Judge a Model
- Outputs are non-deterministic: Even at low temperature, sampling parameters can produce differently worded outputs from the same input. The quality of a single sample cannot represent the overall level; evaluation must rest on enough samples and repeated sampling.
- The experience dimension tends to be flattened: Chat interfaces usually hide critical constraints such as rate limits, concurrency quotas, and input/output length limits. How something feels in the UI says nothing about how the model performs in batch calls, structured output, or tool calling.
- Cost and capacity are continuous variables: The rate at which quota is consumed is closely tied to input length, output length, call frequency, and failed retries. When there is network jitter or occasional rate limiting, retries without backoff and circuit breaking can multiply consumption.
- Fair comparison requires controlling variables: Providers differ in tokenization, context length, parameter limits, and default parameters. If prompts, parameters, and scoring criteria are not standardized, comparison results are meaningless.
Therefore, model evaluation should cover at least three kinds of questions: Does the capability meet business needs? How many resources does a single task consume, and is the cost sustainable? Can the service reliably support the expected traffic? This aligns with the classic classification of software quality attributes: functional suitability maps to capability, efficiency and capacity map to cost and throughput, and reliability and maintainability map to engineering controllability.
2. Building a Multi-Dimensional Evaluation System
2.1 Capability Dimension: Replace Subjective Impressions with Decidable Metrics
Capability evaluation should revolve around real tasks. Common quantifiable metrics include:
| Metric | Meaning | Formula |
|---|---|---|
| Task success rate | Whether the end-to-end output is correct | Correct samples ÷ total samples |
| pass@k | At least one correct among k attempts | 1 − C(n−c, k) ÷ C(n, k), where n = number of samples, c = number correct |
| Instruction-following rate | Proportion meeting format, length, and role constraints | Samples meeting all constraints ÷ total samples |
| Structured output validity rate | Whether the returned content can be parsed into the agreed structure | JSON-parseable samples with all fields present ÷ total samples |
| Tool-call accuracy | Whether the right function is chosen and parameters passed correctly | Samples correct on selection, parameters, and result use ÷ total samples |
| Hallucination rate | Proportion of factual or verifiable errors | Answers with errors ÷ total answers |
| Robustness | Whether behavior stays stable under input perturbation or injection | Samples passing adversarial cases ÷ total adversarial cases |
pass@k is used for generative tasks, commonly in code generation: if at least one of the n generated candidates passes the unit tests, the sample is considered passed. For tasks with a single correct answer, pass@1 is equivalent to accuracy.
2.2 Cost Dimension: Estimate “Cost per 10,000 Effective Tasks”
Traditional software can use load testing to determine whether a system can handle peak load, but LLM calls are constrained not only by their own rate limits but also by competition for resources with all other users sharing the same service. Queuing during business peaks is essentially instantaneous concurrency exceeding the quota.
Common throughput metrics include throughput at different concurrency levels (successful requests per second), latency percentiles (P50/P95/P99), and rate-limit incidence (the proportion of requests returning rate-limit errors). For the cost dimension, it is recommended to standardize on “cost per 10,000 effective tasks,” factoring in the losses from success rate and retries:
effective_tasks = total_calls × task_success_ratecost_per_10k_effective_tasks = total_cost ÷ effective_tasks × 10000total_cost = Σ(input_tokens × input_price + output_tokens × output_price) + billing for failed calls
This measure exposes a common pitfall: a model with a lower unit price, if its task success rate is noticeably lower, will have retries that push up the real cost; and queuing under high concurrency can further reduce the effective task count within a limited window. Looking only at unit price easily leads to wrong decisions.
2.3 Engineering Dimension: Controllable, Observable, Portable
- Context length must be “effective”: Do not just look at the advertised window size; test whether key information in the middle of long texts can be used accurately. Long contexts usually bring higher latency and cost, so “stuffing all the material into the context” is not necessarily the most cost-effective approach.
- Call methods must fit the business: Interactive conversations care about time-to-first-token and can use asynchronous batch inference to lower unit cost; offline tasks can use message queues to buffer and smooth peak-load requests into off-peak periods.
- Ecosystem compatibility affects migration cost: Whether it is compatible with the common Chat Completions interface style, and whether it supports streaming output and function calling, determines the effort of migrating to a multi-model architecture.
- Failure handling must be explicit: Whether error codes can distinguish rate limiting, timeouts, and server-side errors is the foundation for designing retry and circuit-breaking strategies.
3. Building a Private Evaluation Set and a Unified Evaluation Process
Public benchmarks are good for getting a rough sense of a model’s general level, but they rarely reflect performance on a specific business. A more reliable approach is to build a private evaluation set in addition to public benchmarks.
3.1 Building the Evaluation Set
- Data sources: Prioritize real business samples that have been anonymized, such as customer service conversations, ticket records, code snippets, and structured generation requirements.
- Stratified design: Sample by task type (information extraction, text generation, code generation, multi-turn dialogue, tool calling) and by difficulty. Prepare at least dozens to hundreds of samples per task type so that the confidence interval of the success-rate metric is narrow enough. A simple method is to estimate the fluctuation range using the standard error √(p(1−p)/n), where p is the success rate and n is the sample size; with n=100 and p=0.9, the standard error is about 3%.
- Clear scoring criteria: Use exact match for extraction tasks, unit tests for code tasks, and key-fact verification for generation tasks, and introduce multi-point scoring as needed (e.g., 1–5 points each for accuracy, completeness, and format compliance).
- Prevent data contamination: Keep the evaluation set private, rotate it regularly, and add new samples to reduce the inflated scores that come from a model having “seen the answer.”
- Version control: Put the evaluation set and scoring rules under version control, re-run the full evaluation on every model change, and form traceable regression records.
3.2 A Unified Evaluation Script
Wrap the call differences across models in a simple layer to ensure the evaluation process is fair and reproducible:
import jsonimport statisticsimport timefrom dataclasses import dataclass@dataclassclass ChatResult:text: strusage: dictlatency_ms: floatclass BaseModelClient:"""Unified abstraction layer: hides interface differences between model services"""def chat(self, messages, **params) -> ChatResult:raise NotImplementedErrordef evaluate(client: BaseModelClient, samples, judge, samples_per_case=3):rows = []for item in samples:results, correct, tokens = [], 0, 0for _ in range(samples_per_case):t0 = time.perf_counter()try:r = client.chat(item["messages"], temperature=0.2,max_tokens=item.get("max_tokens", 512))results.append(r)correct += int(judge(item, r.text))tokens += (r.usage.get("prompt_tokens", 0)+ r.usage.get("completion_tokens", 0))except Exception as exc: # record timeouts, rate limits, and other errors uniformlyrows.append({"case_id": item["id"], "error": str(exc)})if results:rows.append({"case_id": item["id"],"success_rate": correct / len(results),"avg_tokens": tokens / len(results),"p95_latency_ms": max(r.latency_ms for r in results),})summary = {"success_rate": statistics.mean(r["success_rate"] for r in rows if "success_rate" in r),"avg_tokens": statistics.mean(r["avg_tokens"] for r in rows if "avg_tokens" in r),"error_rate": sum("error" in r for r in rows) / len(rows),}return summary
A few things to note when putting this into practice:
- Independent judge:
judgecan be rules, unit tests, or a model reviewer calibrated by humans. Model review is cheaper, but it has its own biases and should be spot-checked by humans to calibrate how well it matches the ground truth. - Concurrency must also be limited: When the evaluation script runs with too much concurrency, it will itself trigger rate limiting, and the measured error rate will not represent the real production level.
- Multiple samples per case: Running each sample k times and averaging the success rate directly is the engineering implementation of the pass@k formula. For brevity, the example only tracks latency here; when evaluating interactive services, you should also record P95 for both time-to-first-token and full-output time.
4. Making Quota Consumption “Controllable and Predictable”
The most instructive point from the original scenario is this: quota silently running out is often more frustrating than the quota simply being insufficient. These problems are common in the pilot stage: no budget guardrails, redundant prompts, failed requests retrying endlessly, and nightly batch jobs competing with daytime peaks for concurrency. Here are several practical guardrails.
4.1 Budget Guardrails and Cost per Task
Set a budget for each call chain at the client or gateway layer. Assume a prompt of about 2000 tokens and an output cap of about 1000 tokens, so a single request’s token limit is about 3000:
class BudgetExceeded(Exception):"""Actively stop when the budget is insufficient, avoiding wasted consumption"""def guarded_chat(client: BaseModelClient, messages, remaining_budget: int,max_tokens=1024):prompt_tokens = client.count_tokens(messages) # estimated with a local tokenizerif prompt_tokens + max_tokens > remaining_budget:raise BudgetExceeded("Budget insufficient; reduce context or adjust output length")return client.chat(messages, max_tokens=max_tokens)
4.2 Lightweight Context and Caching
- Keep system prompts lean: Trim redundant instructions and keep structured prompts stable so they hit billing discounts such as prefix caching.
- Assemble context on demand: Use retrieval-augmented generation (RAG) to recall relevant fragments by question for long documents and knowledge-base content, rather than stuffing entire passages into the context.
- Result caching: Build a cache layer for high-frequency similar requests so that a hit avoids the call entirely. Knowledge-base Q&A can be reused by semantic similarity, and generation tasks can be reused by a normalized request fingerprint. Set an expiration time on the cache and invalidate it promptly after knowledge updates.
- Batching: Send latency-tolerant tasks through asynchronous batch inference, and prioritize streaming output for interactive conversations to improve time-to-first-token.
4.3 Retries, Backoff, and Peak Shaving
import randomimport timedef chat_with_retry(client, messages, max_attempts=4, **params):delay = 1.0for attempt in range(1, max_attempts + 1):try:return client.chat(messages, **params)except Exception as exc:# raise non-retryable errors such as parameter errors and content-policy rejections immediatelyif attempt == max_attempts or not getattr(exc, "retryable", False):raise# exponential backoff + random jitter to avoid many clients retrying in synctime.sleep(delay + random.uniform(0, 0.5))delay *= 2
- Retry only recoverable errors: Rate limits, timeouts, and 5xx responses can be retried; parameter errors and content-policy rejections should not.
- Circuit breaking and degradation: When failures persist, trip the circuit temporarily and degrade requests to a backup model or cached results.
- Async peak shaving: Post non-real-time tasks to a message queue and have worker processes consume them at a steady rate within quota. Let the queue build up during peaks and drain during lulls; this both smooths concurrency peaks and improves quota utilization.
4.4 Multi-Model Routing
Use a rule-based classifier or a lightweight model to judge task difficulty and route to models of different costs: send simple classification, extraction, and formatting tasks to lightweight models, and call stronger models only for complex reasoning and long-form generation. This kind of division of labor—like “large models plan, small models execute”—is already widely practiced in the industry. This strategy should be combined with the stratified evaluation set from Section 2 to verify that degradation does not noticeably harm task quality.
5. Continuous Operations After Launch
- Observability: In the logging service, record each call’s token usage, latency, error codes, and task success rate by model, scenario, and application, then configure alerts in the monitoring system for quota consumption rate, error rate, and latency P95.
- Capacity forecasting: Combine business growth forecasts to estimate monthly call volume and cost, keep 20%–30% headroom, and prepare a pay-as-you-go channel for sudden traffic spikes.
- Anti-lock-in design: Use a unified abstraction layer to hide differences between providers, and preserve prompts, evaluation sets, and scoring rules as independent assets, making future cross-comparison and migration easier.
- Compliance and data security: Clarify which data can be sent to the model service, and anonymize sensitive information; also check whether the terms and configuration in use allow the data to be used for training, and if necessary choose a service form that supports data isolation.
6. Summary
| Stage | Core Actions | Key Outputs |
|---|---|---|
| Before selection | Build a stratified private evaluation set; unify the call wrapper and scoring rules | Reproducible comparison report |
| Pilot phase | Budget guardrails, caching, retry with backoff, async peak shaving | Cost per task, rate-limit rate, P95 latency |
| After launch | Log metrics, monitoring alerts, multi-model routing, regular regression | Capacity forecast and optimization checklist |
Back to the original question: how do you evaluate an LLM? The answer is not the brilliance or disappointment of any single conversation, but a sustainable mechanism—use a stratified evaluation set to measure capability, cost per task to measure economics, and concurrency, latency, and error rate to measure engineering maturity, then use budget guardrails and routing strategies to turn the conclusions into a controllable operating state. When quota no longer “burns through unnoticed,” evaluating a model shifts from subjective impressions to decisions that are quantifiable, reproducible, and grounded in engineering.
