Large Language Model Selection: A Practical Guide to Horizontal Evaluation

    This article presents a practical approach to evaluating and selecting large language models for production use. Instead of relying on vendor benchmarks or generic leaderboards, it describes how to build a reusable horizontal evaluation workflow based on business requirements. The guide covers a four-step evaluation process, a unified model access layer, dimension-based test sets, multi-layer scoring methods, and decision criteria that consider quality, cost, latency, stability, and compliance. Code examples and templates are included to help teams run consistent and repeatable model comparisons.

    Large Language Model Selection: A Practical Guide to Horizontal Evaluation

    1. Why run horizontal model evaluations

    Over the past two years, large language model iteration has accelerated. New versions repeatedly update metrics such as long-context handling, reasoning, and multimodal understanding, making capability boundaries between models less distinct. For developers and technical decision-makers, the key question is no longer simply “Which model is better?” The more important question is: Under our own business scenario, which model performs more reliably, has more controllable costs, and is more worth long-term investment?

    These questions cannot be answered by vendor presentation charts alone, nor by a few ad hoc trials. There are three main reasons:

    • Vendor benchmarks use different emphases: Different vendors publish different benchmarks and test sets, so scores cannot be directly compared side by side.
    • General-purpose leaderboards may not match business scenarios: A model that scores well on a public leaderboard may not perform best in a company’s vertical domain.
    • A single metric is not enough for model selection: Output quality is only one part of the decision. Latency, cost, stability, and content compliance also affect the final choice.

    Building a reusable horizontal evaluation process turns “trial-and-error based on intuition” into “data-driven decision-making.” This article covers three parts: building a unified access layer, designing dimension-based evaluation sets, and applying multi-dimensional scoring and decision methods.

    2. Four steps in a horizontal evaluation

    A standard evaluation workflow usually includes four stages. Together, they form a continuously improving loop:

    1. Define objectives: First determine the tasks the model will perform, such as customer support Q&A, contract review, coding assistance, or image-and-text understanding. Then define the evaluation priorities based on those tasks.
    2. Build a unified access layer: Hide differences in API formats and authentication methods so that comparison conditions remain consistent.
    3. Build the evaluation set: Prepare test cases and reference answers by capability dimension, covering typical scenarios and boundary cases.
    4. Score and decide: Use automated checks, model-based review, and human blind evaluation, then combine the results with cost and stability considerations.

    After launch, real business requests should continue to flow back into the evaluation set. Regular regression tests help prevent performance degradation caused by model upgrades or prompt changes.

    3. Unified access layer: switch models through configuration

    The first principle of horizontal comparison is controlling variables. Different model services often expose APIs that are compatible with common chat interfaces, but authentication methods, context-length limits, and multimodal input support can vary. Calling each API directly in evaluation code can lead to several problems:

    • Inconsistent prompt assembly and default parameters make results non-comparable.
    • Switching models requires major code changes, making tests hard to reuse.
    • When a model version is upgraded, historical results lose traceability.

    A more robust approach is to introduce a lightweight abstraction layer. Evaluation code should work with a unified message structure and parameter set, while provider-specific access details are injected through configuration:

    1. from dataclasses import dataclass
    2. import httpx
    3. @dataclass(frozen=True)
    4. class ModelProfile:
    5. """Model profile: stores access information and capability constraints for consistent testing."""
    6. name: str # Anonymous label used in evaluation, e.g. "Model-A"
    7. base_url: str # Service endpoint, injected via environment variables
    8. api_key: str # API key, injected via environment variables; never hard-code it
    9. model: str # Target model name or version identifier
    10. max_context: int # Maximum context window size in tokens
    11. supports_vision: bool = False # Whether the model supports image input
    12. class ChatClient:
    13. def __init__(self, profile: ModelProfile, timeout: float = 60.0):
    14. self.profile = profile
    15. self._timeout = timeout
    16. def chat(self, messages: list[dict], **overrides) -> dict:
    17. """Send a chat request and return the raw response; overrides can temporarily change evaluation parameters."""
    18. payload = {"model": self.profile.model, "messages": messages}
    19. # Keep generation parameters fixed to avoid randomness affecting comparisons
    20. payload.update({"temperature": 0, "max_tokens": 1024})
    21. payload.update(overrides)
    22. resp = httpx.post(
    23. f"{self.profile.base_url}/chat/completions",
    24. headers={"Authorization": f"Bearer {self.profile.api_key}"},
    25. json=payload,
    26. timeout=self._timeout,
    27. )
    28. resp.raise_for_status()
    29. return resp.json()

    Key design considerations include:

    • Key management: Inject access keys through environment variables or a secret management service. Never hard-code them or commit them to a repository.
    • Failure handling: Add retry and backoff strategies for timeouts, rate limits, and server errors. Mark failed cases separately so they are not misjudged as model capability gaps.
    • Anonymous recording: Use anonymous labels for models during evaluation. Do not reveal real model names during scoring to reduce bias.
    • Prefer structured output: For tasks requiring structured answers, use JSON output modes commonly supported by platforms rather than relying on fragile prompt constraints.

    Teams can also use cloud platforms to connect to multiple models through unified authentication and invocation. This can reduce the maintenance cost of the access layer and make usage and cost management more centralized.

    4. Evaluation dimension design: from “can chat” to “actually useful”

    Evaluation dimensions should come from real business requirements. The following table shows a common dimension breakdown and example weights. Adjust them according to business priorities. The weights should sum to 100%.

    Evaluation dimension Typical cases Main observations Example weight
    Chinese understanding Ambiguous sentence analysis, idiom interpretation, terminology explanation Semantic accuracy, natural expression, terminology correctness 20%
    Long context Clause location in long documents, cross-paragraph information integration Key information recall, continuity of context integration 20%
    Logical reasoning Multi-step calculation, conditional constraints, causal analysis Conclusion correctness, verifiability of reasoning process 20%
    Coding ability Function generation, defect localization, unit test writing Functional correctness, code quality, boundary handling 20%
    Multimodal understanding Chart reading, invoice information extraction, screenshot Q&A Extraction accuracy, completeness, misreading cases 10%
    Instruction following Format constraints, multi-task instructions, refusal boundaries Constraint satisfaction, output structure compliance 10%

    Key design points for each dimension:

    • Chinese understanding: Focus on expressions that depend heavily on context. For example, ask the model to identify pronoun references, explain word meanings in specific contexts, or rewrite the same content in formal and informal styles.
    • Long context: Prepare documents of tens of thousands of words or longer. Place key information at the beginning, middle, and end to test whether the model can reliably locate it and whether it truly reads the full text rather than guessing from keywords.
    • Logical reasoning: Design multi-step reasoning tasks such as logic puzzles and constrained problems. Besides checking the final answer, verify whether intermediate steps are consistent and identify “right answer, wrong process” outputs.
    • Coding ability: Use engineering-oriented tasks such as completing functions, fixing defects, and writing unit tests. Evaluation should mainly rely on test pass rates and static checks to reduce subjectivity.
    • Multimodal understanding: Choose information-dense charts or invoices and ask the model to extract fields one by one. Compare results against human annotations, calculate accuracy, and record omissions and misreadings.
    • Instruction following: Test execution under complex constraints. For example, require valid JSON output, specific fields, and a maximum word count, then verify whether all constraints are met simultaneously.

    1. Representative prompt example

    The following is an example structure for a long-context evaluation task:

    1. [Task]
    2. Read the following product requirements document and answer the questions.
    3. [Constraints]
    4. 1. Answers must quote the original text as evidence and indicate the relevant section.
    5. 2. If the information is not mentioned, answer "Not mentioned" and do not speculate.
    6. [Document]
    7. (Insert a document of tens of thousands of words here, with key information distributed at the beginning, middle, and end.)
    8. [Questions]
    9. 1. How does the system handle inventory when an order is not paid within the timeout period?
    10. 2. How many business days is the refund review deadline?
    11. 3. Are cross-border orders supported? If so, which settlement currencies are supported?

    This task evaluates three capabilities:

    • Key information retrieval
    • Citation of original text
    • Refusal behavior for unknown information

    After models answer, compare quoted sentences with the source document to quantify whether the citations are genuine.

    2. Organizing multimodal test inputs

    Image inputs are generally passed through a content block list. The same test case can be used for all models that support visual capabilities:

    1. messages = [{
    2. "role": "user",
    3. "content": [
    4. {"type": "text", "text": "Read the invoice information in the image and return the fields seller, total, and date in JSON."},
    5. {"type": "image_url",
    6. "image_url": {"url": "https://example.com/invoice.png"}},
    7. ],
    8. }]

    The image URL above is only an example. In real evaluations, use internal storage or local resources. If a target model does not support image input, skip that case rather than assigning a score of zero; otherwise, its overall capability may be underestimated.

    5. Scoring mechanism: automated, model-based, and human review

    Each scoring method has limitations:

    • Pure automatic metrics may not cover semantic quality.
    • Pure human scoring is expensive and slow.
    • Pure model-based review may introduce bias.

    A three-layer approach is recommended.

    Layer 1: Automated checks. Use deterministic rules to evaluate objective cases: answer matching, valid JSON with required fields, code passing unit tests, and compliance with format or length constraints. This layer can be repeated and is suitable for regression testing.

    Layer 2: Model review. A stronger model scores outputs according to a rubric. The rubric should define clear score levels, such as the following example for long-document QA:

    Score Criteria (example: long-document QA)
    5 Accurate and complete answer; citation exists and points to the correct section
    4 Correct answer; minor citation issue, such as an inaccurate section label
    3 Mostly correct, but lacks evidence or contains redundant content
    2 Partially correct; key conclusion is wrong or missing
    1 Mostly incorrect, or includes information not present in the source text
    0 Off-topic, vague, evasive, or refuses to answer

    Layer 3: Human blind review. Hide model identities and have domain experts review disputed samples or sampled cases.

    For tasks that require fixed-structure output, use deterministic validation as follows:

    1. import json
    2. def validate_structured_output(raw: str, required: set[str]) -> bool:
    3. """Validate model output: ensure it is valid JSON and contains all required fields."""
    4. try:
    5. data = json.loads(raw)
    6. except json.JSONDecodeError:
    7. return False
    8. return isinstance(data, dict) and required.issubset(data.keys())
    9. # Example
    10. ok = validate_structured_output('{"city": "Hangzhou", "temp": 26}', {"city", "temp"})

    When using model review, pay attention to three common biases:

    • Position bias: Review models tend to give higher scores to answers listed earlier.
    • Verbosity bias: Longer answers may be rewarded unfairly.
    • Self-preference bias: A model may favor styles similar to its own outputs.

    Mitigation measures include:

    • For pairwise comparisons, swap A/B order and evaluate both ways. If results differ, send the case to human review.
    • Explicitly state in the rubric that longer responses should not receive extra credit.
    • Avoid using the same model as both the system under test and the reviewer.

    A general function can aggregate scores:

    1. def weighted_score(scores: dict[str, float], weights: dict[str, float]) -> float:
    2. """Calculate an overall score on a 0-100 scale using dimension weights."""
    3. total_weight = sum(weights.values())
    4. if total_weight == 0:
    5. raise ValueError("The sum of weights cannot be zero")
    6. weighted_sum = sum(scores.get(k, 0) * w for k, w in weights.items())
    7. return round(weighted_sum / total_weight * 100, 1)
    8. # Example: only demonstrates the calculation method
    9. scores = {"Chinese understanding": 4.3, "Long context": 3.8, "Logical reasoning": 4.1,
    10. "Coding ability": 4.5, "Multimodal understanding": 4.0, "Instruction following": 4.6}
    11. weights = {"Chinese understanding": 0.20, "Long context": 0.20, "Logical reasoning": 0.20,
    12. "Coding ability": 0.20, "Multimodal understanding": 0.10, "Instruction following": 0.10}
    13. print(weighted_score(scores, weights))

    After testing, compile dimension scores, average response latency, and cost per call into a comparison report. Include the model version and test date to support future re-testing and regression comparisons after upgrades.

    6. From scores to decisions

    1. Set admission thresholds

    First, filter candidates using hard constraints. For example:

    • Exclude models whose context length cannot cover the business documents.
    • Exclude models that do not support required input types for the relevant scenario.
    • Do not consider models whose content safety policies conflict with business requirements.

    2. Build a weighted score matrix

    For models that pass the thresholds, calculate an overall score using business weights:

    Candidate model Chinese understanding Long context Logical reasoning Coding ability Multimodal understanding Instruction following Overall score
    Model A 4.3 3.8 4.1 4.5 4.0 4.6 42.2
    Model B 4.1 4.4 4.0 4.0 3.5 4.2 41.8

    All values in the table are illustrative and show the calculation method. Model A performs better in coding ability and instruction following, while Model B performs better in long-context handling. If the business focuses on contract review, increase the weight of long-context capability. If it focuses on coding assistance, Model A has an advantage. Weights should be determined by business needs, not by scores. This is key to avoiding a score-only mindset.

    3. Consider non-quality factors

    • Cost and latency: Estimate monthly cost based on input/output token volume per request and call frequency. Also analyze percentile latency for first token and full response time; do not rely only on averages.
    • Stability: Monitor retry rates, error rates, and model version update frequency.
    • Content compliance: Add content moderation and sensitive information masking before model output enters the system to meet business and regulatory requirements.
    • Deployment model: Evaluate public cloud APIs and private deployment options based on data sensitivity.

    4. Continuous regression and dynamic routing

    Selecting a model is not the end of evaluation:

    • Regression testing: Integrate the evaluation pipeline into CI. Re-run core test cases automatically when model versions change or prompts are modified to prevent performance regression.
    • Dynamic routing: After launch, route requests by task type. For example, long-document tasks can go to models with stronger long-context capability, coding tasks can go to models with better code performance, and a fallback model can be configured for timeouts.
    • Canary release: Before fully rolling out a new model, compare it with the existing model under a small traffic share, collect real user feedback, and gradually increase traffic.

    7. Common pitfalls and recommendations

    • Inconsistent prompts: Small differences in system prompts, few-shot examples, or output-length limits can significantly affect results. Fix prompt templates before evaluation and version-control them.
    • Randomness: Keep generation parameters such as temperature consistent. For subjective tasks, run multiple samples and use averages to reduce variance.
    • Context-length estimation bias: Token count is not the same as character count. English, Chinese, code, and images have different conversion rules. Confirm the actual context limit before long-text tests; if necessary, split the text or create a summary first.
    • Differences in multimodal support: Not all models support images, audio, or video. Confirm capability boundaries before evaluation to avoid false low scores.
    • Version drift: Models are continuously updated. Early conclusions may not apply to the current version. Reports should record model versions and test dates, and regular re-testing is recommended.
    • Data compliance: If evaluation data contains user privacy or commercially sensitive information, mask it first. For services involving cross-border data transfer, evaluate the related compliance requirements.

    8. Summary

    Large language model selection is shifting from “which model is stronger” to “which model is more suitable.” The core approach can be summarized as follows:

    1. Unified access: Use a configurable access layer to hide differences and control variables.
    2. Dimension-based testing: Design test cases around business requirements across Chinese understanding, long context, logical reasoning, coding, multimodal understanding, and instruction following.
    3. Three-layer scoring: Combine automated checks, model review, and human blind evaluation, then aggregate scores using business weights.
    4. Rational decision-making: Choose models based on quality, cost, latency, stability, and compliance. Continue optimizing through regression testing, canary releases, and dynamic routing.

    For development teams, connecting multiple models through cloud platforms and applying the evaluation methods in this article can provide a low-cost, quantifiable, and reproducible basis for model selection.