How to Choose and Integrate a Domestic LLM: A Practical Guide
This guide presents a practical framework for selecting and integrating a large language model. Instead of relying on public leaderboards, it shows how to build your own evaluation set, compare hosted and self-hosted inference, normalize API differences through an adapter layer, and measure performance and cost with real data. It also includes a stability engineering checklist covering retries, fallback, observability, security, and canary rollouts.
1. Reframing the Problem: From “Which Model” to “How to Choose”
When teams start model selection, the first instinct is often to look for a leaderboard answer. But leaderboards only reflect relative performance under a specific task distribution; they cannot replace validation on your own business data. A more reliable approach is to break the problem into three verifiable sub-questions: whether the task falls within the model’s capability coverage, whether the inference service can meet throughput and latency constraints, and whether integration and operational costs are acceptable.
It is worth emphasizing that model capability, service availability, and engineering fit are three independent evaluation axes. Strong performance in public benchmarks does not mean a model will be equally stable on your private data distribution; an endpoint that returns results does not mean it can meet your business SLA under concurrent load. Selection conclusions must therefore be backed by your own test data, not inferred from external buzz.
2. Capability Evaluation: Build Your Own Evaluation Set
Building the evaluation set is the most frequently skipped step in selection, yet it has the greatest impact on how reliable the conclusion is. A practical process is “sample real requests + stratified sampling + a human-labeled baseline.” The set does not need to be large: one or two hundred high-quality samples covering typical scenarios are often more discriminative than thousands of random ones.
The evaluation dimensions can be split into four layers:
- Correctness: whether the answer satisfies business constraints and whether it contains factual errors;
- Instruction following: whether format, length, and field structure strictly match the requirements;
- Stability: output consistency across repeated calls with the same input, especially at low temperature settings;
- Robustness: how much quality degrades with very long contexts, noisy input, and multi-turn follow-up questions.
A sketch of the evaluation loop is shown below. The key is to decouple “model invocation” from “scoring logic” so that multiple candidates can be compared side by side:
def run_eval(candidates, dataset, scorer):report = {}for name, client in candidates.items():rows = []for case in dataset:raw = client.chat(messages=case.messages,temperature=0.0, # Fixed parameters during evaluation to reduce randomnessmax_tokens=case.limit)rows.append(scorer(case, raw))report[name] = aggregate(rows)return report
For generative tasks, in addition to human scoring, you can add rule-based checks (such as JSON parse rate and missing-field rate) and pairwise comparison to reduce the bias of any single automated metric.
3. Inference Service Options: Hosted APIs vs. Self-Hosting
Once model capability is settled, you need to decide how to obtain inference service. There are three common options: using a standardized hosted inference API in the cloud, self-hosting inference on a container platform, or a hybrid elastic architecture that combines both.
Hosted APIs have low startup cost and free you from driver and GPU memory scheduling concerns, making them suitable for projects with spiky traffic or in the validation phase. The tradeoff is weaker control: quotas and queuing depend on resources on the platform side, and responses may slow down at peak times. Self-hosting offers the strongest control and allows deep tuning of batch size, concurrency, and quantization precision, but you take on GPU capacity planning, image maintenance, version upgrades, and failure mitigation. A hybrid architecture keeps stable baseline traffic on a self-hosted cluster and spills burst traffic over to hosted APIs.
Whichever option you choose, it is recommended to implement a unified abstraction layer on the client side so that business code is not tightly coupled to one specific API:
class LLMClient:def chat(self, messages, **kw): raise NotImplementedErrorclass HostedClient(LLMClient): # Hosted inference API...class SelfHostedClient(LLMClient): # Self-hosted inference service...
4. API Compatibility and Portability
The industry commonly follows an HTTP API convention similar to the mainstream open-source ecosystem, with three endpoint types: “chat completions + text completions + embeddings.” The request body includes fields such as the model identifier, message array, temperature, and maximum generation length; the response body returns candidate text and usage statistics. During selection, check item by item: whether streaming responses are supported, whether tool calling and structured output are supported, whether error code semantics are clear, and whether usage and rate-limit response headers are provided.
The key to portability is confining differences to the adapter layer. The adapter below only performs field mapping and error normalization, so the business side depends only on unified exceptions:
def normalize(resp):if resp.status_code == 429:raise RateLimited(retry_after=resp.headers.get("retry-after"))if resp.status_code >= 500:raise UpstreamUnavailable(resp.text)return resp.json()["choices"][0]["message"]["content"]
5. Performance and Cost: Decide with Data, Not Gut Feel
Performance evaluation must distinguish time to first token from total generation time: the former determines interactive responsiveness, while the latter determines how long batch jobs take. When testing, record P50/P95 latency, timeout rate, and rate-limit hit rate at different concurrency levels, and observe degradation in long-context scenarios.
For cost, use “cost per thousand effective requests” as the measure, factoring in retries, failure fallback, and cache hits rather than looking at unit price alone. Overhead can be reduced through semantic caching, result reuse, context trimming, and tiered model routing (sending simple requests to smaller models).
6. Stability Engineering Checklist
- Timeouts and retries: set separate connect and read timeouts; use exponential backoff with jitter for retries to avoid a synchronized storm;
- Circuit breaking and fallback: trip the circuit after consecutive failures and fall back to a backup model or a templated response;
- Observability: consistently log request identifiers, token usage, and latency percentiles, and connect to logging services and monitoring alerts;
- Security and compliance: moderate content in both directions (input and output), mask sensitive information, and keep keys in a configuration center rather than in the code repository;
- Canary and rollback: roll out a new model to a percentage of traffic and keep a switch to revert to the previous version in one step.
7. Conclusion
Selection is not a one-time action but a loop of “small-sample evaluation → small-traffic canary → metric-driven scaling.” Evaluating capability, service form, API compatibility, and cost at the same time, and using an adapter layer to isolate uncertainty, keeps the engineering side stable in an environment where models iterate quickly. Baidu AI Cloud provides full support across model services and general-purpose capabilities such as data, containers, and monitoring, and can serve as one reference path for teams putting this into practice.
