Large Language Model Selection and Engineering Practices: A Practical Guide
This guide explains how to choose and operate large language models based on task requirements rather than public rankings. It breaks down capability dimensions, shows how to build a reproducible internal evaluation set, discusses trade-offs among cost, latency, and stability, and outlines an architecture with an abstraction layer and routing. It also covers prompt and context engineering, a rollout path, and common pitfalls. Readers will find practical code examples and a measurable framework for balancing capability, cost, and reliability.
1. The Real Problem: From “Which Model Is Best” to “Which Combination Fits”
When building LLM-powered applications, the most common starting point is comparing model capabilities side by side. From an engineering perspective, however, this question lacks constraints. Model capability is a multi-dimensional vector that includes at least reasoning depth, code generation and repair, long-context understanding, multimodal perception, instruction-following stability, structured output reliability, cost per token, time to first token and throughput, and availability and rate-limiting policies. No ranking on a single dimension can cover a real business distribution.
A more practical question is: given a task distribution, latency budget, compliance constraints, and cost ceiling, how do you choose a model combination and invocation strategy? The judgment “it depends on what you want to do” is a reasonable abstraction: the task type determines capability priorities, while engineering constraints determine the final architecture.
2. Capability Dimensions and Task Mapping
2.1 Reasoning and Planning
Tasks that involve multi-step derivation, math, or logic checks require strong chain-of-thought stability and self-verification. In engineering, you can use a multi-turn prompt structure of “decompose, solve, and review,” or bring in external computation and verification tools to reduce reliance on a single model’s internal reasoning.
2.2 Code Capabilities
Code tasks should be split into five sub-scenarios: generation, completion, refactoring, defect localization, and test generation. These sub-scenarios differ in their dependence on context length and repository-level information retrieval. In practice, a more effective approach is not to find the “strongest code model,” but to build a retrieval-augmented context assembly pipeline that injects relevant files, type definitions, and test cases into the prompt.
def build_prompt(task, repo_context, top_k=8):ctx = retrieve(repo_context, task.query, k=top_k)return f"""Task: {task.type}Constraints: keep existing interface signatures, do not introduce new dependenciesRelevant context:{ctx}Code to process:{task.snippet}Output: return only the modified code and a change description"""
2.3 Multimodal and Document Understanding
The processing pipeline for images, scanned documents, and audio/video inputs typically includes preprocessing, layout reconstruction, structured extraction, and post-validation. The model is only one part of it, and upstream parsing quality often affects final accuracy more than model selection does.
2.4 Long Context and Knowledge-Intensive Tasks
A larger context window does not mean better effective utilization. You need to balance retrieval granularity, chunk reranking, and compressed summaries to avoid diluting key evidence.
3. Build a Reproducible Internal Evaluation Set
Public leaderboards deviate from real business distributions, so you must build your own evaluation set:
- Sampling: stratified sampling from real request logs, covering high-frequency, long-tail, and abnormal inputs.
- Annotation: define automatically judgeable metrics (structured field accuracy, unit test pass rate, citation hit rate) and human-rated dimensions (readability, instruction following).
- Regression: run the same set of cases after every change to prompts, model versions, or retrieval strategies, and form trend curves.
- Layered reporting: report separately by task type, input length, and language to avoid averages hiding weaknesses.
{"case_id": "code_fix_018","task_type": "bugfix","metrics": {"unit_test_pass": true, "diff_minimality": 0.82},"cost": {"input_tokens": 5120, "output_tokens": 640},"latency_ms": 2870}
4. The Trade-off Triangle: Cost, Latency, and Stability
Unit cost should be calculated as the total cost of completing a task, not the price per token. If a weaker model needs multiple retries to pass validation, its total cost may be higher. For latency, distinguish time to first token from overall completion time: interactive scenarios should prioritize the former, while batch scenarios should focus on throughput. For stability, pay attention to rate limiting, timeouts, and output format drift. It is recommended to set parsing-failure retries and fallback templates for structured output.
5. Architecture: An Abstraction Layer and Intelligent Routing
Abstract model invocation into a unified interface to hide differences and decouple business code from specific implementations:
class LLMClient:def chat(self, messages, **opts): raise NotImplementedErrorclass Router:def __init__(self, clients): self.clients = clientsdef pick(self, req):if req.type == "reasoning": return self.clients["deep"]if req.type == "chat": return self.clients["fast"]return self.clients["general"]
On top of this, add four types of strategies: first, tiered routing that splits traffic by task difficulty; second, semantic caching that reuses results for similar requests; third, concurrency and batching to improve throughput; and fourth, a fallback path that switches to a backup implementation and triggers alerts when the primary path fails. Observability is also necessary: record token consumption, elapsed time, failure reasons, and version identifiers, and connect to logging services and monitoring and alerting systems to form capacity and cost baselines.
6. Prompt and Context Engineering Essentials
Define the role and output contract clearly, and use parseable format constraints; structure long documents before feeding them in; require source snippets for key conclusions; and explicitly mark uncertain judgments as pending verification. On the security side, apply two-way filtering of inputs and outputs, mask sensitive fields, and limit the permission scope of tool calls.
7. Rollout Path and Common Pitfalls
The recommended path is: first run a small-scale feasibility validation, then build the evaluation set and abstraction layer, then gradually roll out with continuous regression. Common pitfalls include: relying only on public leaderboards for selection; treating the context window as a knowledge base; ignoring engineering constraints on output formats; lacking cost attribution; and treating prompt changes as risk-free.
In summary, the right approach to model selection is to treat it as a continuously evolving engineering problem: start from the task distribution, base decisions on your own evaluation, use an abstraction layer and routing strategies as means, and achieve a measurable balance among capability, cost, and stability. If you need an integrated platform to carry this, you can evaluate general capabilities such as the container platform, object storage, logging service, and monitoring and alerting offered by Baidu AI Cloud to build your own model integration and governance system.
