Practical LLM Evaluation: Coding and Long-Chain Reasoning
Evaluating Large Language Models (LLMs) requires more than casual testing, as model performance often fluctuates across different tasks. This article outlines a systematic approach to LLM evaluation, covering key dimensions such as coding capabilities, long-text information extraction, long-chain reasoning, mathematical precision, instruction following, and inference efficiency. It provides a reproducible Python evaluation framework, compares reasoning and non-reasoning modes, highlights common pitfalls in interpreting results, and offers practical recommendations for implementing these evaluations in production environments.
Practical LLM Evaluation: Coding and Long-Chain Reasoning
1. Why Systematic Evaluation is Necessary
The performance differences between Large Language Models (LLMs) often manifest in specific tasks. A model that performs stably in general Q&A may exhibit noticeable fluctuations when applied to multi-step reasoning or code modification scenarios. Relying on a single trial or a few examples to judge model quality often leads to highly biased conclusions. Therefore, when selecting or upgrading model versions, teams need a reproducible and quantifiable evaluation method.
A reliable evaluation process typically includes four elements: clearly defined capability dimensions, a sufficiently comprehensive test set, unified scoring standards, and synchronized records of inference modes, costs, and stability. Missing any of these makes it difficult for the evaluation results to guide decision-making.
2. Breaking Down Evaluation Dimensions
2.1 Coding Capabilities
Coding capabilities should not be summarized by a single total score. It is recommended to break down tasks into five categories: code generation, bug localization, code modification, unit test writing, and code explanation. Each category should provide clear inputs and expected behaviors, verifying the results through automated execution rather than solely relying on manual review.
When evaluating, pay attention to the distribution of programming languages. The same model may perform very differently across different languages. If a team primarily uses one language, they should track statistics for that language separately to avoid having weaknesses masked by stronger performance in other languages.
2.2 Long-Text Information Extraction and Hallucination Control
Hallucination refers to model output that does not match the input material. In long-text scenarios, common forms include fabricating numbers not present in the original text, misreading table fields, and confusing information between adjacent paragraphs. Log parsing, contract clause extraction, and ticket summarization all fall under this category of tasks.
The measurement method involves preparing long-text samples with standard answers and tracking two metrics: the proportion of fields in the output that can find grounding in the original text, and the number of fabricated fields. Running the same sample multiple times also allows you to observe output consistency. It is important to note that a low hallucination rate does not equal zero hallucinations; critical business tasks still require manual or programmatic review.
2.3 Long-Chain Reasoning and Stability
Long-chain reasoning refers to problems that require multiple intermediate steps to reach a conclusion. Evaluation should design questions layered by the number of steps, such as 3, 6, and 10 steps, recording how the accuracy changes as the step count increases. The flatter the decline curve, the more reliable the model is on complex tasks.
Stability is equally important. If multiple samplings of the same question cause the results to fluctuate between correct and incorrect, it indicates that the model has occasional errors. Teams should record both the “single-run best score” and the “multi-run average score” separately. When there is a large gap between the two, the actual performance in a production environment will often be closer to the latter.
2.4 Mathematical Calculation and Precision
Mathematical tasks can be divided into two categories: direct calculations (e.g., multi-digit arithmetic, base conversions) and word problems (which require modeling before calculation). Direct calculation results can be verified by programs and should be exactly identical. Word problems require checking whether the derivation process is reasonable, as the final numerical value is only part of the result.
If a model shows minor errors in direct calculations, first confirm whether it relies on its own generated values or called an external calculation tool. In production environments, performing programmatic verification on critical calculation results is a common practice—it is low-cost and can intercept most precision issues.
2.5 Instruction Following
Instruction following can be divided into direct instructions and conditional instructions. An example of a direct instruction is “Output JSON without any explanatory text.” An example of a conditional instruction is “If the input is empty, return an error code; otherwise, output in the specified format.” Questions should be designed separately for both types, as different models may perform differently on these two task types.
When scoring, rule-based judgments should be used as much as possible, such as checking whether the JSON can be parsed, whether fields are complete, and whether conditional branches are correctly triggered. Rule-based judgments are more stable than manual scoring and are easier to use for regression testing.
2.6 Inference Efficiency and Cost
Inference efficiency refers to the number of output tokens consumed and the response time required to complete the same task. In deployment environments with limited computing power or budget, this metric directly affects cost and throughput.
When comparing efficiency, token consumption should be compared under the premise of similar accuracy. If a model’s accuracy is slightly lower but its consumption is significantly reduced, it may be more suitable for certain scenarios. Discussing efficiency without considering accuracy yields conclusions with no reference value.
3. Building a Reproducible Evaluation Pipeline
Below is a schematic code for a general evaluation framework. The model calling function is a placeholder and can be replaced with a team’s own service interface.
import jsonfrom dataclasses import dataclass@dataclassclass TestCase:case_id: strcategory: str # e.g., coding / extraction / reasoning / math / instructionprompt: strexpected: strdef call_model(model_name: str, prompt: str) -> dict:"""Placeholder function: returns {'text': output text, 'output_tokens': number of output tokens}"""raise NotImplementedErrordef check(case: TestCase, output: str) -> bool:"""Applies different judgment rules by category, using exact match as an example here"""return output.strip() == case.expected.strip()def run_suite(model_name: str, cases: list[TestCase], repeats: int = 3) -> dict:stats = {}for case in cases:for _ in range(repeats):resp = call_model(model_name, case.prompt)ok = check(case, resp["text"])bucket = stats.setdefault(case.category, {"total": 0, "passed": 0, "tokens": 0})bucket["total"] += 1bucket["passed"] += int(ok)bucket["tokens"] += resp["output_tokens"]return statsif __name__ == "__main__":cases = [] # Load the test set with standard answersreport = run_suite("model-a", cases, repeats=3)print(json.dumps(report, ensure_ascii=False, indent=2))
This framework has three design points. First, statistics are bucketed by category to prevent a total score from masking specific weaknesses. Second, each question is run multiple times to measure stability. Third, token consumption is recorded simultaneously so that accuracy and cost can be compared within the same report. In actual use, model versions, sampling parameters, and test set versions should also be recorded to ensure reproducible results.
4. Comparing Reasoning and Non-Reasoning Modes
Some models offer both explicit reasoning and non-reasoning execution modes. When comparing the two, the same test set and the same set of sampling parameters should be used, recording accuracy, output token count, and response time separately.
Typically, the reasoning mode achieves higher accuracy but also consumes more tokens. Therefore, the conclusion should provide both “cost at the same accuracy level” and “accuracy at the same cost level.” If the business is sensitive to latency, first-token latency and full response time should also be tracked separately.
5. Common Pitfalls in Interpreting Results
- Drawing conclusions from small samples. When the number of questions is small, a difference of a few questions might just be random fluctuation. It is recommended to report the fluctuation range of multiple runs or increase the number of questions.
- Looking only at the total score. Two models with similar total scores may perform very differently in long-text extraction or mathematical calculations. Results should be viewed by category.
- Test set leakage. If the test questions have already appeared in the model’s training data, the scores will be artificially inflated. Test sets should be updated regularly, and a portion of unpublished questions should be retained.
- Inconsistent scoring standards. If different judgment rules are applied to the same type of question across different batches, the results are not comparable.
- Ignoring cost and latency. A solution with high accuracy but slow response and high cost may not necessarily be suitable for online services.
6. Implementation Recommendations
- First, determine the weights of each capability dimension based on the business scenario. For example, a customer service scenario values instruction following more, while a code assistant scenario prioritizes coding and long-chain reasoning.
- Establish regular regression testing. After every model version or prompt change, automatically run the same test set and compare the results with historical data.
- Add programmatic verification to key outputs, such as format checks, numerical recalculations, and field source tracing, to reduce the risks brought by hallucinations and precision issues.
- Retain complete evaluation logs, recording inputs, outputs, judgment results, and version information to facilitate troubleshooting and trace decision-making basis.
