How to Scientifically Evaluate LLM Services and Control Usage Costs

    A practical guide to evaluating large language model (LLM) services with methods instead of gut feeling. It introduces a four-dimensional framework—quality, performance, cost, and governance—and shows how to build reliable evaluation sets, measure end-to-end latency and per-task cost, and apply usage-control strategies such as tiered routing, context engineering, and retry backoff. It includes illustrative code and a checklist of common pitfalls.

    1. Cognitive Bias in Model Selection: A Lesson from Personal Experience

    You often see descriptions like this about evaluating LLMs: “My membership is about to expire and I still have some quota left. Requests keep queuing up, so it feels wasteful not to use it. I set it to the big model to knock out a few complex tasks at once, and the quota was gone in no time.” This says nothing about the model’s intrinsic capability, yet it reflects a common pattern: people’s judgments about LLMs are often driven by an obvious “motivation bias” rather than rigorous engineering conclusions.

    Breaking this kind of description apart:

    • The evaluation motive is not neutral: The evaluation comes from “not wasting quota,” not from testing how the model performs on a specific task.
    • Trading intensity for quality: Deliberately picking the most complex tasks just to “burn through” quota means the sample does not represent everyday, real-world workloads.
    • Confused cost perception: Slow queuing and quota exhaustion are two different problems. The former is about capacity and scheduling, possibly caused by too many requests or overly long context; the latter is about usage and budget, tied to task complexity. Both get lumped together as “hard to use.”
    • No comparable baseline: There is no control result from other approaches on the same input, and no quantitative metrics such as accuracy, latency, or cost per task.

    If you only “pick a model by feel” in a personal setting, the cost is just some time or subscription fees. In an enterprise environment, that impact gets multiplied:

    1. Distorted procurement decisions: Selection is based on leaderboard rankings or personal experience rather than test results that fit the business.
    2. Misaligned capacity planning: Treating “long queues” as insufficient model capability, and “fast quota burn” as a slow model, when the real triggers may be call volume, context length, and retry strategy.
    3. Uncontrollable costs: Without usage attribution and budget constraints, a one-off spike during peak hours can blow past the budget.

    So the rest of this article won’t discuss any specific product. Instead, it abstracts the problem into a general engineering question: how to use a reusable, quantifiable method to evaluate the quality, performance, and cost of an LLM service, and to do proper usage governance on that basis.

    2. A Four-Dimensional Evaluation Framework: Quality, Performance, Cost, Governance

    2.1 Task Quality: Business Metrics Before Generic Leaderboards

    Generic leaderboards reflect a model’s average performance on public datasets, which may not match your business distribution. Quality evaluation should follow the principle of “business metrics first.”

    When building an evaluation set, cover the following dimensions:

    Evaluation dimension Focus Typical measurement
    Accuracy Consistency of answers with facts and reference answers Accuracy, F1, or the proportion of answers with verifiable sources
    Instruction following Adherence to format, length, and role constraints Automated pass rate, e.g., JSON parse success rate, word-count range hit rate
    Reasoning and code Multi-step logic, code runnability Unit test pass rate, manual review
    Long context Retrieval of key information from large passages “Needle in a haystack” localization tests, cross-paragraph summarization
    Stability Whether repeated calls on the same input are consistent Consistency across repeated samples, accounting for default sampling randomness
    Safety Sensitive information and compliance boundaries Block rate, false-block rate

    Evaluation set design requirements:

    • Stay close to the real data distribution: De-identified sampling from historical tickets, Q&A logs, and code repositories.
    • Moderate scale, automatable judgment: For example, 200–500 items per business scenario, prioritizing question types with automatically verifiable answers; use manual sampling review for open-ended questions.
    • Version control: Record inputs, expected outputs, and scoring criteria, and keep expanding them as the business evolves.
    • Double-blind review when necessary: Hide the model source and have multiple reviewers score independently to reduce preconceptions.

    Let a task’s accuracy be $p$ and the sample size be $n$. The half-width of the 95% confidence interval for the overall accuracy is approximately:

    $\Delta \approx 1.96 \times \sqrt{\frac{p(1-p)}{n}}$

    For example, suppose two candidate models measure 82% and 85% accuracy on a task, but the evaluation set has only 100 items. Here each result carries an error margin of about ±7.4 percentage points, and the two intervals overlap substantially. Concluding from this single round that the latter is better rests on weak evidence. Matching the evaluation set size, number of scenarios, and business risk level is the most easily overlooked basic skill in quality evaluation.

    2.2 Engineering Performance: Focus on the End-to-End Experience

    Performance evaluation is not just about “how fast.” In an LLM service, the lifecycle of a single request typically includes authentication, queuing, prefill, and decoding stages. The end-to-end experience is determined by several metrics together:

    • Time To First Token (TTFT): The time from sending a request to receiving the first output unit. It directly determines the “responsiveness” of interactive scenarios and is closely tied to input context length and queue wait time.
    • Time Per Output Token (TPOT): After the first output unit, the average interval between each generated output unit. It determines whether long text “streams out word by word” or “freezes for a long time then returns all at once.”
    • End-to-end latency: The total time to obtain the complete result, suited to measuring batch-type tasks.
    • Latency percentiles: Focus on P95 and P99, not the average. Averages hide queue jitter and occasional timeouts.
    • Throughput and concurrency: The system’s overall output units processed per second, and its stability under the target concurrency.
    • Streaming output and timeout strategy: Whether streaming is supported, and how client read timeouts and server request timeouts coordinate.
    • Availability and rate-limit behavior: Service level objectives, the response after rate limiting is triggered (e.g., returning a rate-limit status code and retry guidance), and whether graceful degradation is possible during failures.

    It’s worth emphasizing: TTFT and TPOT usually get worse as context length grows. If you stuff large blocks of background material “all at once” into the prompt, both first-token latency and inter-token intervals degrade, and users perceive this as “long queues” or “freezing.” In other words, “slow” and “burning quota” are often different symptoms of the same root cause: redundant context.

    2.3 Cost: Account by “Cost per Task,” Not by Unit Price

    LLM services are mostly billed in tokens, usually distinguishing input from output, and the unit prices for the two often differ. When comparing services, looking only at unit price is meaningless. You should convert everything into a cost per task:

    $C{\text{task}} = \bar{t}{in} \times p{in} + \bar{t}{out} \times p_{out}$

    where $\bar{t}{in}$ and $\bar{t}{out}$ are the average input and output tokens consumed by one task, and $p{in}$ and $p{out}$ are the corresponding unit prices.

    Key factors that affect cost include:

    • Context length: Repeated system prompts and lengthy background material push up input token consumption.
    • Output length: When open-ended tasks have no upper bound, output can far exceed expectations. Constrain answer length through parameters or prompts.
    • Retries and failed calls: Retries triggered by timeouts or rate limits also consume quota. If failure rates and retry counts aren’t tracked, the real cost is severely underestimated.
    • Accumulation across multi-turn conversations: Every turn carries the prior context, so total consumption can grow roughly quadratically with the number of turns. The comparison below illustrates standalone turns versus turn-by-turn accumulation.
    1. # Illustrative pseudocode: comparing token usage under two context strategies
    2. avg_input_per_turn = 800 # New input per turn (tokens), including system prompt and current question
    3. avg_output_per_turn = 500 # Output per turn (tokens)
    4. # Strategy A: resubmit the full history every turn (stateless calls)
    5. total_input_stateless = sum(
    6. avg_input_per_turn + (i - 1) * (avg_input_per_turn + avg_output_per_turn)
    7. for i in range(1, 11)
    8. )
    9. # Strategy B: submit only incremental content each turn (stateful service or self-maintained context)
    10. total_input_stateful = 10 * avg_input_per_turn
    11. print(f"Strategy A total input: {total_input_stateless} tokens") # 66500
    12. print(f"Strategy B total input: {total_input_stateful} tokens") # 8000

    For the same 10-turn conversation, input consumption differs by about 7x. This isn’t a “unique capability” of any particular service; it’s a direct result of a general design choice: who maintains the conversation state. Using a stateful service, or maintaining context on the application side with cache reuse, are both common approaches.

    2.4 Operations and Governance: Observability Determines Long-Term Sustainability

    Whether a model can reliably support a business over the long run depends on how complete its governance is:

    • Call logging and auditing: Record the request ID, model name, input/output token counts, status code, latency, and error type to support cost attribution and troubleshooting. Logs can simply land in general cloud products such as a logging service or object storage.
    • Monitoring and alerting: Set thresholds around error rate, P95/P99 latency, token consumption rate, and budget utilization, and notify responsible parties through a monitoring and alerting service.
    • Quotas and rate limiting: Apply rate-limiting strategies such as token buckets on the application side (e.g., at the API gateway), so a single business or an abnormal loop can’t monopolize the entire quota during peak hours.
    • Data security and compliance: Clarify whether data is used for model training, whether no-persistence calls are supported, the data residency region, and de-identify data per scenario.
    • Replaceability: Abstract a unified model access layer so you can switch quickly when quality, price, or availability changes, avoiding deep lock-in to a single service.

    3. An Actionable Evaluation Process

    Stringing these four dimensions into a flow yields a reusable evaluation loop:

    1. Define business metrics and acceptance thresholds: First decide “what level counts as usable,” e.g., task accuracy no lower than 85%, P95 first-token latency no higher than 2 seconds, and cost per task no higher than a given threshold.
    2. Build and lock down the evaluation set: Cover core scenarios, long-tail scenarios, and adversarial samples, with de-identification applied.
    3. Batch-call and record in a structured way: Run each candidate service on the same evaluation set, fully recording quality, performance, and consumption data.
    4. Automated scoring + manual spot checks: Batch-score questions that can be judged automatically; use double-blind review for open-ended ones; meanwhile compute cost per task and latency percentiles.
    5. Load testing and rate-limit verification: Simulate behavior under the target concurrency, and verify that backoff after rate limiting is triggered remains controllable.
    6. Canary rollout and continuous regression: Roll out by percentage in the early stage, watch business metrics and evaluation-set metrics simultaneously, and run automatic regression after model or prompt updates.

    The following is illustrative code for structured recording of each call:

    1. import time
    2. def record_call(record: dict) -> None:
    3. """Write one call record to a log; illustrative: print to stdout or send to a logging service"""
    4. print(record)
    5. def evaluate_once(client, prompt: str, model: str, tags: dict) -> dict:
    6. start = time.perf_counter()
    7. record = {
    8. "request_id": tags.get("trace_id", ""),
    9. "model": model,
    10. "project": tags.get("project", "default"),
    11. "env": tags.get("env", "test"),
    12. "prompt_tokens": 0,
    13. "output_tokens": 0,
    14. "status": "ok",
    15. "error_type": "",
    16. "latency_ms": 0,
    17. }
    18. try:
    19. # Illustrative pseudocode: use your provider's SDK/HTTP interface
    20. resp = client.chat(model=model, messages=[{"role": "user", "content": prompt}])
    21. record["prompt_tokens"] = resp.usage.prompt_tokens
    22. record["output_tokens"] = resp.usage.completion_tokens
    23. except Exception as exc:
    24. # Record only the error type to avoid writing sensitive data such as user input to logs
    25. record["status"] = "error"
    26. record["error_type"] = type(exc).__name__
    27. finally:
    28. record["latency_ms"] = int((time.perf_counter() - start) * 1000)
    29. record_call(record)
    30. return record

    4. Usage Control: Turning “Sufficient Quota” into “Good Usage”

    Back to the opening question: quota that “can’t be used up” is essentially insufficient demand or poor call design, while quota that “runs out” often reflects a lack of usage control. Usage governance can be summarized into the following six strategies.

    4.1 Tiered Routing: Send Simple Tasks to Lightweight Models

    Not every request needs the strongest, most expensive model. You can tier requests by task complexity:

    1. # Illustrative pseudocode: select a model tier based on task characteristics
    2. def route_model(task: dict) -> str:
    3. # Rule layer: deterministic tasks such as format conversion, keyword extraction,
    4. # and template filling should prefer rules or a light model
    5. if task["type"] in {"format_convert", "keyword_extract"}:
    6. return "light"
    7. # High-confidence simple intents (e.g., a knowledge-base FAQ hit) can return a cached answer directly
    8. if task.get("faq_hit", False):
    9. return "cache"
    10. # Route complex reasoning, long-document analysis, and code generation to a stronger model
    11. return "standard" if task["input_tokens"] < 8000 else "strong"

    The key to tiered routing is establishing a “task-to-model” mapping and validating with evaluation data that each tier’s accuracy meets business requirements.

    4.2 Context Engineering: Trim First, Then Cache, Then Compress

    • Trim: Remove repeated instructions and redundant background, keeping only material relevant to the current task.
    • Cache: Set content-hash caches for identical or similar requests (e.g., high-frequency Q&A), and return the answer directly on a hit.
    • Compress: For very long documents, first extract relevant passages via retrieval, or summarize the conversation history, before sending it to the model.

    4.3 Coordinating Streaming Output with Timeout and Retry

    Streaming output can significantly improve the interactive experience, but you must set a reasonable read timeout. Retries should follow general principles: retry only on retryable errors (rate limiting, timeouts, server errors); use exponential backoff with random jitter to avoid a retry storm; and set a maximum retry count and an overall budget cap.

    1. import random
    2. import time
    3. class RateLimitError(Exception):
    4. """Illustrative: rate-limit error"""
    5. class BudgetExceeded(Exception):
    6. """Illustrative: reached the max retry count or time budget for this task"""
    7. def call_with_backoff(client, request: dict, max_retries: int = 3,
    8. base: float = 0.5, cap: float = 8.0):
    9. for attempt in range(max_retries):
    10. try:
    11. return client.chat(**request)
    12. except RateLimitError:
    13. if attempt == max_retries - 1:
    14. raise BudgetExceeded("Retry limit reached; fall back or queue the request")
    15. # Exponential backoff + jitter to avoid many clients retrying at once
    16. delay = min(cap, base * (2 ** attempt)) * (0.5 + random.random())
    17. time.sleep(delay)

    4.4 Asynchronization and Peak Shaving

    Batch and offline tasks (e.g., document batch processing, report generation) don’t need real-time responses. Put them into a message queue for asynchronous processing and run them during business off-peak periods to stagger the load. This both eases rate limiting and improves overall throughput.

    4.5 Quotas, Budgets, and Attribution

    • Allocate call quotas per business and environment so a single business can’t monopolize all resources.
    • Set daily and monthly budget alert thresholds, and notify in advance when approaching them.
    • Tag every call with project, environment, and business line so you can attribute by dimension.
    • Log input, output, cache hits, and failures together to keep the cost-accounting basis consistent.

    4.6 Building a Governance Foundation on General Cloud Capabilities

    None of these strategies need to be built from scratch. They can be combined from general cloud product capabilities:

    • Deploy a unified model access gateway on a container platform, centralizing routing, rate limiting, and logging.
    • Use object storage to hold evaluation sets, de-identified samples, and call logs.
    • Use a logging service and monitoring and alerting to visualize token consumption and provide budget warnings.
    • Use a message queue to shave peaks and asynchronize batch tasks.

    Taking cloud platforms such as Baidu AI Cloud as an example, most of these capabilities already exist as corresponding general product categories and can be combined as needed to form a complete “evaluate–call–monitor–alert” chain.

    5. A Checklist of Common Pitfalls

    • Judging by leaderboards: Leaderboard scores are disconnected from business performance; the evaluation set is the reliable basis.
    • Looking only at unit price: Input/output ratios and context strategies vary widely across services; convert to cost per task.
    • Ignoring retry costs: Failing to count consumption from failed calls underestimates the real cost.
    • Blaming “slowness” entirely on the service: Lengthy context is itself a shared driver of both first-token latency and cost.
    • Making decisions on average latency: Averages hide the long tail; use P95/P99 percentiles.
    • Configurations that “only grow”: No output-length cap and unbounded context growth are common triggers of budget overruns.
    • Lacking canary rollout and rollback: Without regression evaluation after model or prompt updates, quality can decline unnoticed.

    6. Conclusion

    Evaluating an LLM service shouldn’t stop at personal impressions like “does it burn quota fast” or “does it queue for long.” It should come down to four quantifiable questions: Is the task done correctly? Is the response fast enough? How much does each task cost? And, when something goes wrong, how observable and controllable is it? Once evaluation is distilled into an evaluation set, monitoring metrics, and budget rules, usage control has a basis: instead of agonizing over unused quota, make every call happen on the right task, with the right model, and with the right context.