Evaluating New LLMs for Inference Cost and Coding Capability
New model releases often come with benchmark rankings, speed figures, and prices that may not reflect real workloads. This article presents a reusable evaluation framework for newly released LLMs, covering task quality, total cost per successful task, tail latency, cache-aware pricing, and multi-agent orchestration. It also explains how to build a real-task evaluation set, calculate coding metrics such as pass@k, convert unit prices into cost per task, and avoid common mistakes when balancing speed and quality.
1. Why Systematic Evaluation Matters After Release
LLM providers release new versions regularly. Release materials often provide benchmark rankings, speed numbers, and prices. These figures may not hold in your own business context. Benchmark tasks differ from real requirements, and input length distribution, concurrency pressure, and cache hit rate can all change the final conclusion. Teams therefore need a reusable evaluation method that measures candidate models against the same standard.
Evaluation should answer three questions: whether the model can complete our tasks, what the unit cost is to complete one task, and whether it can deliver reliably under our latency requirements. All three are necessary. Answering only one makes model selection error-prone. For example, if one model has the highest quality but its cost per task is five times that of another model, the team must decide whether the quality gap is worth the expense.
2. Breaking Down Five Core Evaluation Dimensions
2.1 Task Completion Quality
Quality is the baseline. Tasks should be split by business category, such as code modification, troubleshooting document generation, long-document summarization, and data analysis Q&A. Each category needs quantifiable judgment criteria, such as test case pass rate, factual consistency, and compliance rate of structured output. Looking only at an aggregate score can easily hide obvious weaknesses in a particular task category.
If the evaluation scope includes coding capability, build separate code-related metrics instead of using an aggregate score. Common metrics are listed below:
| Metric | Definition | Use case |
|---|---|---|
| Unit test pass rate | Proportion of generated functions that pass pre-written test cases | Function-level coding |
| pass@k | Estimated probability that at least one of k samples for the same problem passes the tests | Compare the capability ceiling under multiple attempts |
| Patch apply rate | Whether the generated diff can be applied to the target codebase without conflicts | Repository-level changes |
| Repository-level task success rate | Proportion of changes where all relevant tests pass and human acceptance is also passed | Cross-file changes |
| Code review defect hit rate | Proportion of issues identified by the model that are confirmed as real defects, plus recall of known defects | Code review |
A common way to calculate pass@k is: sample n times for the same problem (n ≥ k), where c samples pass the tests, then
pass@k = 1 − C(n − c, k) ÷ C(n, k)
where C denotes the binomial coefficient. When the number of samples is small, you can also directly count the results of k independent calls, but the report must state the number of samples.
2.2 Total Cost per Task
Vendor list prices are charged per token, but the actual cost of a task also includes multi-turn calls, intermediate results returned by tools, failed retries, and repeated transmission of context. The correct lens is the total cost to complete a task: sum the cost of all calls, then divide by the number of successfully completed tasks. Failed calls are also billed, so do not count only the invoices for successful tasks.
2.3 Response Speed
Speed should be split into two metrics. Time to first token determines when the user starts waiting, while output throughput, or tokens generated per second, determines the completion time of long answers. Interactive scenarios care more about time to first token, while batch scenarios care more about throughput and total elapsed time.
Online services also need to look at tail latency. The statistical method is: sort all request latencies over a period from smallest to largest, and take P95 as the value at the 95th percentile, meaning 95% of requests are no slower than this time. Averages are easily skewed by a few very slow requests, so teams should record both P50 and P95. For time to first token, P95 measures the first token time of a streaming response; for total latency, P95 measures end-to-end task completion time. The implementation metrics below also use these two P95 values.
2.4 Pricing Structure and Context Window
In addition to base input and output unit prices, pay attention to cache-hit pricing. Repeated content such as system prompts, codebase snippets, and knowledge-base documents can significantly reduce input cost when it hits cache. When two models have similar base unit prices, the difference in cache hit rate may determine the final cost ranking.
Context window length determines whether complete material can fit in one request, but very long context often adds extra latency and must be verified through testing. A large nominal window does not mean quality and latency remain stable at that length.
2.5 Multi-Agent Orchestration Capability
More and more scenarios use a main model for planning and assign subtasks to multiple execution units for parallel processing. Evaluation should check whether the main model decomposes tasks reasonably, whether subtask results are correctly aggregated, and whether conflicts can be identified. Orchestration capability affects quality, cost, and latency at the same time, so it must be tested on the full workflow rather than only on individual subtasks.
3. Building an Evaluation Set from Real Tasks
The evaluation set is the foundation of the entire assessment. It is recommended to build it in the following steps:
- Extract real requests from online logs or manual curation, covering both high-frequency and high-value cases.
- Stratify by difficulty and category, keeping enough samples per stratum; a common size is dozens to hundreds of samples.
- Write judgment rules or reference answers for each sample, avoiding scoring only by subjective impression.
- Fix random seeds and temperature parameters so different models are compared under the same conditions.
- Hold out a portion of samples from tuning and use them only for final validation.
The following statistical framework calculates quality, cost, and latency together. Record usage for each model call separately, and put calls produced by retries in the same list:
import mathfrom dataclasses import dataclass@dataclassclass Usage:input_tokens: int # Total input tokens, including cache-hit tokenscache_hit_tokens: int # Cache-hit tokens, a subset of input_tokensoutput_tokens: int # Output tokens, based on API-reported usage@dataclassclass TaskResult:passed: bool # Whether the task passed the judgment rulescalls: list[Usage] # Usage for each call; calls after the first are retrieslatency_s: float # End-to-end task latency in seconds@dataclassclass Prices:input: float # Price per million non-cached input tokenscache: float # Price per million cache-hit tokensoutput: float # Price per million output tokensdef call_cost(u: Usage, p: Prices) -> float:uncached = u.input_tokens - u.cache_hit_tokensreturn (uncached * p.input+ u.cache_hit_tokens * p.cache+ u.output_tokens * p.output) / 1_000_000def percentile(values: list[float], q: float) -> float:s = sorted(values)k = max(0, math.ceil(q / 100 * len(s)) - 1)return s[k]def summarize(results: list[TaskResult], p: Prices) -> dict:if not results:raise ValueError("Evaluation results are empty; cannot compute metrics")total = retry_cost = failed_cost = 0.0passed_count = 0for r in results:if r.passed:passed_count += 1for i, u in enumerate(r.calls):c = call_cost(u, p)total += cif i > 0:retry_cost += cif not r.passed:failed_cost += clatencies = [r.latency_s for r in results]return {"pass_rate": passed_count / len(results),"cost_per_success": total / passed_count if passed_count else None,"retry_cost_share": retry_cost / total if total else 0.0,"failed_cost_share": failed_cost / total if total else 0.0,"p50_latency_s": percentile(latencies, 50),"p95_latency_s": percentile(latencies, 95),}
The core metric in this code is cost_per_success, the average cost per successful task. Calls for failed tasks also incur charges, so they are included in total cost. When there are no successful tasks, this metric returns None, and the report needs to explain this separately. retry_cost_share and failed_cost_share help identify where waste comes from. If retry cost accounts for a high share, output format constraints or tool calling are likely unstable; fix those issues before comparing model unit prices.
4. Converting Unit Prices into Cost per Task
Vendor prices are usually quoted per million tokens. When calculating cost per task, split input into two parts: cache-hit and non-cache-hit. Cache-hit tokens are already included in total input tokens and are a subset of input, so they must not be added to the full input again. The formula is:
Cost per task = (non-cached input tokens × input price + cache-hit tokens × cache price + output tokens × output price) ÷ 1,000,000
where non-cached input tokens = total input tokens − cache-hit tokens.
Three points require attention. First, history in multi-turn conversations is repeatedly counted in input, so actual input tokens are usually much higher than the length of a single user question. Second, output token prices are often higher, and some models may also bill generated reasoning content; use the usage reported by the API rather than estimating manually. Third, retries and failed calls must be included in cost just like successful calls.
When checking the cost accounting, confirm each item:
- Whether input tokens include historical conversation and tool-returned content.
- Whether cache-hit tokens are read separately from API usage fields and are not double-counted in input.
- Whether output tokens include reasoning content, and whether reasoning content is billed at the output price.
- Whether retries and calls reissued after timeouts have been included.
- Whether tool calls, retrieval, or other external services have separate charges.
Consider a hypothetical scenario: a task averages 20,000 input tokens and 2,000 output tokens, with 15,000 tokens hitting cache. Assume a model’s non-cached input price is CNY 10 per million tokens, cache-hit price is CNY 2 per million tokens, and output price is CNY 30 per million tokens. These prices are only for demonstrating the calculation method and do not represent the actual price of any model.
Non-cached input is 20,000 − 15,000 = 5,000 tokens. Substituting into the formula:
(5,000 × 10 + 15,000 × 2 + 2,000 × 30) ÷ 1,000,000 = CNY 0.14
If you add the full 20,000 input tokens and the 15,000 cache-hit tokens together, the result becomes CNY 0.29, overestimating cost by about one times. This error is most obvious in scenarios with a high cache hit rate, and model selection may therefore exclude a model that is actually cheaper.
5. Trade-offs Between Speed and Quality
A fast model is not necessarily suitable for every scenario. Choose according to business type:
- Interactive Q&A: prioritize time to first token. Slightly lower quality than the strongest model may be acceptable, but a clear quality floor must be set.
- Code generation and review: quality first. Longer latency is acceptable, but results must be verifiable through tests.
- Batch processing: prioritize throughput and unit cost. Faster or smaller models are suitable for standardized tasks, with spot checks on anomalous results.
A common approach is tiered routing: send simple requests to a fast model and escalate difficult requests to a high-quality model. Routing rules themselves must also be validated with the evaluation set to avoid misjudging difficulty and reducing quality. Routing also changes the cost structure. Escalated requests incur two calls, and this must be included in total cost.
Evaluation should also avoid several common mistakes: comparing only unit prices while ignoring cache hit rate; looking only at average latency while ignoring P95; and counting only successful calls while ignoring the cost of failures and retries.
6. Engineering Considerations for Multi-Agent Collaboration
When a main model is responsible for splitting tasks and submodels are responsible for execution, system complexity rises significantly. Implementation should focus on the following points:
- Task boundaries: subtask inputs and outputs should have a clear structure, such as an agreed JSON format, to make aggregation easier for the main model.
- Concurrency control: parallel execution shortens total elapsed time but amplifies rate limits and cost peaks, so concurrency caps are needed.
- Failure handling: when a single subtask fails, support partial retry rather than rerunning the whole workflow.
- Result validation: before aggregation, apply rule checks to subtask results, such as format, numeric ranges, and test results.
- Observability: record latency, usage, and status for each subtask to help locate cost anomalies.
An illustrative orchestration structure is shown below:
Main task├─ Planning: split into N subtasks├─ Parallel execution: subtasks 1..N (with timeout and retry)├─ Validation: format and rule checks└─ Aggregation: generate final result and record usage
Evaluation of an orchestration design must consider both quality and cost. Checking only whether the final answer is correct cannot reveal cost waste caused by repeated subtask retries.
7. Implementation Recommendations
- Define business metrics before choosing a model. Common metrics include task pass rate, cost per task, and P95 total latency.
- Use the same evaluation set and the same judgment rules for each evaluation to ensure comparability.
- Start with small-traffic canary releases, observe real user feedback and cost curves, and then decide whether to switch fully.
- Keep a fallback plan so you can switch to a backup model if the main model has an issue.
- Retest periodically. Model versions and prices change, and evaluation conclusions usually have a short shelf life.
When evaluating new models, use your own tasks, your own cost accounting, and your own latency requirements. Only then will the conclusions be reproducible and reusable in the next release.
