LLM Selection and Integration in Practice: From Evaluation to Production
This article explains how to choose and integrate large language models for production use. It covers why public leaderboards alone are not enough, six selection dimensions (task performance, context length, latency and throughput, cost, compliance, and stability), and how to build an in-house evaluation set. It also describes a unified inference access layer, staged rollout with dynamic routing, observability, cost governance, and an implementation checklist.
1. Why Model Selection Should Not Rely on Public Rankings
Public leaderboards reflect performance on specific test sets. The question types, language distribution, and scoring methods in those test sets often differ from a team’s real business workloads. A model that scores highly on code generation may not perform reliably on Chinese customer service Q&A or contract field extraction. Leaderboards are useful for filtering out clearly unsuitable candidates, but the final decision should be based on your own samples.
Another easily overlooked issue is the pace of version iteration. Different versions within the same model family can differ noticeably in quality, pricing, and API capabilities. A selection conclusion has a limited shelf life. Teams should build re-evaluation into their routine processes instead of making one selection and keeping it indefinitely.
2. Six Core Dimensions of Model Selection
- Task performance
Evaluate each business task separately, such as information extraction, summarization, multi-turn dialogue, code assistance, and logical reasoning. Score each task category on its own instead of relying on one overall score. An aggregate score can hide weaknesses in a critical scenario. For example, a model may have a high overall score while frequently making errors in extracting monetary amounts.
- Context length
The average and maximum length of your business documents determine the context window you need. The advertised context window may differ from the range the model can use effectively. To check, test recall with long document samples by placing key information at the beginning, middle, and end. Then decide whether chunking or retrieval-augmented generation is needed.
- Latency and throughput
Time to first token determines how long users perceive they are waiting. Output speed determines how long long responses take to finish. Concurrent throughput determines capacity planning. Interactive scenarios should prioritize time to first token and P95 tail latency. Offline batch processing cares more about throughput per unit of time and cost per unit. The two scenarios call for different optimization goals and should not be confused.
- Cost
Most services bill input and output tokens separately, and output tokens usually cost more. To estimate monthly cost, multiply the daily request volume by the average input length, then by the average output length. Include the overhead from retries, failed requests, and system prompts. Actual bills often exceed rough estimates, so leave a buffer.
- Compliance and data boundaries
When personal information or trade secrets are involved, confirm the following: whether data leaves the country, whether it is used for model training, how long logs are retained, and whether a data processing agreement can be signed. These conditions often narrow the candidate pool earlier than performance metrics do. Complete this screening before running evaluations.
- Stability and capability ecosystem
Review rate limiting policies, availability commitments, and version deprecation schedules. Also check support for commonly used features such as streaming output, function calling, and structured output. Providers name and design parameters for similar capabilities differently. Rely on the relevant API documentation and hands-on testing, not on feature names, to judge whether two capabilities are equivalent.
3. Building Your Own Evaluation Set
The evaluation set is the core asset of model selection. A reliable one is usually built in five steps.
Step 1: Sample from real business logs. Samples should cover high-frequency questions, edge cases, and historical failure cases. Avoid selecting only questions the model is likely to answer well. Each task type needs enough samples to show the distribution of results.
Step 2: Define scoring criteria for each sample. Use rules wherever possible. Examples include whether required fields are present, whether output is valid structured data, and whether values match the reference answers. For open-ended questions, use a rating scale. For example, score factual accuracy, completeness, tone, and format from one to five. At least two annotators should score each sample independently. Samples with large disagreement go to a third reviewer for adjudication, and the reasons for the decision are recorded.
Step 3: Fix the experimental conditions. Keep prompt templates, sampling temperature, maximum output length, and system instructions identical across models. Otherwise the comparison has no meaning. If a model needs a different prompt to perform its best, record that difference as a separate variable instead of mixing it into the comparison.
Step 4: Record multidimensional data. For each candidate model, record the quality score, average latency, P95 latency, cost per request, and failure rate. Summarize them in a comparison table. The table makes trade-offs visible. For example, a model with slightly lower quality but half the cost is information that decision makers need to see.
Step 5: Set pass thresholds. The business side should set thresholds based on the cost of errors. For fields written automatically to a database, format compliance may need to be close to 100%. Internal writing assistance can accept a lower bar. Do not copy thresholds from other teams. They should reflect your team’s risk tolerance.
The evaluation set also needs regular updates. Business changes, new features, and shifts in user behavior gradually make old samples less representative. Add a batch of new samples every quarter, and keep a fixed subset for longitudinal comparison.
4. Designing a Unified Inference Access Layer
If business code calls a provider’s API directly, switching models later becomes expensive. A safer approach is to add a unified access layer between the business logic and the models. This layer exposes one consistent calling method to the business. It also handles authentication, routing, retries, rate limiting, and logging.
The access layer usually includes four components:
- Adapters. Each provider has an adapter. It converts the unified request format into that provider’s API format, then converts the response back into a unified structure. Business code programs only against the unified structure.
- Routing policy. The policy decides which model to call first, based on task type, tenant tier, or cost budget. Store the policy in configuration so that changes do not require redeploying business code.
- Fallback and retries. When a model is rate limited or times out, traffic switches automatically to a backup model. Set an upper limit on retries and use exponential backoff, so that failures do not amplify traffic during an outage.
- Observability instrumentation. Record the model name, latency, token usage, error type, and result status of every call. This data supports later analysis.
The following pseudocode shows the call flow:
function call_llm(request):candidates = route_policy.select(request.task_type, request.tenant)for model in candidates:try:resp = adapter[model.provider].invoke(model = model.name,messages = request.messages,max_tokens = request.max_tokens,timeout_ms = model.timeout_ms)metrics.record(model.name, resp.latency_ms, resp.usage)return respexcept RateLimitError or TimeoutError:metrics.record_failure(model.name)continue // fall back to the next candidate modelraise AllModelsUnavailable
A few implementation points matter. Read API keys from a key management service. Never write them into code repositories or logs. Mask user input in logs so personal information is not stored long term. Set timeouts by task type. Timeouts for interactive requests should be clearly shorter than those for batch jobs.
5. Staged Rollout and Dynamic Routing
Do not switch all traffic to a new model at once. Roll it out in three stages.
Stage 1: Shadow traffic validation. Send each request to both the current model and the candidate model. Return only the current model’s response to users, and record both outputs and their metrics. This stage does not affect the live experience. It shows how the candidate performs on real traffic, not only on the evaluation set.
Stage 2: Small-percentage canary. Route a small share of real traffic, for example 5% to 20%, to the candidate model. Monitor spot-checked quality scores, user complaint rates, latency, and error rates. Define rollback conditions before the canary starts. For example, switch traffic back automatically when the error rate exceeds a set threshold.
Stage 3: Scenario-based routing. Different tasks need different model capabilities. Send simple classification and keyword extraction to lower-cost models. Send complex reasoning and long-document analysis to more capable models. Put a switch on the routing rules so that the system can quickly return to the unified policy if problems appear.
6. Observability and Cost Governance
After launch, monitor the following metrics continuously: request volume, success rate, P95 and P99 latency, token usage, cost per request, rate limit events, and quality spot-check scores. Connect these metrics to an alerting system and set a threshold for each one. For example, when the success rate stays below the set value for several consecutive minutes, trigger an alert and notify the on-call engineer.
Store call logs in a logging service. Set retention periods according to compliance requirements. Use role-based access control for log queries. Do not give all developers access to raw content.
Cost governance can start in four areas:
- Set usage quotas for each tenant or business line. Warn or downgrade the service when a quota is exceeded.
- Cache results for frequently repeated questions. Include the prompt version and model version in the cache key, so outdated results are not reused by mistake.
- Trim system prompts by removing instructions unrelated to the task. This reduces the fixed overhead of every request.
- Set maximum output token limits based on business needs. This prevents unusually long outputs from driving up costs.
7. Implementation Checklist
- Define the business task types and their priorities, and identify the core metrics for each type.
- Determine compliance and data boundaries, and filter out candidates that do not meet them.
- Build an evaluation set for each task type, and fix the scoring criteria and experimental conditions.
- Complete the candidate model evaluation, and produce a comparison table covering quality, latency, and cost.
- Build the unified access layer, and configure the routing policy, fallback rules, and observability instrumentation.
- Validate candidate models with shadow traffic, run a small-percentage canary, and then route traffic by scenario.
- Set up metric dashboards and alert rules. Re-evaluate candidate models once a quarter and update the selection conclusions.
Following this process keeps model selection grounded in your team’s real data and keeps the switchover controllable. Future model changes then require only configuration updates, not refactoring of business code.
