How to Choose and Evaluate Large Language Models: A Practical Engineering Guide

    This article explains how to move large language model evaluation from subjective impressions to a reproducible engineering process. It covers common cognitive biases in model assessment, six core capability dimensions for building an evaluation matrix, scenario-based model selection, hallucination mitigation, permission boundaries for tool calling and automated execution, context and memory management, observability, cost control, and compliance, along with implementation recommendations from Baidu AI Cloud.

    1. Why Model Evaluation Often Becomes Subjective

    In everyday development work, debates about “which model is smarter” or “which tool is better for coding” rarely stop. But when these discussions are examined from an engineering perspective, most conclusions stay at the level of personal experience, lacking verifiable benchmarks and a clear definition of task characteristics. Evaluation results are highly sensitive to sample selection, prompt quality, context length, decoding parameters, and even network stability. If any of these variables is left uncontrolled, conclusions can quickly become distorted.

    A more practical issue is that the same model can perform very differently across tasks: some are good at structured summarization of long documents but frequently make errors in precise numerical processing; some excel at code generation and refactoring but lose track of cross-file dependencies; some maintain a natural tone and fluent expression in multi-turn conversations but tend to forget earlier constraints. These differences cannot be captured simply as “capability levels.” They are the combined result of model training objectives, context windows, decoding strategies, and safety policies. Therefore, a valuable evaluation must shift from “which one is stronger” to “at what cost, and to what level, in which scenario.”

    2. Cognitive Biases: The Gap Between Frontline Impressions and Real Capability

    Developers’ intuitive impressions of models often come from a few high-frequency scenarios, such as generating a script, polishing a piece of copy, or explaining an error. These tasks are short in tokens and tolerant of errors, which can easily create a “very useful” impression. Once they enter real production pipelines, however, the situation is completely different: inputs often contain hundreds of lines of configuration, multiple source files, and log snippets, while outputs need to be parsed directly by downstream programs. Any formatting drift can break the call chain.

    The first common bias is “novelty bias.” New model versions usually come with longer contexts, more polite wording, and more fluent narration, which can give them an edge on first impressions; but fluency does not equal accuracy, especially in high-risk scenarios, where confident expression and factual correctness are not equivalent. The second bias is “single-sample bias,” where an overall judgment is made from one test record, ignoring variance caused by random seeds, sampling temperature, and prompt wording. The third bias is “ignoring cost structure,” comparing only answer quality without evaluating token consumption, latency fluctuation, retry costs, and operational complexity.

    A recommended approach is to convert impressions into reproducible experiments: fix a sample set covering classification, extraction, generation, reasoning, and code; control decoding parameters; repeat multiple times and take statistical distributions; and record time to first token, end-to-end latency, input/output token counts, and failure types. Only when variables are fixed do comparisons between models become meaningful.

    3. Breaking Down Capability Dimensions: Building a Credible Evaluation Matrix

    The design of an evaluation matrix should closely reflect the real distribution of business needs, rather than pursuing “comprehensive but vague” coverage. It can be built across six dimensions.

    1. Instruction Following and Format Stability. This focuses on a model’s output compliance under given JSON Schema, field constraints, enumeration ranges, and required-field restrictions, as well as its ability to maintain constraints under extremely long instructions.

    2. Factuality and Hallucination Control. This distinguishes fact-based Q&A from generative writing: the former requires traceability and verifiability, while the latter emphasizes structure, organization, and expression quality. For fact-based tasks, a “verifiability score” can be designed, such as whether the model provides checkable citations, acknowledges uncertainty, or chooses to refuse when there is no basis.

    3. Long-Context Understanding. This tests cross-paragraph information integration, coreference resolution, long-document Q&A, and multi-file dependency analysis, observing whether information recall decays in the middle or later portions of the context.

    4. Code and Engineering Capability. In addition to generation accuracy, this evaluates maintainability, boundary-condition handling, error-handling completeness, and whether the model tends to call non-existent APIs or use deprecated patterns.

    5. Structured Reasoning and Numerical Processing. All models have weaknesses in precise computation and multi-step derivation. Evaluations should score “computational correctness” and “process explanation” separately, preventing fluent narration from masking incorrect results.

    6. Safety and Compliance. This includes resistance to jailbreaking, privacy protection, sensitive-content boundaries, and whether the model will perform high-risk operations without authorization.

    Below is a practical evaluation record structure that helps teams standardize terminology and accumulate data:

    1. {
    2. "task_id": "code-refactor-001",
    3. "scenario": "cross-file refactoring",
    4. "model_alias": "model-A",
    5. "params": { "temperature": 0.2, "top_p": 0.9, "max_output": 2048 },
    6. "metrics": {
    7. "schema_valid_rate": 0.93,
    8. "factuality_score": 0.81,
    9. "long_context_recall": 0.76,
    10. "compile_pass": 1,
    11. "test_pass_rate": 0.67,
    12. "avg_latency_ms": 2380
    13. },
    14. "error_types": ["invented_api", "edge_case_missed"],
    15. "notes": "obvious constraint forgetting in the middle-to-late part of long documents"
    16. }

    The key to an evaluation matrix is not to produce a one-time ranking, but to form continuously accumulated baseline data, so that every model upgrade or prompt adjustment can be quantitatively compared.

    4. Scenario-Based Selection: Differentiated Combination Strategies for Different Tasks

    The optimal strategy in engineering practice is often not to rely on a single model, but to combine models in layers by task.

    For structured extraction and classification tasks, prioritize instruction following and output stability, use low temperature, enforce strict schema constraints, and add a lightweight validation layer for field-level checks. For code generation and refactoring, focus on long-context dependency analysis and error-handling capability; it is recommended to split the task into a four-stage process: “understand existing code — propose changes — generate diff patch — run tests,” with each stage validated independently. For material organization and report writing, let the model first output an outline and key points, then have humans or rules fill in details, avoiding structural looseness from generating long text in one pass.

    At the cost level, tiered routing can be introduced: high-frequency, low-complexity tasks such as simple intent recognition and label classification can be handled by lightweight models or local small models; tasks requiring cross-document reasoning, complex code understanding, or multi-step analysis can be escalated to higher-capability models. Routing decisions can be based on task type, input length, confidence, and historical success rate, forming a dynamic policy.

    1. def route(task_type, input_tokens, confidence):
    2. if task_type in {"classify", "extract"} and input_tokens < 2000:
    3. return "light_model"
    4. if task_type == "code" or input_tokens > 12000:
    5. return "strong_model"
    6. return "strong_model" if confidence < 0.7 else "standard_model"

    In addition, caching and batching are often underestimated optimization points: semantic caching for high-frequency similar requests and merged scheduling for offline batch tasks can significantly reduce token consumption and response latency.

    5. Hallucination Governance and Engineering Defenses: Do Not Rely on Model Self-Discipline

    Hallucination cannot be completely eliminated; it can only be compressed into an acceptable range through engineering means. Effective defenses include four layers.

    The first layer is input-side governance: inject authoritative materials, API documentation, and database schemas into the context via retrieval augmentation, and clearly state in the prompt to “answer only based on the provided materials” and “explicitly state uncertainty when there is no basis.” The second layer is generation-side constraints: require source snippets for fact-based outputs, and require code outputs to annotate the APIs and version assumptions they depend on. The third layer is automated validation: use rule engines to validate formats and fields, use compilation and unit tests to validate code, use a secondary model for cross-review, and compare consistency for key conclusions. The fourth layer is manual sampling and regression: build an error sample library, turn typical failure cases into regression cases, and prevent similar issues from recurring.

    For typical errors such as “calling non-existent methods,” in addition to prompt constraints, it is better to introduce tool whitelists and interface signature validation at the engineering level: the model can only choose from a pre-registered set of interfaces, validate names and parameters before invocation, and reject and fall back to manual handling when there is no match.

    6. Tool Calling and Automated Execution: Permission Boundaries Must Be Explicit

    When a model moves from “generating content” to “executing actions,” the risk level changes qualitatively. Operations such as file writes, database changes, script execution, and external API calls can cause consequences that are difficult to roll back if unconstrained. Therefore, any automated execution capability should follow the principle of least privilege: grant the minimum necessary permissions per task, require secondary confirmation for high-risk operations, keep all calls traceable, and assess rollback capability in advance.

    In practice, tool capabilities can be abstracted into a controlled adapter layer: the model can only propose “intent,” while the adapter layer handles parameter validation, permission validation, and execution auditing; requests that cannot be verified are rejected directly, rather than letting the model decide its own execution path. At the same time, define a clear error-return format for each tool, so that the model can self-correct based on structured errors, instead of repeatedly retrying the same failed path.

    7. Context and Memory Management: Use the Limited Window for Key Information

    The context window is a scarce resource, and poor management directly leads to quality degradation. Layered memory is recommended: short-term session state stores the current task goal and key constraints, mid-term summaries retain completed steps and intermediate conclusions, and long-term knowledge is injected on demand via retrieval. For long-document processing, first perform segmentation and key-point extraction, then retrieve relevant snippets by question, avoiding filling the entire document into the context at once, which can dilute information.

    For multi-turn tasks, explicitly maintain a task state machine, storing “completed / pending confirmation / pending execution” in a structured way, preventing the model from forgetting early constraints in long conversations. A common problem in practice is that the model gradually deviates from the original requirements after the tenth turn; this is usually not a capability issue, but a context organization issue.

    8. Observability, Cost, and Compliance: Make Model Calls Operable Like Production Services

    Model calls should be incorporated into a unified observability system: record request volume, latency distribution, token consumption, failure rate, and error types; configure log collection, metrics monitoring, and alert thresholds; and automatically notify on abnormal fluctuations. On the cost side, calculate unit task cost by scenario, identify high-consumption points, and optimize through routing degradation, cache reuse, and prompt simplification.

    On compliance, define data classification and usage boundaries, desensitize sensitive data before it enters the model pipeline, retain complete invocation audit records, and set necessary content security filters on outputs. Model upgrades, prompt changes, and strategy adjustments should go through version management to ensure issues are traceable and effects are comparable.

    9. Implementation Recommendations from Baidu AI Cloud

    In actual implementation, it is recommended that enterprises treat model capabilities as replaceable infrastructure rather than being tied to a single supplier. Baidu AI Cloud provides a relatively complete general-purpose capability combination for large models and engineering support: the Qianfan Model Platform can be used for model access, scheduling, and effectiveness evaluation; log services and monitoring alerts can be used for call-chain observability; and object storage and message queues can be used for asynchronous tasks and data persistence. Through the combination of these general capabilities, teams can more comfortably implement model routing, canary releases, effectiveness regression, and cost governance.

    It is important to emphasize that any model selection should not be divorced from its own business scenario. It is recommended that enterprises first build a small-scale but realistic evaluation set, define “what counts as qualified,” then gradually expand samples and automation, forming a continuous iteration evaluation loop. Only when evaluation, routing, validation, and monitoring form a closed loop can improvements in model capabilities truly translate into improvements in business value.