LLM Evaluation and Cost Governance: A Practical Guide
This article presents a practical approach to evaluating and governing the cost of large language model (LLM) services. It covers a three-dimensional framework for assessing model capability, engineering performance, and cost; building a business-specific evaluation set; measuring latency, concurrency, and rate limiting; modeling unit task cost; managing quota and spend with caching, model routing, and asynchronous batching; and running a fast evaluation process. It also highlights common mistakes and explains how to turn model adoption from guesswork into measurable decisions.
LLM Evaluation and Cost Governance: A Practical Guide
Many teams have experienced a similar situation: credits or quota on a model platform are about to expire, and a noticeable balance remains, so teams pick low-importance tasks to “use up the quota.” These tasks are often lightweight work with low technical difficulty and high determinism requirements, such as labeling a batch of documents or extracting fields from unstructured text. However, after submission, the job stays queued far longer than expected.
This experience may seem incidental, but it reveals two common engineering problems:
- Lack of cost governance. A credit balance does not tell you how many real requests can still be served. A single quota can be consumed quickly, while unused remaining capacity is not planned.
- Lack of capacity assessment. A model that performs well can still fail to meet production SLAs during peak hours due to concurrency limits and queueing delays.
Therefore, evaluating an LLM cannot rely only on benchmark scores. It must answer three questions:
- How well does the model perform on my tasks?
- Can it stably handle my traffic volume?
- How long can it support my workload under my budget constraints?
The following sections describe an actionable evaluation and cost governance methodology.
1. Three-Dimensional Evaluation Framework: Capability, Engineering, and Cost
LLM evaluation can be broken down into three interrelated dimensions.
- Capability: model effectiveness on business tasks, such as classification accuracy, field extraction F1, and factual consistency of generated content.
- Engineering: latency percentiles (P50/P95/P99), throughput and concurrency, rate-limiting behavior, error-code distribution, and structured-output compliance rate.
- Cost: average token consumption per task, pricing structure, additional overhead caused by retries, and unit business cost.
All three dimensions are required. Looking only at capability may lead to poor performance under queue pressure after launch. Looking only at cost may hide higher downstream costs caused by wrong answers. Looking only at engineering may lead to selecting a model that is fast but produces low-quality answers.
In practice, teams can set qualification thresholds for each dimension and then use weighted scoring. For high-concurrency scenarios, the weight of P95 latency can be increased. For finance or government scenarios with strict consistency requirements, the capability dimension should be weighted more heavily.
2. Capability Evaluation: Build a Business-Aligned Evaluation Set
2.1 Task Layering and Sample Construction
Public leaderboards can only be used as a preliminary screening reference because the task distribution of leaderboards often differs greatly from real business workloads. A more reliable approach is to build a private evaluation set.
- Sampling sources: randomly select desensitized samples from production logs or historical tickets, covering both high-frequency scenarios and typical long-tail scenarios.
- Task layering:
- L1: information extraction, text classification, and formatting conversion, where answers can be judged directly by rules;
- L2: summarization, rewriting, and generation, which require human-annotated reference points or scoring rubrics;
- L3: multi-step reasoning, long-document QA, and tool calling, which require end-to-end acceptance cases.
- Scale reference: usually prepare one or two hundred valid samples for each layer. This is enough to distinguish candidate models while keeping manual review costs acceptable.
2.2 Scoring Design
Scoring methods should be designed by layer, combining automation and human review.
- L1 uses objective metrics such as exact match, field-level F1, and JSON parse rate;
- L2 uses key-point recall or rubric-based scoring;
- L3 uses task pass rate, meaning whether the final answer is correct and whether the tool-calling sequence is reasonable;
- all layers should track refusal rate and format violation rate.
Automated evaluation can be written as:
import json# Each case contains a unique ID, input, reference answer, layer, and acceptance type.CASES = load_cases("eval_set.jsonl")def evaluate(client, cases, judge):"""client: unified model-calling client; judge: function that scores a case based on its acceptance type."""results = []for case in cases:resp = client.chat(case["input"], temperature=0) # Disable sampling randomness during evaluation to ensure reproducibility.results.append({"id": case["id"],"layer": case["layer"],"type": case["type"],"passed": judge(case, resp.text),})return resultsdef summarize(results):"""Summarize pass rates by task layer for horizontal comparison of candidate models."""summary = {}for layer in {r["layer"] for r in results}:rows = [r for r in results if r["layer"] == layer]summary[layer] = round(sum(r["passed"] for r in rows) / len(rows), 3)return summary
2.3 Robustness and Difference Analysis
- Multiple sampling: call the same case multiple times and calculate the average pass rate and variance. Larger variance makes stable online performance more difficult.
- Robustness testing: use paraphrasing, typos, and word-order changes to observe whether results shift significantly.
- Error attribution: classify errors into prompt design, model capability, and input truncation due to excessive length. Only clear attribution can prevent prompt optimization and model replacement from being confused with each other.
- Instruction following: if the business depends on a fixed output format, such as strict JSON, include format violation statistics in evaluation.
3. Engineering Evaluation: Latency, Concurrency, and Rate Limiting
3.1 Measure Latency in Stages
- Use streaming output to measure time to first token (TTFT), and calculate average generation speed (TPS) by dividing total elapsed time by the number of output tokens;
- When sample size is small, averages can be skewed by long tails, so report P95/P99 percentiles as well;
- Record latency separately for cold start, after warm-up, and during peak periods to avoid overly optimistic conclusions based only on idle-time measurements.
3.2 Concurrency Step Testing
Higher concurrency is not always better. Teams need to find the “maximum stable concurrency without degrading quality.” A common approach is to increase load step by step and observe error rates, rate-limiting responses, and latency turning points:
| Concurrency level | Success rate | P95 latency | Rate-limiting / queueing ratio | Conclusion |
|---|---|---|---|---|
| Low (single digits) | Close to 100% | Baseline | None | Baseline reference |
| Medium (tens) | Slight decrease | Noticeably higher | Some | Working range for most small and medium businesses |
| High (hundreds) | Decreases | Significantly higher | Relatively high | Requires queueing and degradation |
Actual values vary by model size and business prompt length. They should be obtained through testing and should not be copied directly from others.
3.3 Rate Limiting and Backoff Retries
Most platforms impose concurrency limits and call quotas per unit time. Excessive instantaneous traffic can trigger rate limiting, which may appear as a clear rate-limit error code or as long request waiting times. Clients should implement exponential backoff with jitter:
import randomimport timeclass RateLimited(Exception):"""Corresponds to a rate-limiting error returned by the server."""def call_with_backoff(client, request, max_retries=3):for attempt in range(max_retries + 1):try:return client.chat(request)except RateLimited:if attempt == max_retries:raisetime.sleep(min(2 ** attempt, 8) + random.uniform(0, 0.5))
In production, teams should also add end-to-end tracing to the call chain, recording model name, input/output token counts, time to first token, total latency, and return codes, and connect logs to logging services and monitoring alerts. This makes it possible to determine within minutes whether the problem is slow business code or queueing in the model service.
4. Cost Evaluation: Build a Unit Task Cost Model
4.1 Clarify Billing Basis
Most platforms charge separately for input tokens and output tokens, and the output unit price is usually higher than the input unit price. Several easily overlooked billing details also matter:
- System prompts, few-shot examples, and multi-turn history messages all count toward input tokens;
- Some platforms support context caching, where input prefixes that hit the cache can be billed at a lower price, but this usually requires meeting conditions such as a minimum prefix length;
- The same data can produce different token counts when split by different tokenizers.
These details mean that the same “price per thousand tokens” can translate into costs that differ by several times in specific business scenarios.
4.2 Use Real Samples to Measure Token Distribution
Do not estimate prompt length by intuition. Instead, sample each scenario and measure the percentiles of input and output tokens, then plug them into formulas. For customer-service QA, for example:
Unit session cost = input tokens × input unit price+ output tokens × output unit price+ additional consumption caused by failed retries
If every turn carries the full conversation history, input tokens will grow linearly with the number of turns, and long sessions will cost much more than short sessions. It is recommended to use a sliding window or summary compression strategy for historical messages.
4.3 Budget Conversion and Capacity Estimation
With unit task cost in hand, “credits” can be converted into “number of requests that can be served”:
Supported requests ≈ available quota ÷ unit task cost
Then, combined with daily request volume and growth trends, estimate how many days the quota can last. This also helps determine whether the quota from one top-up or billing cycle can cover business goals. If not, teams should choose between scaling up or optimizing costs instead of reacting only after the quota is exhausted.
5. Quota and Cost Governance: Avoid Idle and Wasted Budget
Based on the problems above, governance can start from four areas.
5.1 Make Quota Visible and Fully Usable
- Build a quota dashboard that monitors remaining quota, average daily consumption, and estimated exhaustion time, with multi-level alerts at 30 days and 7 days before expiration;
- For quota that is genuinely at risk of expiring, plan consumption in advance: historical data backfill, offline document batch processing, non-real-time report generation, and similar tasks. These tasks do not depend on real-time responses, can run during off-peak hours, and can tolerate retries;
- It is not recommended to spend quota on random tasks that have little output value and where better solutions are known to exist.
5.2 Environment Separation and Quota Isolation
Assign independent credentials and quotas to development, testing, staging, and production to avoid joint testing or stress testing consuming production quota. On the production side, set call quotas for different business lines to prevent a non-core feature from exhausting all resources under abnormal conditions.
5.3 Caching, Model Tiering, and Asynchronous Processing
- Semantic caching: for high-frequency repeated questions, such as standard product inquiries, cache results using normalized text vectors or exact text fingerprints as keys, and set a reasonable expiration time to significantly reduce repeated calls;
- Model tiered routing: route simple tasks to smaller models or rule engines, and route only complex reasoning tasks to larger models. This reduces costs and also helps relieve peak-period queueing;
- Asynchronous processing and batching: decouple non-real-time tasks through a message queue and consume them with stateless worker nodes at a steady rate based on quota. This naturally smooths traffic peaks.
def route_task(task):# Send lightweight tasks to a small model and complex tasks to a large model.if task.need_reasoning or len(task.context) > 8000:return "large"return "small"def handle_batch(tasks, client, quota_limiter):for task in tasks:quota_limiter.acquire() # Token bucket controls call rate; block and wait if no token is available.client.chat(task, model=route_task(task))
5.4 Capacity Planning and Degradation
Set concurrency thresholds based on stress-test results. When the threshold is exceeded, prioritize the core path: send non-core requests to a queue, or degrade them to smaller models or even template-based replies. For example, a message queue can smooth instantaneous traffic spikes, and downstream consumers can process requests at a steady rate based on available concurrency, avoiding mass timeouts after many requests arrive at once. With these mechanisms, even if a model service is queued during peak hours, the business can degrade smoothly rather than fail outright.
6. Fast Evaluation Process: Five Steps
- Define boundaries (Day 1): determine task types, acceptance metrics, and cost red lines, such as the maximum unit task cost and maximum P95 latency.
- Build the evaluation set (Days 2–3): sample desensitized data, annotate reference answers, and divide tasks into layers.
- Blind-test candidate models (Day 4): hide model names and conduct cross-review, combine automatic metrics with human scores, and output a layered score table.
- Run stress tests and cost calculations (Day 5): execute concurrency step tests, measure real token distributions, and calculate unit task cost.
- Validate with canary rollout (after Day 5): launch with a small traffic share, continuously monitor quality, latency, and consumption, and retain a quick rollback switch.
7. Common Pitfalls
- Looking only at leaderboard scores: leaderboard distributions often differ from business distributions, which can distort conclusions.
- Drawing conclusions from a single test: generative tasks have sampling variance, and one run is not enough.
- Calculating only unit prices without tokens: real costs in long-prompt and long-history scenarios are often underestimated.
- Ignoring failures and retries: retry consumption caused by network jitter, rate limiting, and timeouts can be significant under high concurrency.
- Treating more quota as always better: quota has an expiration date, and poor planning can lead to rushed consumption before expiry or unused quota being lost.
8. Conclusion
The experience of “2,000 credits left and a queue that makes you give up” contains one valuable lesson: model selection must weigh effectiveness, engineering capacity, and cost in the same evaluation table. Building a private evaluation set, performing concurrency step testing, establishing a unit task cost model, reducing costs with caching and model tiered routing, and preparing degradation plans for peak hours can turn LLM adoption from guesswork into measurable decision-making. On platforms such as Baidu AI Cloud, teams can use unified LLM access and observability capabilities to incorporate the evaluation process into engineering standards, ensuring that every part of the budget is spent on tasks that truly create value.
