How to Evaluate an LLM: Model Selection Through Cost, Quota, and Performance Constraints

    Evaluating a large language model goes far beyond answer quality. Many teams judge on quality scores alone, then hit rate limiting, queuing, and expiring quota after launch—and sometimes burn quota on low-value calls only to conclude the model is "bad." This guide reframes model evaluation as a set of measurable, governable engineering concerns. It shows how to build a per-call token cost model, apply token-based rate limiting, bound concurrency, handle retry and backoff, prioritize tasks, design degradation paths, route across model tiers, streamline context, cache results, and set up observability with tiered alerts. It also presents a four-dimension selection framework—quality, cost, performance, and stability—alongside quota governance practices. Baidu AI Cloud appears only as an example of a general cloud platform; every technique applies equally to self-hosted inference and model APIs from any provider.

    On model selection, “how good are the answers” is only the first layer of evaluation. Many teams are still stuck at the stage of looking only at quality scores, and after going live they repeatedly run into rate limiting and queuing, or discover right before a resource package expires that they could never have used it all. More concerning is another scenario: as quota nears expiration, people make calls with no business value just to “avoid waste,” and then conclude that “the model isn’t good.” At that point, the root cause of the degraded experience often lies not in the model itself.

    This article evaluates no specific product. Instead, from a senior developer’s perspective, it breaks these problems into measurable, governable engineering elements, and presents a cost accounting method for model calls, a quota governance approach, and a model selection evaluation framework. Baidu AI Cloud appears only as an example of a general cloud platform; all practices apply equally to self-hosted inference services and model APIs from any vendor.

    1. First, Separate Two Things: Model “Quality” vs. Call “Quality”

    The experience in everyday use is determined jointly by at least four layers:

    1. Model capability: depth of reasoning, instruction following, context understanding, output stability, and so on. These factors are the easiest to perceive, yet the most often treated as the sole cause of “bad experience.”
    2. Cost and quota: how many tokens each call consumes, how much billing quota remains, and whether it is close to expiring.
    3. Rate and concurrency: limits such as requests per minute (RPM), tokens per minute (TPM), and maximum concurrency. Much of what users perceive as “queuing” is really the client-side or server-side manifestation of these limits.
    4. Platform scheduling and capacity: resource contention at peak times, regional capacity differences, and the resulting latency fluctuations.

    The last three layers are engineering constraints. In resource-constrained environments, their impact on everyday experience can sometimes exceed the subtle differences in model capability itself. So before evaluating a model, answer three questions first:

    • Has my usage formed a stable business loop?
    • Are the per-call token cost and latency within budget?
    • Can the quota last through the next billing cycle, and be spent on things that actually matter?

    2. Four Categories of Constraints: The Roots of Queuing, Rate Limiting, Rejection, and Quota Waste

    Reducing vague feelings of “it’s not usable” to concrete constraints is the first step toward governance:

    Constraint type Typical symptom Trigger mechanism How to address
    Billing quota exhausted Requests are rejected outright; completely unavailable within quota Resource package or prepaid credit used up Forecast consumption ahead, top up in time, set a buffer watermark
    Rate limit (RPM/TPM) Bursts of concentrated calls fail in large numbers, mostly 429s Requests or tokens per unit time exceed the limit Client-side token bucket, peak shaving, backoff retry
    Concurrency limit Failure rate rises noticeably under multi-threaded or multi-instance workloads Simultaneous in-flight requests exceed the limit Bound in-flight requests with a semaphore; queue and degrade
    Queuing and latency Succeeds, but responses are slow and jittery Resource contention during peak hours Priority queues, timeout budgets, async processing
    Quota waste Quota expires unused, or calls with no value are made to “use it up” Consumption rate far below quota supply rate Forecast expiration consumption, defer usage, tier by need

    “Quota waste” deserves separate emphasis. Burning through the balance with tasks that have no business value as quota nears expiration is a classic case of ineffective consumption:

    • Uncontrollable consumption: such calls have no clear success criteria and easily trigger repeated retries and ever-increasing usage;
    • No data value: ineffective calls don’t accumulate into reusable evaluation sets or feedback samples;
    • Misleading judgment: after the quota is burned through and rate limiting and queuing appear, people attribute it to “the model being bad,” when the real cause is out-of-control budget planning.

    The right approach: consume evenly according to business priority within the billing cycle, and give every call a clear success criterion.

    3. Capacity Planning: Start by Calculating Token Consumption

    3.1 The Cost Model of a Single Call

    A single call’s consumption can be abstracted as:

    1. single-call consumption (tokens) = input side + output side
    2. input side = system prompt + business input + retrieved context + conversation history
    3. output side = min(actual generated length, max output length limit)

    The input side is usually underestimated. In retrieval-augmented scenarios, the document chunks spliced into the prompt often account for the bulk of the input; in multi-turn conversations, history grows roughly linearly with turns if it isn’t trimmed.

    3.2 Four Easily Overlooked Details

    1. Retries are also cost: the input of a failed request is billed too. If the retry rate is r and each call retries at most n times, actual consumption is roughly 1 + r × n times the theoretical value.
    2. Streaming output only affects first-token latency: it improves perceived speed, but the total token count is essentially unchanged, so it can’t be treated as a cost-saving measure.
    3. Multimodal inputs are converted by volume: images, audio, and the like usually convert into a sizable number of tokens, and this cost should be measured separately from text.
    4. Different versions may be priced differently: different versions of the same model may differ in unit price and billing rules. Consumption estimates should match the version actually being called.

    3.3 Rough Estimation and Precise Statistics

    In the prototype stage, you can first convert tokens roughly, then calibrate against representative samples using the usage field returned by the API. Returned fields typically include input tokens, output tokens, and total tokens:

    1. # Rough estimate: empirical values for mixed Chinese-English text, for capacity estimation only; official billing follows the API response
    2. def rough_tokens(text: str) -> int:
    3. ascii_chars = sum(1 for ch in text if ord(ch) < 128)
    4. non_ascii = len(text) - ascii_chars
    5. return int(ascii_chars / 4 + non_ascii * 1.5) + 1
    6. def estimate(req_in_chars: str, max_out_tokens: int,
    7. history_turns: int, rag_chunks: int) -> dict:
    8. base_in = rough_tokens(req_in_chars)
    9. hist_in = history_turns * 500 # assume ~500 tokens of history per turn
    10. rag_in = rag_chunks * 400 # assume ~400 tokens per retrieved chunk
    11. sys_in = 200 # system prompt
    12. return {
    13. "input_tokens": sys_in + base_in + hist_in + rag_in,
    14. "output_tokens": max_out_tokens,
    15. }
    16. # Metering fields in the API response (field names may vary slightly across platforms)
    17. usage = {"prompt_tokens": 1800, "completion_tokens": 320, "total_tokens": 2120}

    With a single-call estimate, multiply by daily call volume to get a capacity baseline. In practice, add a 20%–40% margin on top to cover retries, traffic spikes, and context growth.

    3.4 The Impact of Caching on Capacity

    For scenarios with highly concentrated question distributions, such as knowledge Q&A and FAQs, adding a caching layer can significantly reduce model call volume:

    1. effective call volume = total requests × (1 − cache hit rate) × retry amplification factor

    Assuming a 40% cache hit rate and a retry amplification factor of 1.1, effective call volume is only 66% of the theoretical value. If you buy quota based on the theoretical value anyway, you create long-term systematic waste.

    4. Engineering Governance: Making Call Volume Controllable and Predictable

    4.1 Token Bucket: Token-Based Rate Limiting

    Rate limiting by request count can’t handle the case of “not many requests, but each with a very long context.” Suppose the RPM limit is 60 but each call inputs 20,000 tokens; the actual TPM then reaches 1.2 million, easily exceeding the token-based rate limit. A more sensible approach is to change the token bucket’s unit of measurement to tokens:

    1. import random
    2. import threading
    3. import time
    4. class TokenBucket:
    5. """Token-based bucket: each call deducts by actual token count"""
    6. def __init__(self, capacity: int, refill_per_sec: float):
    7. self.capacity = capacity # bucket capacity, i.e., allowed instantaneous burst
    8. self.refill = refill_per_sec # token refill rate (tokens/sec)
    9. self.tokens = float(capacity)
    10. self.ts = time.monotonic()
    11. self.lock = threading.Lock() # ensures atomic deduction under multi-threading
    12. def _refill(self):
    13. now = time.monotonic()
    14. self.tokens = min(self.capacity,
    15. self.tokens + (now - self.ts) * self.refill)
    16. self.ts = now
    17. def acquire(self, cost: int, max_wait: float = 5.0) -> bool:
    18. """Try to reserve cost tokens for one call, waiting at most max_wait seconds"""
    19. deadline = time.monotonic() + max_wait
    20. while True:
    21. with self.lock:
    22. self._refill()
    23. if self.tokens >= cost:
    24. self.tokens -= cost
    25. return True
    26. need = cost - self.tokens
    27. wait = need / self.refill
    28. if time.monotonic() + wait > deadline:
    29. return False # hand off to the upper layer for degradation or queuing
    30. time.sleep(wait)
    31. # Example: 60000 tokens per minute, burst cap of 120000 tokens
    32. bucket = TokenBucket(capacity=120000, refill_per_sec=60000 / 60)

    Note that a token bucket can only align local call rate with quota; it cannot eliminate platform-side resource contention at peak times. If queuing is severe in certain windows and your business isn’t latency-sensitive—for example batch jobs like offline report generation, data cleaning, and knowledge base construction—you can proactively schedule them off-peak.

    4.2 Concurrency Control: Bounding In-Flight Requests

    Many platforms, beyond RPM/TPM, also limit the number of simultaneously in-flight requests. Multi-threaded or multi-instance programs see a clear rise in failure rate during traffic peaks. Bounding in-flight requests with a semaphore on the client side is cheap and effective:

    1. import threading
    2. from concurrent.futures import ThreadPoolExecutor
    3. sem = threading.BoundedSemaphore(4) # no more than 4 concurrent in-flight requests
    4. def guarded_call(payload):
    5. with sem: # blocks and waits automatically when a permit isn't available
    6. return call_model(payload) # call_model is the actual invocation wrapper
    7. with ThreadPoolExecutor(max_workers=16) as pool:
    8. results = list(pool.map(guarded_call, payloads))

    The thread pool size can exceed the semaphore count, so that queuing happens inside the process rather than hitting the server as a flood of failed requests.

    4.3 Retry and Backoff: Only Retry Failures Worth Retrying

    Not every error is worth retrying. Deterministic errors like malformed requests, context overflow, and content moderation rejections will only repeat the failure and waste quota. They need to be handled distinctly:

    1. RETRYABLE_STATUS = {408, 409, 425, 429, 500, 502, 503, 504}
    2. RETRYABLE_EXC = (TimeoutError, ConnectionError)
    3. def call_with_backoff(fn, max_attempts: int = 4,
    4. base: float = 1.0, cap: float = 20.0):
    5. for attempt in range(max_attempts):
    6. try:
    7. return fn()
    8. except Exception as e:
    9. status = getattr(e, "status_code", None)
    10. retryable = status in RETRYABLE_STATUS or isinstance(e, RETRYABLE_EXC)
    11. if not retryable or attempt == max_attempts - 1:
    12. raise # deterministic error or retries exhausted: raise directly
    13. # exponential backoff + random jitter to avoid a second wave from many clients retrying simultaneously
    14. delay = min(cap, base * (2 ** attempt))
    15. time.sleep(random.uniform(0, delay))
    16. raise RuntimeError("unreachable")

    For writes or calls that produce side effects, also carry an idempotency key to avoid duplicate processing caused by retries.

    4.4 Priority Queue: Reserving Limited Quota for High-Value Tasks

    When request volume exceeds quota and all tasks queue equally, high-value online interactions get dragged down by low-value background jobs. Introducing a priority queue and degrading by policy when the queue backs up is a more robust approach:

    1. import heapq
    2. import itertools
    3. from dataclasses import dataclass, field
    4. @dataclass(order=True)
    5. class Task:
    6. priority: int # smaller value = higher priority
    7. seq: int # within the same priority, order by enqueue sequence (FIFO)
    8. name: str = field(compare=False)
    9. est_tokens: int = field(compare=False)
    10. _seq = itertools.count()
    11. class PriorityQueue:
    12. def __init__(self, capacity: int = 10000):
    13. self.heap = []
    14. self.capacity = capacity
    15. def push(self, name: str, est_tokens: int, priority: int = 5):
    16. if len(self.heap) >= self.capacity:
    17. raise OverflowError("queue full") # trigger degradation or fast-fail
    18. heapq.heappush(self.heap, Task(priority, next(_seq), name, est_tokens))
    19. def pop(self):
    20. return heapq.heappop(self.heap) if self.heap else None
    21. # Tiering example: 1 = online interaction, 3 = internal tools with lower real-time needs, 5 = offline batch
    22. q = PriorityQueue()
    23. q.push("customer service live Q&A", est_tokens=2500, priority=1)
    24. q.push("knowledge base offline build", est_tokens=8000, priority=5)
    25. task = q.pop() # online interaction tasks come out first

    Offline batch jobs can further leverage infrastructure common on general cloud platforms—asynchronous batch tasks, message queues, and so on—to run off-peak during business lulls, further reducing interference with online requests.

    4.5 Degradability: Preparing a Plan B for Every Capability

    Degradation strategies should be decided at the design stage, not improvised when quota runs out:

    • Model tier routing: route simple tasks to a lower-cost model, escalating only for complex tasks;
    • Rule fallback: when quota is exhausted or rate limiting persists, FAQ-type questions return the retrieved standard answer directly;
    • Cache fallback: reuse existing results for similar historical questions;
    • Async: convert non-real-time tasks to “submit and notify the result,” avoiding long user waits;
    • Friendly prompts: return structured error codes and clear messages for easy frontend display and user self-service.

    5. Cost Optimization: Getting the Same Work Done for Less

    5.1 Model Tier Routing

    Many requests don’t need the strongest model. Doing intent recognition first and deciding whether to escalate often saves substantial cost:

    1. def route(task: dict) -> str:
    2. if task["need_reasoning"] or task["input_tokens"] > 16000:
    3. return "flagship" # flagship tier: complex reasoning, long context
    4. if task["category"] in ("chitchat", "format", "extract"):
    5. return "light" # light tier: chitchat, format conversion, simple extraction
    6. return "standard" # standard tier: general Q&A
    7. # When the light tier fails, automatically escalate to the standard tier and retry once
    8. def execute(task: dict):
    9. tier = route(task)
    10. try:
    11. return call_model(task["prompt"], model=tier)
    12. except Exception:
    13. if tier == "light":
    14. return call_model(task["prompt"], model="standard")
    15. raise

    5.2 Context Streamlining

    • Dedup and truncate retrieved chunks: take Top-K by relevance instead of splicing all recall results;
    • Rolling summaries of conversation history: compress early history into a summary and keep only the most recent few turns verbatim;
    • Streamline the system prompt: remove redundant instructions and front-load key constraints.

    These practices not only reduce token consumption but also reduce interference from irrelevant information on model output.

    5.3 Constraining Output Length

    Explicitly set a maximum output length, and use the prompt to require “conclusion first, then supporting evidence.” Output length often contributes to billing no less than input, especially for reasoning tasks that tend to generate lengthy chains of thought. If you need the model to reason before answering, split reasoning and the final answer into two calls, and meter only the final answer portion.

    5.4 Caching and Hit Strategy

    • Exact cache: use a hash of the prompt and key parameters as the key; suitable for FAQs and templated tasks;
    • Semantic cache: match similar questions via vector retrieval for a higher hit rate, but it needs an extra index to maintain and a similarity threshold to avoid returning irrelevant results;
    • Cache invalidation: clear the cache in sync when associated knowledge updates, to prevent returning stale answers.

    Cache storage can live in a general cache service such as Redis, or in local memory.

    6. Observability: Making Every Call Accountable

    Model evaluation without data support easily stays at the level of subjective impressions. It’s recommended to instrument the call path uniformly and record at least the following fields:

    Field Purpose
    Request ID, scenario tag, model tier Break down cost by business dimension
    Input/output token counts Account for consumption, detect context bloat
    Cache hit or not Evaluate cache strategy effectiveness
    First-token latency, total time Analyze queuing and performance bottlenecks
    Retry count, error codes Locate rate-limiting and failure causes
    Call source (online/offline) Evaluate priority scheduling effectiveness

    On this basis, configure tiered alerts:

    • Daily consumption reaches 70% of budget: prompt for attention;
    • Consumption rate deviates markedly from the historical baseline: possibly a prompt change or context bloat;
    • 429 error share stays above 5%: adjust rate-limit parameters or request a higher quota;
    • Remaining quota insufficient to last to the end of the billing cycle: trigger a top-up or a degradation plan.

    These capabilities can be built on general offerings from cloud platforms such as Baidu AI Cloud, like logging services and monitoring/alerting; the technical approach is the same as a self-built solution.

    7. Selection Evaluation: Measuring All Four Factors with One Baseline

    “Which model is better” out of context is hard to answer. A more reliable approach: sample from real business to build an evaluation set that covers typical and long-tail tasks, compare candidate models horizontally with the same process, and record all four categories of metrics for every sample:

    Dimension Key metrics Notes
    Quality Task success rate, factual accuracy, human rating Judge against criteria defined by the business
    Cost Average tokens per task, cost per task Statistically measured on the real input distribution, not theoretical values
    Performance First-token latency P50/P95, total time P95 Sampling that covers business peak hours
    Stability Error rate, rate-limit trigger rate, output format compliance rate Including final results after retries

    Evaluation results can be aggregated into a weighted composite score, with weights adjusted dynamically by business stage. For example, in user-facing real-time scenarios, the weights on latency and stability should exceed that on cost; offline batch scenarios are the reverse:

    1. # Each metric is normalized to [0, 1], higher is better; weights sum to 1
    2. def weighted_score(metrics: dict, weights: dict) -> float:
    3. return sum(metrics[k] * w for k, w in weights.items())
    4. scores = {
    5. "model_a": {"quality": 0.88, "cost": 0.62, "latency": 0.71, "stability": 0.90},
    6. "model_b": {"quality": 0.92, "cost": 0.45, "latency": 0.55, "stability": 0.85},
    7. "model_c": {"quality": 0.81, "cost": 0.90, "latency": 0.88, "stability": 0.93},
    8. }
    9. online_weights = {"quality": 0.35, "cost": 0.15, "latency": 0.30, "stability": 0.20}
    10. batch_weights = {"quality": 0.40, "cost": 0.35, "latency": 0.05, "stability": 0.20}
    11. for name, m in scores.items():
    12. print(name, round(weighted_score(m, online_weights), 3),
    13. round(weighted_score(m, batch_weights), 3))

    At the same time, mind the validity of the evaluation method itself:

    • Avoid contamination: the evaluation set must not appear in any model’s training data, or scores will be inflated;
    • Fix parameters: use the same parameters such as temperature across candidate models to ensure comparability;
    • Sample multiple times: generative output is stochastic, so run the same model multiple times and take the mean, to avoid random results skewing conclusions.

    After a model goes live, keep validating continuously with small-traffic canary releases, and always retain the ability to roll back quickly to the previous version.

    8. Quota Governance: Putting the Budget Where It Counts

    Quota management and capacity planning are two sides of the same coin. Whether using a self-hosted service or resource-package offerings from cloud platforms such as Baidu AI Cloud, the following principles apply:

    1. Don’t hoard quota overnight: forecast remaining quota within the billing cycle from historical consumption curves, and adjust usage strategy ahead of time, rather than scrambling to use it up in the last few days before expiration;
    2. Institutionalize priority: online interaction > internal tools > offline batch; guarantee in this order when quota is tight;
    3. Defer, don’t scramble: if quota genuinely won’t be used up, prioritize scheduling planned batch jobs to run within the quota validity window, rather than manufacturing temporary demand;
    4. Review regularly: after each billing cycle, compare three data points—budget consumption / quota supply / business output—as the basis for the next cycle’s procurement and quota requests.

    9. Implementation Checklist

    • Define the four limits—RPM, TPM, concurrency, and quota—and set buffer watermarks
    • Complete a single-call token cost estimate based on the real input distribution
    • Implement client-side token bucket rate limiting and a concurrency semaphore
    • Distinguish retryable from non-retryable errors, and configure exponential backoff and idempotency keys
    • Build a task priority queue and degradation plans
    • Implement model tier routing, context streamlining, and caching strategies
    • Instrument the call path and configure cost and rate-limit alerts
    • Build a business evaluation set and assess it across four dimensions: quality, cost, performance, and stability
    • Establish a quota-usage review mechanism to consume evenly by priority

    Conclusion

    Evaluating a model isn’t just about whether it “sounds human”; it’s about whether it can reliably and economically support the business loop under real cost and quota constraints. Once you’ve built up engineering practices—capacity planning, rate-limit governance, caching and tier routing, and observable alerting—model selection shifts from a feeling-based debate into an engineering practice that can be quantified, rolled back, and continuously optimized. At that point, what limits the experience will no longer be quota and queuing, but the goals you set for the business itself.