How to Choose and Integrate Chinese LLMs: A Practical Engineering Guide

    This guide explains how to move from leaderboard-driven debates to constraint-based selection of Chinese large language models, and how to integrate their APIs reliably. It covers hard and soft selection criteria, building a reproducible layered evaluation set, calculating effective cost with retry factors, designing a unified gateway with routing and fallback, and engineering techniques such as RAG, structured output contracts, and self-verification to reduce hallucinated answers. A final checklist helps turn model selection into a repeatable engineering process.

    1. The Real Problem: Solve Under Constraints, Not by Leaderboard Rank

    The usual debate is “which model is stronger,” but in engineering practice that question rarely converges. The reason is simple: model capability is a multi-dimensional vector, while business requirements usually constrain only a few of those dimensions. Treating leaderboard positions as the final decision typically costs you twice: you pay for capabilities you never use, and you get burned on the dimensions that actually matter, such as long-context stability and structured output success rate.

    A more reasonable approach is to model selection as a constrained solving process: fix the hard constraints first, then compare soft metrics within the feasible region.

    1. Hard constraints (fail one, and the model is out)
    2. ├── Data compliance and deployment form (public cloud API / on-premises)
    3. ├── Context window large enough for the input size of a single task
    4. ├── Stable structured output support (JSON Schema / function calling)
    5. └── Unit price and quota sufficient for peak concurrency
    6. Soft metrics (weighted scoring within the feasible region)
    7. ├── Long-document recall and use of mid-context information
    8. ├── Accuracy on complex reasoning and code generation
    9. ├── Time to first byte and throughput (affects interaction quality)
    10. └── Ecosystem maturity (SDKs, documentation, observability support)

    It is worth stressing that a larger parameter count does not mean better task performance. Parameter count mainly affects the model’s knowledge capacity and potential ceiling, while actual performance also depends on the training data mix, post-training strategy (alignment and instruction tuning), decoding configuration at inference time, and how context is organized. A smaller model that has been thoroughly post-trained on Chinese corpora and structured tasks often outperforms a larger general-purpose model on information extraction and summarization; conversely, larger models show a clearer advantage on cross-domain complex reasoning.

    2. Build a Reproducible Evaluation: Turn Opinions into Data

    Any selection conclusion without evaluation support is just a subjective impression. Build a layered evaluation set: it does not need to be large, but it must reflect the real distribution.

    The first layer is a capability baseline, using public general benchmarks to measure knowledge breadth and reasoning level, for reference only and not as the main decision basis. The second layer is the scenario set: sample 100–300 tasks from real business logs, covering typical phrasings, boundary inputs, and adversarial samples. The third layer is stability regression: fix the random seed and decoding parameters, call repeatedly, and measure output consistency to surface occasional nonsense.

    Scoring should combine three sources: rules, model review, and human spot checks.

    1. # Minimal skeleton of a layered evaluation
    2. cases = load_cases("scene_set.jsonl") # scenario set
    3. def evaluate(model_client, cases):
    4. result = {"rule_pass": 0, "schema_ok": 0, "latency_p95": []}
    5. for c in cases:
    6. out = model_client.chat(c.prompt, temperature=0.2)
    7. result["latency_p95"].append(out.latency_ms)
    8. if rule_check(c.expected, out.text): # rule-decidable parts
    9. result["rule_pass"] += 1
    10. if json_schema_validate(c.schema, out.text): # structured output success rate
    11. result["schema_ok"] += 1
    12. result["rule_pass"] /= len(cases)
    13. result["schema_ok"] /= len(cases)
    14. result["latency_p95"] = percentile(result["latency_p95"], 95)
    15. return result

    The key metrics here are not “how good the answer is” but the structured output success rate and P95 latency. These two directly determine whether downstream systems can consume model output automatically. In practice, a lower temperature, an explicit output contract, and a few examples significantly improve parseability.

    3. Cost and Latency: Convert “Expensive” into Engineering Metrics

    “Too expensive” is a vague statement. In engineering terms it should be broken into three computable parts: input-side cost, output-side cost, and the hidden cost of retries. For long documents, input dominates, so context compression and retrieval augmentation (recall fragments first, then hand them to the model) reduce cost more effectively than switching models. For tasks with high output-side cost, structured constraints can compress redundant phrasing.

    The hidden cost is the easiest to overlook: if a model’s structured output success rate is low and you actually need 1.5–2 retries to get a usable result, its real unit price should be multiplied by the retry factor.

    1. Effective cost ≈ (input tokens × input price + output tokens × output price) × retry factor
    2. retry factor = 1 / first-pass usability rate

    For latency, distinguish time to first byte from total generation time. Interactive applications are sensitive to first-byte latency, while batch jobs care more about throughput. If a single vendor cannot satisfy both, the right fix is to split traffic at the gateway layer rather than hard-coding one model in business code.

    4. A Unified Access Layer: Hide Model Differences Behind an Abstraction

    Using multiple models requires interface abstraction. Define an internal unified chat abstraction, converge vendor differences into an adapter layer, and let business code depend only on your own interface. On this layer, Baidu AI Cloud offers general cloud service capabilities: model services combined with basic components such as object storage, logging, and monitoring and alerting can form a complete invocation and observability chain.

    1. class ChatModel(Protocol):
    2. def chat(self, messages: list[dict], **kw) -> ChatResult: ...
    3. class UnifiedGateway:
    4. def __init__(self, adapters: dict[str, ChatModel]):
    5. self.adapters = adapters
    6. def call(self, scene: str, messages, **kw):
    7. name = self.route(scene) # route by scenario
    8. try:
    9. return self.adapters[name].chat(messages, **kw)
    10. except (TimeoutError, RateLimitError):
    11. return self.adapters[self.fallback(name)].chat(messages, **kw)
    12. def route(self, scene: str) -> str:
    13. # long docs → long-context model; extraction → high-stability model; chitchat → low-cost model
    14. return POLICY.get(scene, "default")

    Route by task type rather than by “newest and strongest”: long-document understanding goes through the long-context channel, information extraction and code generation go through the stability-first channel, and low-value high-frequency requests go through the low-cost channel. Also set timeouts, rate-limit circuit breaking, and a fallback chain so that jitter from a single vendor does not affect overall availability.

    5. Suppressing Hallucination: Engineering First, Model Swapping Second

    Producing plausible but wrong content is an inherent property of generative models and cannot be eliminated by switching models. Four engineering measures work: retrieval augmentation, which puts the evidence in context and requires source attribution; structured output constraints, which use fixed fields and enum values to narrow the space for improvisation; self-verification, where a second call only validates and scores; and low temperature with fixed decoding configuration to improve reproducibility.

    1. {
    2. "answer": "……",
    3. "evidence": ["quoted source fragment 1", "fragment 2"],
    4. "confidence": 0.0,
    5. "need_human_review": true
    6. }

    Forcing the return of evidence fragments and a confidence score is a low-cost way to make uncertainty explicit, and it lets human spot checks focus on low-confidence samples.

    6. Deployment Checklist

    1. Write down the hard constraints first (compliance, deployment form, context length, structured output), then discuss strength.
    2. Build a 100–300 case scenario set sampled from real business traffic; make first-pass usability rate and P95 latency the primary metrics.
    3. Account for cost as “effective cost = nominal cost × retry factor,” and prioritize retrieval and compression for long documents.
    4. Build unified abstraction with routing and fallback in the access layer; do not bind business code to any single model.
    5. Use the trio of retrieval augmentation, structured contracts, and self-verification to suppress wrong output, and keep a human review channel.
    6. Set up invocation logging and monitoring alerts, run regression evaluations weekly, and trigger comparison automatically when model versions update.

    Following this process turns selection from a subjective argument into a sustainable engineering decision: models can be replaced, while the evaluation and gateway assets always stay in your own hands.