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.

    1. 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.

    2. 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.

    3. 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?

    4. 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:

    1. 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.

    2. 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.

    3. 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:

    1. Cost per call =
    2. uncached input tokens × input unit price
    3. + cached input tokens × cached input unit price
    4. + output tokens × output unit price
    5. Cost 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:

    1. Credits per task =
    2. input tokens × input credit factor
    3. + output tokens × output credit factor
    4. Amount 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_tokens or prompt_tokens
    • output_tokens or completion_tokens
    • cached_tokens or a cache-hit flag
    • total_tokens
    • retry_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:

    1. request time, time to first token, completion time, queue time,
    2. 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-11:00 1200 1.1s 6.8s 0.4% 0.2s rate limiting
    2026-01-01 20:00-21: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.

    1. import time
    2. import math
    3. def grade(text: str, expected) -> int:
    4. # Placeholder dependency: replace with unit-test pass rate, field accuracy,
    5. # 0/1 scoring, or 0-5 scoring
    6. return 1 if text == expected else 0
    7. def percentile_nearest_rank(values, p: float):
    8. if not values:
    9. return None
    10. ordered = sorted(values)
    11. rank = math.ceil(p * len(ordered))
    12. rank = min(len(ordered), max(1, rank))
    13. return ordered[rank - 1]
    14. def evaluate_model(client, test_cases, timeout_ms=60000):
    15. results = []
    16. errors = []
    17. for case in test_cases:
    18. start = time.time()
    19. try:
    20. resp = client.complete(case["prompt"], timeout=timeout_ms)
    21. latency_ms = (time.time() - start) * 1000
    22. usage = getattr(resp, "usage", {}) or {}
    23. results.append({
    24. "id": case["id"],
    25. "input_tokens": usage.get("prompt_tokens", 0),
    26. "output_tokens": usage.get("completion_tokens", 0),
    27. "total_tokens": usage.get("total_tokens", 0),
    28. "cached_tokens": usage.get("cached_tokens", 0),
    29. "latency_ms": latency_ms,
    30. "passed": bool(grade(resp.text, case["expected"])),
    31. })
    32. except Exception as e:
    33. errors.append({
    34. "id": case["id"],
    35. "latency_ms": (time.time() - start) * 1000,
    36. "error": str(e),
    37. })
    38. return summarize(
    39. results,
    40. errors=errors,
    41. input_price=0.0,
    42. output_price=0.0,
    43. cached_input_price=None,
    44. )
    45. def summarize(
    46. results,
    47. errors=None,
    48. input_price=0.0,
    49. output_price=0.0,
    50. cached_input_price=None
    51. ):
    52. errors = errors or []
    53. if not results:
    54. return {
    55. "sample_count": 0,
    56. "error_count": len(errors),
    57. "pass_rate": None,
    58. "avg_total_tokens": None,
    59. "cost_per_task": None,
    60. "p95_latency_ms": None,
    61. "p99_latency_ms": None,
    62. }
    63. n = len(results)
    64. if cached_input_price is None:
    65. cached_input_price_local = input_price
    66. else:
    67. cached_input_price_local = cached_input_price
    68. cost_sum = 0.0
    69. for r in results:
    70. cached = r.get("cached_tokens", 0)
    71. uncached_input = max(0, r["input_tokens"] - cached)
    72. cost_sum += (
    73. uncached_input * input_price
    74. + cached * cached_input_price_local
    75. + r["output_tokens"] * output_price
    76. )
    77. return {
    78. "sample_count": n,
    79. "error_count": len(errors),
    80. "pass_rate": sum(1 for r in results if r["passed"]) / n,
    81. "avg_input_tokens": sum(r["input_tokens"] for r in results) / n,
    82. "avg_output_tokens": sum(r["output_tokens"] for r in results) / n,
    83. "avg_total_tokens": sum(r["total_tokens"] for r in results) / n,
    84. "cost_per_task": cost_sum / n,
    85. "p95_latency_ms": percentile_nearest_rank(
    86. [r["latency_ms"] for r in results],
    87. 0.95
    88. ),
    89. "p99_latency_ms": percentile_nearest_rank(
    90. [r["latency_ms"] for r in results],
    91. 0.99
    92. ),
    93. }

    This code has several key design choices:

    • When results is empty, it returns an empty result instead of crashing on division by zero.
    • percentile_nearest_rank uses a boundary-safe percentile to avoid n * 0.95 going out of range.
    • Cost calculation distinguishes input, output, and cache hits, rather than crudely estimating with a single total_tokens.
    • client and grade are 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.

    1. 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.

    2. 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.

    3. 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.

    4. 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.

    5. 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.”