How to Choose and Integrate Chinese LLMs: A Practical Engineering Guide
This guide explains how to move from leaderboard-based model selection to building a sustainable LLM integration capability. It covers building an internal evaluation set, comparing managed inference APIs with private deployment, designing a thin backend abstraction with routing, prioritizing prompt and decoding tuning, and addressing cost, security, and observability so model swaps become reversible configuration changes.
1. Reframing the Problem: From “Which Model Should We Pick” to “How Do We Build Sustainable Model Integration”
Many model selection discussions start with a screenshot of a leaderboard: a model ranks near the top on code generation benchmarks, so the team decides to replace its current model entirely. The risk is that leaderboards reflect average performance over a specific task distribution, while real business traffic is often heavily skewed—perhaps 80% of requests are structured extraction and only 20% involve multi-file code understanding. Putting a model with a high average score in front of such a skewed workload can deliver a worse experience than a model with a slightly lower overall score but lower variance.
A more reasonable approach is to break the problem into three layers:
- Capability layer: the model’s performance on your task distribution, context length, structured output stability, and multimodal needs;
- Service layer: the form of the inference service (managed API, private deployment, edge inference), elasticity and rate-limiting strategy, and release cadence;
- Engineering layer: integration abstraction, observability, cost control, and compliance and data boundaries.
A weakness in any one of the three layers cancels out the gains from “picking the right model.” For example, the model may be capable enough, but if the service side has no stable rate quota or fallback path, errors go straight to users at peak times.
2. Capability Evaluation: Build Your Own Eval Set Instead of Relying on Public Leaderboards
Public leaderboards are good for initial screening, not for decisions. Build an internal eval set of 200–500 cases that covers your real business distribution, and label each sample with an expected value that can be judged automatically.
Suggested evaluation dimensions:
- Instruction following: whether output format, field naming, and length constraints are strictly respected;
- Structured output: JSON schema validity rate, missing-field rate, and numeric type correctness;
- Long context: recall of information in the middle of long documents (avoid looking only at the beginning and end, which creates a recency advantage);
- Code capability: cross-file dependency understanding and unit test pass rate, rather than snippet completion alone;
- Stability: variance across repeated samples of the same input—high variance means heavier post-processing;
- Refusal and safety: whether handling of unauthorized or sensitive-data requests meets your compliance requirements.
A reusable automated evaluation skeleton (illustrative; interfaces follow your own abstraction layer):
def run_eval(model_client, dataset, k=3):report = {}for name, case in dataset.items():scores = []for _ in range(k): # sample multiple times to assess varianceraw = model_client.chat(case.prompt, params=case.params)scores.append(case.metric(parse(raw), case.expected))report[name] = {"mean": sum(scores) / k,"variance": max(scores) - min(scores),}return report
Key engineering detail: track “parse failure” as its own metric. Many production incidents are not wrong answers but outputs that downstream systems cannot parse; these should be addressed ahead of accuracy.
3. Service Form: Managed APIs vs. Private Inference
There are roughly two mainstream ways to obtain models today: calling a managed inference API through a cloud platform, or deploying open weights on a container platform or your own GPU cluster. They are not mutually exclusive; they can coexist.
Managed APIs offer fast time to launch, no operations burden, and elasticity handled by the platform, which suits businesses with volatile traffic and short validation cycles. What to watch: quotas, rate limits, the scope of data leaving your environment, and how version changes are announced.
Private inference keeps data in your environment, gives more controllable unit cost under stable high load, and allows quantization and batching optimizations tailored to the business. The cost is that you take on GPU memory planning, concurrency scheduling, failover, and model upgrades yourself.
A common middle ground is tiered routing: send requests containing sensitive fields or strict compliance requirements to the private cluster, send general generation requests to the managed API, and unify authentication, metering, and log formats in the abstraction layer.
4. Integration Abstraction: A Thin Wrapper for Long-Term Replaceability
Models iterate far faster than business code is refactored, so do not hardcode one vendor’s API in business code. Define a minimal capability set and implement adapters for multiple backends:
class ModelBackend:def chat(self, messages, *, temperature=0.2, max_tokens=1024,json_schema=None): ...def embed(self, texts): ...def health(self): ...class Registry:def __init__(self): self._b = {}def add(self, tag, backend): self._b[tag] = backenddef get(self, tag): return self._b[tag]
The routing layer should support three strategies: static routing by task tag, dynamic down-weighting based on real-time quality metrics, and circuit breaking by cost budget. Combined with unified retry and timeout budgets (for example, an overall 8-second budget with no single call exceeding 5 seconds, leaving the remaining time for a fallback template), this can significantly reduce the impact of tail latency on users.
5. Tuning: Priority Order for Prompts, Parameters, and Post-Processing
In practice the payoff order is usually: data and prompt design > parameters and decoding strategy > switching models. Proceed in this order:
- Define the output contract: field descriptions, examples, and fallback behavior for invalid input;
- Reduce decoding randomness: push temperature to 0–0.2 for extraction and classification tasks, and loosen it moderately for creative tasks;
- Constrain length and structure: validate with a schema rather than hard-parsing with regex, and trigger one repair retry with the error message when validation fails;
- Retrieval augmentation: put external knowledge in the context instead of relying on the model’s parametric memory, making updates and audits easier;
- Small model first: use a lightweight model for intent classification and routing, reserving expensive calls for complex requests.
Illustrative repair-retry implementation:
def chat_json(client, prompt, schema, retry=1):for i in range(retry + 1):out = client.chat(prompt, json_schema=schema)try:return validate(out, schema)except Invalid as e:prompt = prompt + f"\nLast output was invalid: {e}. Return only the corrected JSON."raise SchemaError("structured output failed repeatedly")
6. Cost, Security, and Observability
Cost governance comes down to three levers: context trimming (removing repeated history and redundant retrieved fragments), caching (semantic caching for frequent identical requests with an invalidation policy), and model tiering (simple requests go to smaller models). Tag token consumption by business line so you can identify the real heavy consumers.
Security must cover both directions. On input, detect and redact sensitive information; on output, audit before persisting. Keep keys in a key management service and never commit them to code repositories. For multi-tenant scenarios, enforce data isolation and log redaction.
For observability, collect four metric groups: call success rate, structured parse success rate, end-to-end latency percentiles (P50/P95/P99), and cost per request. With these four, replacing a model becomes a rollback-able configuration change rather than a gamble.
7. Rollout Roadmap
- Weeks 1–2: define the task distribution and build the internal eval set and baseline;
- Weeks 3–4: complete the abstraction layer and dual-backend integration, and get canary release and rollback working;
- Weeks 5–6: add caching, rate limiting, fallback, and cost tagging;
- Week 7 onward: review quality metrics weekly and roll model versions forward based on eval results.
The conclusion is not complicated: instead of asking “which model is the strongest,” ask “under my task distribution, service form, and compliance boundaries, which combination has the lowest total cost and the best rollback-ability.” Turn selection into a measurable, replaceable engineering capability—the faster models iterate, the more you benefit.
