A Practical Guide to Integrating and Selecting Chinese LLM APIs

    This guide breaks down large language model (LLM) selection into a repeatable engineering framework. It covers building neutral evaluation dimensions, preparing API keys and endpoints, implementing a vendor-agnostic client layer with retry and streaming logic, tuning prompts and parameters, and managing stability, cost, and observability in production. It also lists common pitfalls to avoid when working with Chinese LLM APIs.

    1. Why Model Selection Is Hard: Missing Evaluation Dimensions

    Over the past year or two, Chinese large language models have been iterating quickly, and different vendors tend to perform differently across tasks. The real challenge for developers is not a lack of options, but the absence of a reusable evaluation framework. A model that leads on a benchmark today may be surpassed by a new version tomorrow. The same model can also have different available versions, rate limits, and billing structures depending on the access channel.

    A rational approach is to break “which model should I choose” into three concrete engineering questions:

    • What category does my business task fall into (long-context understanding, structured extraction, code generation, multi-turn dialogue, tool calling)?
    • What are my hard constraints on latency, throughput, context length, and concurrency quotas?
    • Can I abstract the model invocation layer so that models are replaceable without affecting business code?

    Once these three questions are answered, model selection shifts from “brand preference” to “constraint solving.”

    2. Building Neutral Capability Evaluation Dimensions

    Before you have real test data, avoid making decisions based on any single marketing claim. Useful general dimensions include:

    1. Context window and effective utilization. The advertised context length is only an upper bound. What matters is whether key information can still be reliably recalled under long inputs. Build your own baseline with “needle-in-a-haystack” style tests.
    2. Controllability of reasoning modes. Some models offer a deep-thinking mode that trades some latency for stronger multi-step reasoning. Engineering-wise, you need to toggle this per request rather than fixing it globally.
    3. Structured output stability. Whether the model consistently produces valid JSON, whether fields go missing, and whether enum values drift directly determine whether it can feed downstream automation.
    4. Tool calling and function signature adherence. Adherence to parameter names, required fields, and nested structures is a prerequisite for building agents.
    5. Multimodal and input format support. Confirm early in the selection process whether you need capabilities such as image, audio, or file parsing.
    6. Engineering usability. This includes rate limiting policies, concurrency quotas, streaming output support, clarity of error code semantics, and version change notification mechanisms.

    A practical approach is to build a small evaluation set: extract 50–100 representative samples from real business scenarios, covering both typical and edge cases. Run the same prompts across candidate models in batch, and record accuracy, average latency, P95 latency, and token consumption in a comparable table. This evaluation set should be maintained continuously as the business evolves.

    3. Preparation Before Integration

    Regardless of which type of model service you ultimately choose, the integration process is largely the same:

    • Apply for and securely store API keys. Keys must only be used on the server side and must never be written into frontend code or committed to version control.
    • Confirm the mapping between the Base URL and the Model ID. Different channels may use different names for the same model.
    • Understand the general billing structure: input and output tokens are usually priced separately, and long context or reasoning modes can significantly increase consumption.
    • Prepare isolated keys and quotas for development, testing, and production to prevent debugging traffic from affecting live services.

    For key management, inject credentials via environment variables or a key management service, following the principle of least privilege and rotating them regularly:

    1. export MODEL_API_KEY="<your-key>"
    2. export MODEL_BASE_URL="<provider-endpoint>"
    3. export MODEL_ID="<model-identifier>"

    4. A Vendor-Agnostic Invocation Layer

    To make models replaceable, add a thin wrapper between your business logic and the model, consolidating “build request — handle streaming — retry on error” in one place.

    1. import os, json, time, random
    2. import requests
    3. class ModelClient:
    4. def __init__(self, base_url=None, model=None, timeout=60):
    5. self.base_url = base_url or os.environ["MODEL_BASE_URL"]
    6. self.model = model or os.environ["MODEL_ID"]
    7. self.timeout = timeout
    8. self.session = requests.Session()
    9. self.session.headers.update({
    10. "Authorization": f"Bearer {os.environ['MODEL_API_KEY']}",
    11. "Content-Type": "application/json",
    12. })
    13. def chat(self, messages, stream=False, temperature=0.7, max_tokens=2048, **extra):
    14. payload = {
    15. "model": self.model,
    16. "messages": messages,
    17. "stream": stream,
    18. "temperature": temperature,
    19. "max_tokens": max_tokens,
    20. }
    21. payload.update(extra) # carries optional parameters such as reasoning mode and tool definitions
    22. return self._with_retry(payload, stream)
    23. def _with_retry(self, payload, stream, attempts=3):
    24. for i in range(attempts):
    25. try:
    26. resp = self.session.post(
    27. f"{self.base_url}/chat/completions",
    28. json=payload, timeout=self.timeout, stream=stream,
    29. )
    30. if resp.status_code in (429, 500, 502, 503, 504):
    31. raise RuntimeError(f"retryable status {resp.status_code}")
    32. resp.raise_for_status()
    33. return resp
    34. except Exception as exc:
    35. if i == attempts - 1:
    36. raise
    37. time.sleep(2 ** i + random.random())

    The core logic for parsing streams is to read line by line and concatenate incrementally:

    1. def stream_text(resp):
    2. buffer = ""
    3. for line in resp.iter_lines(decode_unicode=True):
    4. if not line or not line.startswith("data:"):
    5. continue
    6. data = line[len("data:"):].strip()
    7. if data == "[DONE]":
    8. break
    9. try:
    10. chunk = json.loads(data)
    11. delta = chunk["choices"][0]["delta"].get("content", "")
    12. buffer += delta
    13. yield delta
    14. except json.JSONDecodeError:
    15. continue
    16. return buffer

    The value of this wrapper is that switching models requires only replacing the model identifier and endpoint in the environment variables, with zero changes to business code. It also centralizes error-prone details such as retries, timeouts, and streaming protocols.

    5. Prompt and Parameter Tuning

    • Route the temperature parameter by task: use low temperature for deterministic tasks like extraction, classification, and code generation; use higher temperature for creative work and brainstorming.
    • Explicitly constrain output format, and provide field descriptions and examples in the prompt. For critical scenarios, add a validation pass that enforces “JSON only” and a fallback for failures.
    • For long-context tasks, segment and summarize/compress content first, then let the model perform global reasoning. This can significantly reduce cost and latency.
    • Deep reasoning modes suit math and multi-step planning problems. For latency-sensitive online paths, disable them by default and set hard timeouts.
    • Establish prompt version control. Run regression tests with a fixed evaluation set after every change to avoid “fixing one scenario and breaking three others.”

    6. Stability, Cost, and Observability

    Production readiness requires three things: budget control for timeouts and retries (to avoid retry amplification of traffic), a multi-model fallback strategy (switch to a backup model when the primary is unavailable), and complete invocation logs (recording request IDs, token usage, latency, and error codes for troubleshooting and cost accounting).

    For cost governance, control spending through input caching and deduplication, pre-extraction of long documents, and tiered model selection based on business value. Observability can be built from general cloud capabilities: a logging service to collect invocation records, monitoring and alerting with thresholds on error rate and P95 latency, a message queue to smooth traffic peaks, and object storage to archive evaluation samples and results.

    7. Common Pitfalls

    • Looking only at advertised context length while ignoring effective recall rate.
    • Hardcoding keys in client code or baking them into images.
    • Switching models frequently without an evaluation set, making performance fluctuations impossible to attribute.
    • Ignoring version changes, so output format drifts after a model upgrade without anyone noticing.
    • Sending every request to the strongest model, leading to runaway costs.

    8. Conclusion

    The right approach to selecting Chinese LLMs is to first build evaluation dimensions and an evaluation set, then abstract the invocation layer into a replaceable component, and finally use engineering practices to control stability and cost. With these three steps, “which model to choose” is no longer a one-time bet but a process of continuous optimization. If you need managed model services along with supporting data, logging, and monitoring capabilities, Baidu AI Cloud offers complete support under general categories that can be flexibly combined according to business constraints.