How to Choose and Integrate Chinese LLM APIs: A Practical Engineering Guide
This guide treats the selection of a Chinese large language model as an engineering problem rather than a brand comparison. It covers six measurable evaluation dimensions, API key issuance and rotation, a unified gateway that isolates model differences, stability patterns such as layered timeouts and fallback chains, observability and cost governance, and security and compliance practices, along with reusable code skeletons. The goal is a pluggable multi-model call layer that lets you swap models without changing business code.
1. Background: Why Model Selection Should Not Be Based on Intuition
The original question is “which Chinese LLM should we choose?” Treating it as a brand comparison means the conclusion will quickly go stale. A more rigorous approach is to frame it as an engineering problem: given a set of business constraints, how do you build a multi-model call layer that is replaceable, measurable, and governable? The model is just a pluggable implementation behind that layer, and business code should not be coupled to any single vendor’s API details.
Three common pain points:
- Capability mismatch: using a general-purpose chat model for structured extraction leads to unstable output.
- Uncontrolled cost: without usage aggregation per business dimension, teams only discover at month end that long context and multi-turn replay have consumed the budget.
- Supply risk: when a single channel is rate limited or jittery, there is no fallback path, and the failure passes straight through to users.
Accordingly, this article first presents evaluation dimensions, then engineering practices for integration and governance, and finally a reusable code skeleton.
2. Evaluation Dimensions: Breaking “Usability” into Measurable Metrics
Score candidates across six dimensions, each with a reproducible measurement method rather than a subjective impression.
- Task performance: run offline evaluation on your own business dataset (200–500 items recommended, covering long-tail and adversarial samples). Metrics include accuracy, structured output compliance rate, and hallucination rate.
- Context and long text: focus on effective context length rather than the nominal length. Test mid-context recall by placing key constraints in the middle of a long document.
- Latency profile: distinguish time to first token from overall throughput. Interactive products care about first-token latency; batch processing cares about throughput.
- Cost model: estimate as “input tokens + output tokens + retry amplification factor.” Long-context scenarios need separate modeling.
- Compliance and data boundaries: whether data is used for training, log retention period, and support for enterprise-grade auditing and private network access.
- Engineering ecosystem: compatibility with the mainstream OpenAI-style calling protocol, streaming output support, and support for function calling and structured output constraints.
A practical scoring table (illustrative):
weights = {"effect":0.35, "latency":0.15, "cost":0.2,"context":0.1, "compliance":0.15, "eco":0.05}score = sum(weights[k] * v[k] for k in weights) # v is the normalized score from 0 to 1
Weights should be adjusted by business type: customer service raises the weights for compliance and performance, while offline labeling raises the weights for cost and throughput.
3. API Keys and Credentials: The Full Path from Issuance to Storage
The core action in the source material is “generate a long-lived API key in the console.” A more robust engineering description is:
- After logging in to the console, go to the access credentials page under personal or project settings.
- Create a new credential and fill in a purpose identifier (such as
prod-retrieval) to support later auditing. - Prefer “long-lived” for the validity period, but pair it with a rotation mechanism rather than never rotating.
- Immediately after generation, write the key into a key management service or environment variables. Never commit plaintext to a repository or paste it into chat logs.
Storage conventions:
# Inject into the process environment only; do not write into code or imagesexport MODEL_API_KEY="$(cat /run/secrets/model_api_key)"
import osKEY = os.environ["MODEL_API_KEY"] # Fail fast when missing to avoid silent degradation in production
Rotation recommendations: run two keys in parallel (old and new both valid for one release cycle), and support hot switching on the gateway side. Force rotation every quarter or whenever personnel change, and retain call audit logs for traceability.
4. Unified Gateway: Isolating Model Differences with One Abstraction Layer
Insert a gateway layer between the business and the models. Its responsibilities include protocol adaptation, routing, rate limiting, caching, and metering. The core interface exposes only three semantics: chat, embed, and rerank.
class ModelBackend:def chat(self, messages, **kw): ...def embed(self, texts, **kw): ...class Gateway:def __init__(self, backends): self.backends = backendsdef chat(self, messages, **kw):for name in self.route(kw.get("task")):try:return self.backends[name].chat(messages, **kw)except (TimeoutError, RateLimited):continueraise RuntimeError("all backends failed")
Routing policies can be layered in three ways: by task type (extraction, generation, summarization), by cost budget, and by real-time health. Health is measured with a sliding window over error rate and time to first token; a node is removed after consecutive failures.
5. Stability Design: Timeouts, Retries, Rate Limiting, and Fallback
- Layer the timeouts: keep connection timeout short (1–2 seconds) and set read timeout dynamically based on output length.
- Retry only on idempotent errors (rate limiting, timeouts, 5xx), with exponential backoff plus jitter, capped at 2 attempts to avoid a retry storm that amplifies cost.
- Apply rate limiting on the client with a token bucket, allocating quota per business line so a single campaign cannot saturate the global limit.
- Fallback chain: primary model → backup model → smaller-parameter model → rules/templates as a last resort → explicit failure with a message to the user.
- Streaming output must be “interruptible”: cancel the upstream request promptly when the client disconnects to stop the loss.
import random, timedef call_with_retry(fn, n=2):for i in range(n + 1):try: return fn()except RateLimited:if i == n: raisetime.sleep((2 ** i) * 0.3 + random.random() * 0.2)
6. Observability and Cost Governance
The minimal observability set: request volume, success rate, P95 time to first token, P95 end-to-end latency, token consumption, cache hit rate, and number of fallbacks. Log request_id, model identifier, token counts, and elapsed time, but do not log raw sensitive text; hash or redact it when necessary.
Cost governance measures:
- Trim prompts and prune history (sliding window plus summary compression).
- Semantic caching to reuse results for high-frequency similar questions.
- Separate offline tasks with batch processing and asynchronous queues.
- Set budgets and alert thresholds per business line, and automatically downgrade the model tier when a threshold is exceeded.
7. Security and Compliance Essentials
Encrypt everything in transit; apply least privilege to credentials and isolate them by environment; moderate content in both directions (input and output); define an explicit retention period for user data and support deletion; redact personal information before it enters the model pipeline; and retain complete call audits to meet traceability requirements. If the business is sensitive to data leaving a region, a general approach is to use multi-region endpoints from the same vendor or private network access.
8. Conclusion
“Which model should we choose” should become “how do we build a solid call layer.” Start with reproducible evaluation to determine the candidate pool and weights, then use a unified gateway to isolate differences, combined with key rotation, layered timeouts, backoff retries, a fallback chain, and cost alerts. The result is an architecture where swapping models requires no business code changes. If you need an out-of-the-box model service with enterprise-grade governance, you can evaluate the relevant general capabilities of Baidu AI Cloud (for example, using a container platform to host the gateway, log service and monitoring alerts for observability, and key management for credential storage), which reduces selection risk to a single configuration change.
