How to Choose and Evaluate LLMs: A Practical Engineering Guide

    Choosing a large language model is not about finding the single "best" model, but about designing a measurable, reproducible, and evolvable model selection and routing mechanism for your specific scenario. This guide explains how to build a five-dimension evaluation framework covering reasoning, long-context handling, code generation, engineering economics, and compliance; how to create private, auto-graded benchmark sets instead of relying on public leaderboards; how to combine long-context processing with retrieval augmentation; and how to implement tiered routing, cost monitoring, security controls, and a staged rollout process. It also highlights common pitfalls such as equating advertised context windows with effective context and mixing evaluation data with training data. Readers will come away with a complete methodology for running LLM selection as an ongoing engineering discipline rather than a one-time comparison.

    1. Reframing the Problem: From “Which Model Is Strongest” to “Which Combination Fits Best”

    In engineering practice, “comparing which large model is stronger” is a question that easily loses focus, for three reasons. First, model capabilities iterate rapidly, so any static ranking quickly becomes outdated. Second, the distribution of problems in public leaderboards often differs systematically from real business distributions, so leaderboard leadership does not translate into business metric leadership. Third, real systems rarely call only a single model. Engineering constraints such as cost, latency, context length, structured output stability, and data egress boundaries often matter more than “a few tenths of a percentage point in accuracy.”

    A more rigorous formulation is therefore: given a specific set of scenario constraints, how to design a measurable, reproducible, and continuously evolving model selection and routing mechanism. The rest of this article develops that idea.

    2. Establishing a Multi-Dimensional Evaluation Framework

    Break evaluation into five orthogonal dimensions, score each independently, then weight the scores according to business priorities rather than producing one vague “overall score.”

    1. Reasoning and logical ability: multi-step inference, constraint satisfaction, mathematical and symbolic operations, abstract pattern recognition.
    2. Long-context and document processing: effective context window, recall of information in the middle of long documents, cross-section citation and summarization.
    3. Code and engineering ability: single-file completion, cross-file refactoring, frontend page generation, unit test generation, instruction following, and structured output.
    4. Engineering economics: cost per token, time to first token, throughput, concurrency quotas, and retry costs on failure.
    5. Compliance and data boundaries: whether data leaves the domain, log retention policy, content safety filtering, and audit traceability.

    The key principle: every dimension must be tied to an automatically checkable business metric. Otherwise, evaluation degrades into subjective impressions.

    3. Reasoning and Math: Beware Leaderboards, Build Your Own Question Set

    Public benchmarks are useful for coarse positioning, but they carry risks of contamination and overfitting. A more reliable approach is to build a private set of 100–300 questions covering your actual business distribution, with answers that can be auto-verified.

    1. # Example: evaluation skeleton for auto-gradable reasoning questions
    2. cases = load_private_cases("reasoning_v3.jsonl") # contains answers / checker functions
    3. def evaluate(model_client, cases, k=3):
    4. scores = []
    5. for c in cases:
    6. votes = 0
    7. for _ in range(k): # multiple samples reduce randomness
    8. out = model_client.chat(c.prompt, temperature=0.7)
    9. votes += c.checker(out) # numeric / set / regex / unit test
    10. scores.append(votes / k) # pass rate similar to pass@k
    11. return sum(scores) / len(scores)

    Three additional recommendations: use multiple samples and report pass rates to reduce single-sample noise; introduce a “self-consistency” metric (agreement among multiple sampled answers) as a confidence signal for production fallback; and include “refusal / out-of-scope recognition” in the scoring. A model that correctly admits it does not know is more valuable than one that fabricates an answer.

    4. Long Context: A Large Window Does Not Mean Effective Use

    Ultra-long context windows (now reaching the million-token scale) significantly expand application boundaries: summarizing entire books, synthesizing long legal or scientific documents, and understanding large codebases shift from “retrieve and stitch” to “feed directly.” But engineering must distinguish effective context from the advertised window. Attention exhibits middle-position information decay in very long sequences: recall of key facts placed in the middle of a document is often markedly lower than for those at the beginning or end.

    The recommended combined strategy:

    • Prefer direct long-context reading: when the document is within roughly 30–50% of the window and the task requires global reasoning (e.g., character relationships across a whole book, cross-chapter contradiction detection), direct ingestion works best.
    • Retrieval augmentation as fallback: when documents far exceed the window, first perform structured chunking and vector retrieval, then build the prompt with “relevant chunks + global summary” as two layers.
    • Positional rearrangement: place key instructions and constraints at the beginning and end of the prompt, with background material in the middle.
    • Chunked summarization (map-reduce): extract key points per chunk first, then perform a second-level summary over the extracted points, controlling single-input size.
    1. [System constraints and output format] <- opening: strong constraints
    2. [Global summary / table of contents]
    3. [Retrieved chunks + location info]
    4. [Other background material]
    5. [Repeat key constraints + question to answer] <- closing: re-emphasize

    5. Evaluating Code and Page Generation

    Code evaluation must be executable. Use unit test pass rate, compilation success rate, and static analysis warning count as primary metrics, supplemented by human review for readability and safety. The evaluation set should include real-world work items—cross-file modifications, version-constraint handling, and error-log-based localization—rather than isolated algorithm puzzles. For frontend page generation tasks, add a manual spot-check ratio for “visual structure consistency.”

    Critically, model-generated code must run in a sandbox with dependency whitelisting; never execute it directly in an environment with production credentials.

    6. Cost, Latency, and Stability: Tiered Routing

    Using one model for everything is usually neither economical nor stable. Use a three-tier routing design:

    1. Light tier: intent recognition, format conversion, summarization—use small models or rule engines.
    2. Default tier: the majority of business requests.
    3. Heavy reasoning tier: complex multi-step reasoning and deep long-document analysis, upgraded on demand.
    1. def route(req):
    2. if req.est_tokens > 200_000 or req.complexity >= 3:
    3. return "reasoning_tier"
    4. if req.task_type in ("classify", "format"):
    5. return "light_tier"
    6. return "default_tier"

    Supporting infrastructure needs: result caching (semantic deduplication), timeout and exponential-backoff retries, multi-provider/multi-region failover, and dashboards for token consumption and failure rates backed by logging and monitoring/alerting. General capabilities on Baidu AI Cloud—object storage, message queues, container platforms, logging services, and monitoring/alerting—can respectively handle persistence of datasets and artifacts, asynchronous decoupling, elastic scaling, and observability, keeping evaluation and routing logic out of the business main path.

    7. Data Compliance and Security Boundaries

    Classify data sensitivity at the selection stage: which data may leave your domain to call external model services, and which must be restricted to private or dedicated deployment environments. Engineering requirements include: masking of prompts and responses in logs, centralized key management with rotation, two-way content safety filtering (input-side injection attack protection, output-side sensitive information interception), and end-to-end call auditing. To counter prompt injection, apply “data-instruction separation” to retrieved content and tool outputs—never splice external text directly into the system instruction area.

    8. Rollout Process: Evaluation Pipeline + Grayscale + Regression

    1. Offline evaluation: private question set + automatic grading, producing per-dimension scores and cost profiles.
    2. Small-traffic grayscale rollout: ramp 1% → 10% → 50%, observing business metrics and human feedback.
    3. Online shadow comparison: run the new model in parallel with the current one, logging results without returning them, and compare differing samples.
    4. Regression gate: incorporate the question set into CI; block releases when model or prompt changes fail to meet thresholds.
    5. Quarterly re-evaluation: models iterate quickly; evaluation sets and weights must evolve in sync.

    9. Common Pitfalls

    • Judging by leaderboards instead of business distribution.
    • Looking only at accuracy while ignoring latency and cost.
    • Treating the advertised window as the effective context window.
    • Lacking refusal and fallback mechanisms.
    • Frequently changing prompts without a regression baseline.
    • Mixing evaluation data with training/fine-tuning data, inflating metrics.

    10. Conclusion

    The hallmark of mature model selection is that the team no longer argues about “which model is best” but instead operates a continuously maintained measurement and governance system: private question sets, automated metrics, tiered routing, controlled grayscale rollouts, and auditable compliance. Building this system on top of Baidu AI Cloud’s general cloud infrastructure keeps model choices neutral and swappable, while business value accumulates in your own evaluation assets and engineering practices.