A Developer's Guide to Systematically Evaluating Large Language Models

    This article provides a systematic framework for developers to evaluate large language models (LLMs) in real-world applications. It covers defining evaluation goals, breaking down core metrics such as functional correctness, code quality, and context processing, and building reproducible datasets. Additionally, it explores setting up automated testing pipelines, conducting human reviews, interpreting results, avoiding common pitfalls, and integrating evaluations into your development workflow.

    1. Why Systematic Evaluation is Necessary

    When discussing model selection within a team, the common basis is personal experience: a model answered a question well once, or a generated piece of code ran successfully on the first try. While such impressions hold some value, they present three obvious problems. First, the sample size is too small; single results are heavily influenced by prompt wording, randomness, and daily server load. Second, personal focus varies—some prioritize reasoning, others code style—making horizontal comparisons difficult. Third, models update frequently, and last year’s impression may not apply to today’s version.

    The goal of systematic evaluation is to transform “it feels good to use” into quantifiable, reproducible, and traceable conclusions. By fixing the evaluation dataset, scoring rules, and execution environment, a team can quickly perform regression tests when upgrading or replacing models to determine if the new version genuinely improves business metrics.

    2. Define Evaluation Goals and Scenarios First

    Evaluation must first answer one question: what task is the model meant to solve? The weighting of different scenarios varies significantly.

    • Code Assistance: Focus on syntax correctness, API call accuracy, and whether modifications are strictly limited to the requirement scope.
    • Documentation and Knowledge QA: Focus on factual accuracy, verifiable citations, and reasonable refusal to answer.
    • Data Extraction and Structured Output: Focus on field completeness, format validity, and whether enumerated values exceed boundaries.
    • Customer Service or Conversational Applications: Focus on multi-turn consistency, tone and compliance, and the quality of human handover decisions.

    It is recommended that teams list two to three core metrics for each scenario and explicitly define the “passing line.” For example, in a structured output scenario, you might require a format validity rate of no less than 99% and a field-level accuracy of no less than 95%. Without a passing line, evaluation results are difficult to translate into deployment decisions.

    3. Break Down Core Evaluation Dimensions

    3.1 Functional Correctness

    Functional correctness is the most fundamental dimension. For tasks with standard answers, such as calculation, classification, or extraction, you can directly compare the output with the annotated result. For open-ended tasks, such as solution design, you need to design scoring rubrics that break down “good” into several judgeable sub-items, such as whether key constraints are covered, whether boundary conditions are omitted, and whether there are factually contradictory statements.

    3.2 Code Quality and Maintainability

    Code-related tasks cannot solely look at whether it runs. A qualified evaluation should simultaneously check:

    • Whether it can be compiled or interpreted successfully;
    • Whether it passes preset unit tests;
    • Whether irrelevant changes are introduced or existing interfaces are broken;
    • Whether naming, exception handling, and comments align with project conventions.

    Passing tests is the most reliable automated signal, but insufficient test coverage can overestimate the model’s capabilities, necessitating manual review.

    3.3 Context and Long Text Processing

    A model’s claimed context window length is not equivalent to its actual utilization capability. A common testing method is to embed key information at different positions within a long text (needle in a haystack) and then check if the model can accurately retrieve it. Tests should cover the beginning, middle, and end, and gradually increase the text length to observe where the performance inflection point occurs.

    3.4 Instruction Following and Structured Output

    In production environments, models often need to return content in a fixed format. Evaluations should include:

    • Whether it strictly follows the output format, such as only returning data in a specified structure;
    • Whether it can satisfy all constraints when facing multiple conditions;
    • Whether it still executes the original instruction when interference is added to the prompt.

    This dimension can be fully automated at a low cost and is suitable for integration into continuous integration (CI) workflows.

    3.5 Latency, Throughput, and Cost

    Latency is divided into time to first token and overall completion time, both of which affect interactive experience differently. Throughput determines the duration of batch processing tasks. Cost must be calculated based on actual input and output token usage, including the overhead of caching, retries, and failed requests. Teams should measure under identical concurrency and input length; otherwise, the numbers are not comparable.

    3.6 Stability and Compliance

    Stability refers to the fluctuation degree of outputs when the same input is run multiple times. This can be measured by fixing the random seed (if the API supports it) or sampling multiple times to calculate variance. The compliance dimension includes sensitive content handling, privacy information leakage risks, and copyright and licensing terms. When user data is involved, data processing agreements should be confirmed before evaluation to avoid transmitting real business data in unauthorized environments.

    4. Build a Reproducible Evaluation Dataset

    The evaluation dataset is the foundation of the entire methodology, and its quality determines the credibility of the conclusions. It is recommended to follow these principles:

    1. Real Sources: Prioritize anonymized sampling from production logs. Manually constructed samples can easily deviate from real distributions.
    2. Sufficient Coverage: Stratify by difficulty, category, and input length, retaining enough samples for each layer.
    3. Clear Annotations: Each sample should be accompanied by a standard answer or scoring rule, along with records of the annotator and the annotation basis.
    4. Version Management: Include the evaluation dataset and scoring scripts in version control. Any modifications should retain a change log.
    5. Prevent Contamination: The evaluation dataset should not overlap with the model’s training data, nor should it be directly used for prompt tuning; otherwise, results will be overly optimistic.

    A practical approach is to split the evaluation dataset into a “development set” and a “validation set.” The development set is used to adjust prompts and workflows, while the validation set is used only once during the final stage of model selection.

    5. Set Up an Automated Evaluation Pipeline

    Below is a simplified evaluation framework example, demonstrating how to organize model calls, checking logic, and latency statistics. Here, call_model is an adapter function interfacing with specific model services. Teams can implement it according to their platform’s API. The framework itself is vendor-agnostic.

    1. import time
    2. import json
    3. from dataclasses import dataclass
    4. from typing import Callable, List, Dict, Any
    5. @dataclass
    6. class TestCase:
    7. case_id: str
    8. prompt: str
    9. checker: Callable[[str], bool] # Returns True if passed
    10. def run_suite(call_model: Callable[[str], str],
    11. cases: List[TestCase]) -> List[Dict[str, Any]]:
    12. results = []
    13. for case in cases:
    14. start = time.perf_counter()
    15. try:
    16. output = call_model(case.prompt)
    17. passed = case.checker(output)
    18. except Exception as exc:
    19. output, passed = f"ERROR: {exc}", False
    20. latency = time.perf_counter() - start
    21. results.append({
    22. "id": case.case_id,
    23. "passed": passed,
    24. "latency_s": round(latency, 3),
    25. "output": output,
    26. })
    27. return results
    28. def summarize(results: List[Dict[str, Any]]) -> Dict[str, float]:
    29. total = len(results)
    30. passed = sum(1 for r in results if r["passed"])
    31. latencies = sorted(r["latency_s"] for r in results)
    32. p90_index = min(total - 1, int(total * 0.9))
    33. return {
    34. "pass_rate": passed / total if total else 0.0,
    35. "p50_latency_s": latencies[total // 2] if total else 0.0,
    36. "p90_latency_s": latencies[p90_index] if total else 0.0,
    37. }
    38. def check_json_fields(output: str, required: List[str]) -> bool:
    39. try:
    40. data = json.loads(output)
    41. except json.JSONDecodeError:
    42. return False
    43. return all(key in data for key in required)

    A few aspects of this framework are worth noting. First, exceptions are caught and counted as failures, preventing a single request error from interrupting the entire evaluation round. Second, latency statistics use a high-precision timer and output both the median and the 90th percentile, which better reflects long-tail scenarios than just looking at the average. Third, the checking logic is separated from the calling logic, meaning the same evaluation suite can interface with multiple model services, making results horizontally comparable.

    If the evaluation involves code generation, the checker can be replaced with a function that runs unit tests in an isolated sandbox. The sandbox must restrict network access and file system permissions to prevent side effects from generated code.

    6. Human Review and Consistency Checks

    Automated checks cannot cover semantic-level quality, such as whether explanations are clear or suggestions are reasonable. Human review requires the following measures:

    • Develop a scoring rubric, providing textual descriptions and examples for each score level;
    • Have at least two reviewers independently score each sample, calculate the inter-rater reliability coefficient, and organize discussions to revise the rubric if consistency is low;
    • Conduct random spot checks on review results to identify and correct systematic biases promptly;
    • Reviewers should be blind to the model’s identity to avoid preconceived notions.

    Consistency can be measured using the weighted kappa coefficient. Generally, a value above 0.6 is considered moderate to high consistency; below this level, the credibility of the conclusions is limited.

    7. Interpret Results and Make Decisions

    Once you have the data, you should not just look at the total score. It is recommended to analyze from the following perspectives:

    1. Scenario-by-Scenario Comparison: A comprehensive score might mask obvious shortcomings in a specific type of task.
    2. Categorize Failed Samples: Classify by failure reason to determine if the problem lies in understanding, reasoning, formatting, or knowledge.
    3. Cost vs. Quality Tradeoff: Plot the cost per task against the pass rate in the same coordinate system to find a reasonable cost-performance zone.
    4. Error Confidence: With small sample sizes, differences might just be random fluctuations; significance testing or repeated experiments are necessary.

    When making decisions, a layered strategy can be adopted: use the most stable, high-quality solution for high-risk tasks, supplemented by human review; for low-risk, high-frequency tasks, prioritize cost and latency. The same business can also use a routing mechanism to assign different models based on task type.

    8. Common Pitfalls

    • Equating benchmark scores with real-world performance. Public benchmarks and real business distributions often differ; ultimately, your proprietary evaluation dataset should be the standard.
    • Only testing happy paths. Failure cases, boundary inputs, and malicious inputs equally need coverage.
    • Ignoring the impact of prompts. The same model might perform vastly differently under different prompts. When comparing, fix the prompt, or evaluate the prompts as well.
    • Ignoring version changes. Providers may update models without notification, so you need to regularly rerun the evaluation dataset to establish a long-term baseline.

    9. Implementation Suggestions

    For most development teams, the following steps can be taken to advance:

    1. Sort out two to three core business scenarios and determine the metrics and passing lines.
    2. Extract 100 to 300 anonymized samples from production logs to form the first version of the evaluation dataset.
    3. Implement a unified call adapter layer and evaluation framework to ensure different models run under identical conditions.
    4. Run a round of evaluation before and after each model upgrade or replacement to generate a comparison report.
    5. Integrate structured output and code testing metrics into continuous integration (CI) with set regression thresholds.

    If your business is deployed on Baidu AI Cloud, you can place the evaluation process behind a unified model service access layer, reusing existing logging, monitoring, and permission systems to reduce redundant infrastructure. Regardless of the infrastructure used, the evaluation methodology itself should remain neutral, using business metrics as the sole basis for judgment.