How to Evaluate Large Language Models for Production: Capability, Cost, and Latency
As large language models and AI coding tools keep evolving, many teams still pick models by trying one and going with a gut feeling. This article lays out a reusable evaluation methodology and summarizes common pitfalls, so teams can make repeatable, data-driven model-selection decisions. It covers how to break capability into measurable sub-metrics, how to calculate real per-task cost instead of headline pricing, how to measure latency with P95/P99 and timeout rates, and how to turn all of it into a lightweight engineering framework.
Introduction
Large language models and AI coding tools are updated constantly, yet many teams decide “which one to use” after a single trial based on intuition. This article presents a reusable evaluation methodology and summarizes common mistakes, helping teams make model-selection decisions that are repeatable, data-driven, and reviewable.
1. Why a Single Experience Is Not Enough
When selecting a large language model, an AI coding assistant, or a code-completion tool, many teams draw conclusions from one or two chat experiences, a single code-generation result, or one leaderboard ranking. The problem is that a single experience is neither stable nor reproducible: the same model can behave very differently under different prompts, context lengths, and network conditions. A truly rigorous evaluation is essentially a multi-dimensional trade-off problem with competing constraints.
In practice, you usually need to observe three categories of metrics at the same time:
- Capability: whether the task is completed correctly and completely.
- Cost: how many tokens (or platform-measured credits/quota) are consumed to complete the task.
- Performance: whether responses are fast enough, whether the service is stable, and whether long queues are required.
These three often conflict with each other. A more capable model usually has more parameters, higher inference cost, and possibly lower speed; pursuing low cost and low latency, on the other hand, may sacrifice output quality. So the evaluation goal is not to find the “strongest model,” but to find the option that is overall optimal across capability, cost, latency, and stability for a specific business scenario.
2. Capability Evaluation: Turn Subjective Feelings into Measurable Metrics
Capability evaluation is the core of model selection, but it is also the part most easily made subjective. Instead of directly asking “is this model good,” break capability down into measurable sub-metrics.
Correctness
Does the output meet expectations? Code-generation tasks can be measured by unit-test pass rate; information-extraction tasks by field accuracy; and question-answering tasks by hit rate against reference answers.Instruction Following
Does the model strictly respect constraints on format, length, language, role, and output structure? A model that is “smart but won’t follow the format” is often hard to use in engineering integrations.Long-Context Handling
With long inputs—an entire code repository, a lengthy document, or multi-turn conversation history—can the model reliably capture key information without missing important constraints?Output Stability
When the same or similar input is called repeatedly, are the results consistent? An unstable model increases the fault-tolerance cost of downstream systems and can cause inconsistent user experiences.
To reduce subjectivity, you can introduce simple scoring examples:
- Correctness: 0 means complete failure, 1 means pass; or use a 0–5 scale.
- Instruction following: 0 means wrong format, 1 means partial compliance, 5 means full compliance with all constraints.
- Code tasks: grade by compile failure, unit-test failure, partial pass, and full pass.
The key principle is: replace ad-hoc trials with a fixed test set. Pick 50 to 200 representative cases from real business scenarios, and lock down the prompts, input context, expected outputs, and scoring criteria. Running the same test set every time is what makes results comparable and reviewable.
3. Cost Evaluation: Look at Cost per Task, Not Just Unit Price
Cost is the dimension most likely to spiral out of control once you scale. Many teams initially focus only on “how much per thousand tokens,” but what really affects the budget is the total consumption to complete a single task. Token consumption mainly comes from three sources:
Input length
System prompts, user questions, conversation history, retrieved snippets, tool-call results, and code-repository context all count toward input cost. The longer the context, the higher the per-call cost.Output length
The more the model generates, the more it costs. On some platforms, the unit price of output tokens is higher than that of input tokens, so a “verbose model” can significantly amplify cost.Number of calls and retries
Multi-turn conversations, agentic tool calls, failed retries, and splitting oversized tasks can all multiply total consumption.
If you compare only unit prices, it is easy to misjudge. A model with a low unit price but verbose output, unstable formatting, and repeated retries may have a higher cost per task than a more expensive model that gets it right on the first try.
The recommended core metric is cost per task.
A more rigorous cost formula should distinguish input, output, and cache hits:
Cost per call =uncached input tokens × input unit price+ cached input tokens × cached input unit price+ output tokens × output unit priceCost per task = total cost to complete one typical task type / number of tasks
If the platform bills in credits, quota, or resource packages, first convert everything to a common measure:
Credits per task =input tokens × input credit factor+ output tokens × output credit factorAmount per task = credits per task × credit unit price
During evaluation, pay special attention to how total_tokens is defined. In most APIs, total_tokens may equal input tokens plus output tokens, but whether it includes the system prompt, conversation history, retrieval-augmented snippets, and cached tokens should be confirmed against the vendor’s documentation. For accurate cost calculation, it is best to record separately:
input_tokensorprompt_tokensoutput_tokensorcompletion_tokenscached_tokensor a cache-hit flagtotal_tokensretry_count- task duration
- failure or timeout status
If an API returns only total_tokens, you can do a rough evaluation first, but before formal procurement or budget planning you should add the input/output breakdown and clarify the unit-price basis; otherwise the cost is likely to be distorted.
4. Latency and Stability: Averages Are Not Enough—Look at P95, P99, and Timeout Rate
Latency directly determines interaction experience and system throughput. For real-time scenarios such as AI coding, code completion, and intelligent customer service, latency is especially critical. Core metrics include:
- Time to First Token (TTFT): the time from sending the request to receiving the first token, which determines whether the interaction feels responsive.
- Full response latency: the time from the request to the completion of the entire output, usually positively correlated with output length.
- Queue time: whether you have to wait for resources during peak hours.
- Timeout rate and error rate: whether requests fail or trigger retries.
- Tail latency: whether P95 and P99 degrade significantly.
In production, you cannot look only at average latency. Averages get pulled down by short requests and mask the experience problems caused by a few slow requests. For example, a model with an average latency of only 1.2 seconds but a P99 of 20 seconds may still feel unusable to users. So it is recommended to record at least:
request time, time to first token, completion time, queue time,output length, input length, status code, error type, retry count
You can build a time-segmented observation table:
| Date | Time window | Sample count | TTFT P95 | Full response P99 | Timeout rate | Avg. queue time | Main error |
|---|---|---|---|---|---|---|---|
| 2026-01-01 | 10 00 |
1200 | 1.1s | 6.8s | 0.4% | 0.2s | rate limiting |
| 2026-01-01 | 20 00 |
1500 | 2.8s | 18.6s | 2.7% | 3.4s | timeout |
During evaluation, pay special attention to real stress scenarios such as business peaks, holidays, and version-release days. For production systems, you can set thresholds, for example:
- Code-completion scenario: TTFT P95 not exceeding 800 ms to 1500 ms.
- Complex code-generation scenario: full-response P99 not exceeding the upper limit the business can tolerate waiting for.
- Critical endpoints: timeout rate below 1% and error rate below 0.5%.
5. Building a Reusable Evaluation Framework
Turning the capability, cost, and latency metrics into engineering code is what lets you make continuous, objective decisions. Below is a minimal evaluation framework example. In the code, client and grade are placeholder dependencies: you can replace them with a specific model SDK and a custom scoring function.
import timeimport mathdef grade(text: str, expected) -> int:# Placeholder dependency: replace with unit-test pass rate, field accuracy,# 0/1 scoring, or 0-5 scoringreturn 1 if text == expected else 0def percentile_nearest_rank(values, p: float):if not values:return Noneordered = sorted(values)rank = math.ceil(p * len(ordered))rank = min(len(ordered), max(1, rank))return ordered[rank - 1]def evaluate_model(client, test_cases, timeout_ms=60000):results = []errors = []for case in test_cases:start = time.time()try:resp = client.complete(case["prompt"], timeout=timeout_ms)latency_ms = (time.time() - start) * 1000usage = getattr(resp, "usage", {}) or {}results.append({"id": case["id"],"input_tokens": usage.get("prompt_tokens", 0),"output_tokens": usage.get("completion_tokens", 0),"total_tokens": usage.get("total_tokens", 0),"cached_tokens": usage.get("cached_tokens", 0),"latency_ms": latency_ms,"passed": bool(grade(resp.text, case["expected"])),})except Exception as e:errors.append({"id": case["id"],"latency_ms": (time.time() - start) * 1000,"error": str(e),})return summarize(results,errors=errors,input_price=0.0,output_price=0.0,cached_input_price=None,)def summarize(results,errors=None,input_price=0.0,output_price=0.0,cached_input_price=None):errors = errors or []if not results:return {"sample_count": 0,"error_count": len(errors),"pass_rate": None,"avg_total_tokens": None,"cost_per_task": None,"p95_latency_ms": None,"p99_latency_ms": None,}n = len(results)if cached_input_price is None:cached_input_price_local = input_priceelse:cached_input_price_local = cached_input_pricecost_sum = 0.0for r in results:cached = r.get("cached_tokens", 0)uncached_input = max(0, r["input_tokens"] - cached)cost_sum += (uncached_input * input_price+ cached * cached_input_price_local+ r["output_tokens"] * output_price)return {"sample_count": n,"error_count": len(errors),"pass_rate": sum(1 for r in results if r["passed"]) / n,"avg_input_tokens": sum(r["input_tokens"] for r in results) / n,"avg_output_tokens": sum(r["output_tokens"] for r in results) / n,"avg_total_tokens": sum(r["total_tokens"] for r in results) / n,"cost_per_task": cost_sum / n,"p95_latency_ms": percentile_nearest_rank([r["latency_ms"] for r in results],0.95),"p99_latency_ms": percentile_nearest_rank([r["latency_ms"] for r in results],0.99),}
This code has several key design choices:
- When
resultsis empty, it returns an empty result instead of crashing on division by zero. percentile_nearest_rankuses a boundary-safe percentile to avoidn * 0.95going out of range.- Cost calculation distinguishes input, output, and cache hits, rather than crudely estimating with a single
total_tokens. clientandgradeare explicitly marked as placeholder dependencies, making it easy to swap in a real model API and a business scoring function.
To make the metrics easier to scan and govern, you can maintain an evaluation metrics table:
| Metric | Field | Collection method | Example target threshold |
|---|---|---|---|
| Capability | pass_rate |
grade score or test pass rate |
Core tasks not below 90% |
| Cost per task | cost_per_task |
Computed from input/output/cached tokens and unit prices | Not above the budget ceiling |
| Time to first token | Requires capturing streaming first-packet time | Request start to first token returned | Code completion P95 below 1.5s |
| Full latency | latency_ms |
Request start to response end | Complex tasks P99 not above the business limit |
| Stability | error_count, timeout rate |
Error codes, timeouts, retry records | Timeout rate below 1% |
After the evaluation is complete, results can be stored in object storage, a logging service, or a metrics platform. But pay special attention to data compliance: do not save full raw prompts and model outputs by default. If business data contains sensitive information, at minimum apply sensitive-prompt masking, access control, retention-period management, and audit logging. For example, store only the task ID, a masked input summary, the score, token counts, latency, and error type; if raw text must be retained, define a clear retention period and an access-approval process.
6. Engineering Optimization: Reduce Cost and Increase Efficiency in Real Systems
Choosing a model is just the starting point. Over long-term operation, you should keep optimizing at the architecture level.
Context governance
Inject only the necessary information. Compress context through summarization, retrieval augmentation, and relevance filtering, rather than blindly stuffing in all history or entire code repositories. This is one of the most effective ways to reduce token consumption.Result caching
Cache outputs for identical or highly similar requests and return them directly on a hit, saving both tokens and latency. Cache keys can be generated from the model version, prompt template, normalized input, retrieved-snippet IDs, maximum output length, and so on. Note that the cache must have an invalidation strategy, and you should evaluate whether similar-request matching could cause incorrect hits. For content involving user privacy, also confirm whether caching is allowed, where it is stored, and how long it is retained.Model tiering and routing
Route tasks by complexity. Simple Q&A, format conversion, and code completion can go to lightweight models; complex reasoning, architecture design, and long-document analysis can be routed to more capable models—putting resources where they matter most.Budget and rate limiting
Set token, credit, request-frequency, and daily caps for users, teams, or applications. This prevents abnormal calls, retry loops, or malicious usage from quickly exhausting the quota.Asynchronous processing and queues
For latency-insensitive, high-volume tasks—such as code scanning, batch document summarization, and offline test generation—use message queues for asynchronous processing to smooth out peak pressure and improve overall throughput.
7. Common Mistakes Checklist
When evaluating a large language model or an AI coding tool, these mistakes are common:
- Judging from a single experience without a fixed test set.
- Looking only at unit price, not cost per task.
- Looking only at average latency, not P95, P99, and timeout rate.
- Ignoring the impact of retries, cache hits, and context length on cost.
- Ignoring data masking, permissions, and retention policies.
- Looking only at leaderboards, not your own business scenario.
- Looking only at peak capability, not production stability.
- Testing only happy paths, not abnormal inputs, boundary conditions, and high-concurrency scenarios.
8. Conclusion
Evaluating a large language model or an AI coding tool should not stop at “try it once and go with a feeling”; it should be a repeatable, reviewable, governable engineering effort. Break the evaluation into four dimensions—capability, cost, latency, and stability—quantify results with a fixed test set, and compare options horizontally using core metrics such as cost per task, P95/P99 latency, timeout rate, and stability. Only then can you cut through marketing claims and find the model that fits your business.
At the same time, through engineering practices such as context governance, result caching, model tiering and routing, budget and rate limiting, and asynchronous queues, teams can continuously balance capability, cost, and performance in real systems—moving from “knowing how to use the tool” to “using the tool well.”
00
00