Evaluating Large Language Models: Methods for Strong Constraint Following and Reasoning
Evaluating the capabilities of Large Language Models (LLMs) requires moving beyond subjective open-ended conversations. This article explores a task-verifiable approach to LLM evaluation, detailing core principles for designing high-quality evaluation sets, including verifiability, difficulty stratification, and anti-contamination. It examines three typical use cases—strong constraint instruction following, multi-solution combinatorial reasoning, and constraint satisfaction reasoning—along with their Python scoring implementations. Finally, it discusses comprehensive scoring, engineering practices for reproducible experiments, and common pitfalls in interpreting results.
1. Why We Need “Task-Verifiable” Capability Evaluation
Evaluating the capabilities of Large Language Models (LLMs) cannot stop at the subjective “feel” of open-ended conversations. Open-ended questions are easily influenced by expression style, prompt wording, and human preferences, making it difficult to form stable, reproducible, and comparable conclusions. A more reliable approach is to decompose capabilities into verifiable tasks: given a specific input, the model is required to produce a result under certain constraints, and a rule or program then verifies whether the result meets the conditions. This type of evaluation does not pursue a single “correct answer” for all scenarios; instead, it prioritizes tasks that can be automatically judged, can pinpoint failure causes, and can support version regression testing.
From an engineering perspective, a high-quality evaluation set should answer at least three questions: First, does the task genuinely cover the target capability, rather than merely testing memory or template matching? Second, is the scoring sufficiently fine-grained to distinguish between “completely correct,” “partially correct,” and “correct in direction but violating constraints”? Third, is the evaluation reproducible—can it yield explainable results across different times, prompt templates, and sampling parameters? Addressing these three questions, the evaluation set can be categorized into strong constraint instruction following, multi-solution combinatorial reasoning, and constraint satisfaction reasoning, with independent verifiers designed for each category.
2. Core Principles of Evaluation Set Design
2.1 Verifiability First
Every test case should have clear passing conditions. For example, “output several sentences” is not verifiable, but “output ten sentences, ending with the letters A through J in order, where the second-to-last letter of each sentence must not be repeated and must not be a specific banned letter” can be checked programmatically item by item. Verifiability does not exclude subjective questions; rather, it requires that subjective questions be broken down into objective sub-conditions, such as format, quantity, order, banned items, and citation scope.
2.2 Difficulty Stratification and Capability Isolation
The evaluation set should avoid having all questions depend on the same capability. Strong constraint instruction following primarily examines format control, order control, and adherence to banned items; multi-solution combinatorial reasoning examines mathematical relationship search, expression construction, and multi-solution differentiation; constraint satisfaction questions examine condition modeling, duplicate counting, and consistency checking. By isolating capability dimensions, failure results are easier to attribute: Did the model fail to understand the constraints, did the reasoning chain break, or is there ambiguity in the verification criteria itself?
2.3 Anti-Contamination and Anti-Leakage
Evaluation cases should avoid fixed expressions directly sourced from public question banks. Regular isomorphic rewrites, number replacements, constraint additions/deletions, and order perturbations should be performed. For math and logic questions, the question type can be retained while the parameter combinations are changed; for instruction following questions, banned letters, ending characters, and sentence counts can be replaced. This not only reduces the impact of memory-based answers but also tests whether the model truly possesses constraint-following capabilities.
2.4 Scoring Criteria Must Be Defined Upfront
Scoring rules should be fixed before evaluation begins, not adjusted after seeing the results. For multi-solution questions, the criteria for “different methods” must be clear: Is it a difference in expression structure, a difference in intermediate steps, or does merely swapping the order of numbers not count as a new method? For constraint satisfaction questions, the counting rule for duplicate numbers must be clear. The earlier the scoring criteria are defined, the more comparable the results will be.
3. Three Typical Use Cases and Scoring Implementations
3.1 Strong Constraint Instruction Following: Sentence Generation Task
A typical task requires the model to output ten fluent sentences, ending sequentially with the letters “A” to “J”, and the second-to-last letter of each sentence must not be repeated, nor can it use banned letters such as “x”, “y”, or “z”. This task seems simple, but it simultaneously stacks quantity constraints, order constraints, semantic fluency constraints, character position constraints, and banned item constraints, effectively exposing the model’s omissions and drift under long constraints.
Scoring can use a per-sentence deduction system: Insufficient quantity or wrong order results in per-item deductions; mismatched ending letters result in deductions; repeated or banned second-to-last letters result in deductions; sentences that are clearly not fluent are deducted after manual review. The automatic verifier can first complete hard rule checks:
def check_sentences(sentences):tails = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]banned = {"x", "y", "z"}if len(sentences) != 10:return False, "Number of sentences is not 10"used = set()for i, s in enumerate(sentences):s = s.strip()if len(s) < 2:return False, f"Sentence {i+1} is too short"if not s.endswith(tails[i]):return False, f"Ending of sentence {i+1} does not match the required order"penultimate = s[-2].lower()if penultimate in banned:return False, f"Second-to-last letter of sentence {i+1} is a banned letter"if penultimate in used:return False, f"Second-to-last letter of sentence {i+1} is duplicated"used.add(penultimate)return True, "Hard rules passed"
After automatic verification passes, a sample manual review is conducted for “fluency and meaning.” This preserves the stability of rule-based evaluation while avoiding leaving semantic quality entirely to string rules.
3.2 Multi-Solution Combinatorial Reasoning: Expression Construction Task
Another high-value task requires the model to construct multiple different expressions to reach a target value, given a set of numbers where each number must be used exactly once. This type of task cannot only examine the final answer; it must also check whether the expression is legal, whether the number usage meets constraints, and whether the different solutions are genuinely different. If elementary operators like exponentiation and square roots are allowed, an operator whitelist should be explicitly defined, and the model should be required to provide checkable expressions.
Scoring can be divided into three parts: result correctness, constraint compliance, and multi-solution differentiation. Incorrect results receive no points; using too many or too few numbers, or introducing unallowed constants, results in deductions; multiple expressions that only swap order or are equivalent transformations count as only one method. The schematic verification logic is as follows:
import astdef collect_numbers(expr):tree = ast.parse(expr, mode="eval")nums = []for node in ast.walk(tree):if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):nums.append(node.value)return numsdef check_numbers_once(expr, target_nums):return sorted(collect_numbers(expr)) == sorted(target_nums)def check_expression(expr, target_nums, target_value):if not check_numbers_once(expr, target_nums):return False, "Number usage does not meet constraints"# In production, AST whitelist validation should be done in a sandbox before evaluationvalue = eval(compile(ast.parse(expr, mode="eval"), "<expr>", "eval"), {"__builtins__": {}}, {})if abs(value - target_value) > 1e-9:return False, "Result does not equal target value"return True, "Passed"
It must be emphasized that the above code is only for illustrating the verification logic. Production evaluations should perform AST whitelist validation, timeout control, and sandbox isolation on expressions to avoid executing untrusted input. For constraints like “no exhaustive scripts allowed,” the automatic verifier cannot directly judge the model’s internal process. Therefore, it should be combined with prompt requirements, step explanations, and manual spot checks to avoid misjudging “correct results” as “compliant reasoning.”
3.3 Constraint Satisfaction: Duplicate Counting and Position Matching
Combination lock-style reasoning questions are suitable for examining condition modeling capabilities. The question provides several guesses and clues, such as the number of “correct positions” and the number of “correct numbers but wrong positions,” requiring the model to deduce the unique password. The key difficulty in such questions lies in the counting of duplicate numbers: if the number of occurrences of a number in the password and the guess differs, it can only be counted as “correct number but wrong position” based on the smaller occurrence count, and it cannot overlap with positions already counted as “correct positions.”
The verifier should calculate the hit situation guess by guess:
from collections import Counterdef score_guess(secret, guess):exact = 0secret_rest, guess_rest = [], []for a, b in zip(secret, guess):if a == b:exact += 1else:secret_rest.append(a)guess_rest.append(b)cs, cg = Counter(secret_rest), Counter(guess_rest)misplaced = sum(min(cs[d], cg[d]) for d in cs)return exact, misplaced
When scoring, the matching situation of each clue can be treated as a hard constraint: the candidate password must make both the “correct position count” and “wrong position count” true for all guesses simultaneously. If the model provides multiple candidates, deductions should be made based on the number of constraints, conflicting clues, and explanation completeness. The advantage of this task is that the answer can be automatically verified, and the failure cause can be pinpointed to a specific clue.
4. From Single-Task Scores to Comprehensive Scoring
A single-task score cannot be directly equated to comprehensive capability. It is recommended to adopt an approach of “dimension weighting + partial credit + failure type statistics.” Dimension weights can be adjusted according to business goals: if targeting structured output scenarios, increase the weight of strong constraint instruction following; if targeting complex analysis scenarios, increase the weight of multi-step reasoning. Partial credit is used to reward answers that are close to correct, for example, giving base points for getting one method right in a multi-solution question, and bonus points for getting multiple distinct methods right. Failure type statistics record tags like “format error,” “constraint omission,” “calculation error,” “duplicate counting error,” and “incomplete explanation” for subsequent improvements to prompt templates or evaluation sets.
A comprehensive report should not just give a total score; it should also present dimensional scores, variance, failure examples, and manual review conclusions. For the same model, it is recommended to sample multiple times under fixed temperature, fixed maximum output length, and fixed prompt templates, reporting the median and dispersion. For different models, comparing only a single total score should be avoided; instead, performance under the same capability dimensions should be compared.
5. Reproducible Experiments and Engineering Implementation
The evaluation set should be version-controlled, recording the reason for changes every time a case is added or modified. The automatic verifier should be maintained in the same repository as the dataset, ensuring that the scoring logic and task definitions evolve synchronously. Batch evaluation can run in isolated containers, standardizing timeouts, retries, and log formats; results are written to structured storage for easy aggregation by version, dimension, question type, and failure tag. If using a cloud platform, general object storage can be used to save versioned evaluation sets, a container platform to run isolated evaluation tasks, a logging service to aggregate verifier outputs, and monitoring alerts to track regression metrics.
Prompt templates should also be brought under version control. The same question may perform noticeably differently under different prompts, so the report should specify the system prompt, output format requirements, and sampling parameters. For verifiers involving code execution, resources should be limited, network access disabled, timeouts set, and whitelist checks performed on expressions or scripts. Finally, manual review should not be completely eliminated; instead, it should focus on semantic fluency, explanation reasonableness, and method differentiation that automatic verification struggles to cover.
6. Result Interpretation and Common Pitfalls
First, do not simply equate “getting it right” with “possessing the capability.” Multi-solution questions might yield answers through memory or pattern matching, so isomorphic variants and step explanations are necessary. Second, do not ignore ambiguity in scoring criteria. Rules for duplicate counting, different solutions, and banned item positions must be defined upfront, or results will be incomparable. Third, do not make decisions based solely on total scores. One model might be very strong in format constraints but unstable in multi-step reasoning, while another might be the opposite. Only dimensional results can support actual model selection. Fourth, do not treat a single evaluation as the final conclusion. Evaluation sets should continuously iterate, and model outputs have sampling randomness, requiring multiple runs and confidence intervals.
7. Conclusion
Evaluating LLM capabilities should shift from “open-ended experience” to “task-verifiable, score-explainable, and result-reproducible.” Strong constraint instruction following, multi-solution combinatorial reasoning, and constraint satisfaction reasoning are three representative types of tasks: they respectively cover format control, search construction, and condition modeling capabilities, and all can obtain stable signals through automatic verifiers. A truly valuable evaluation system does not pursue a beautiful total score, but rather can answer three questions: “Under what constraints does the model fail, is the failure reproducible, and how can it be improved subsequently?” Only in this way can evaluation results serve prompt engineering, application selection, and engineering regression, rather than remaining a one-time experience description.
