Selecting and Deploying Open-Source LLMs in China: A Practical Guide with Qianfan Integration

    This article provides a practical framework for Chinese enterprises choosing and deploying open-source large language models (LLMs) on the Baidu AI Cloud Qianfan platform. It covers how to interpret public benchmark scores, which dimensions to compare during model selection, steps for fine-tuning, the use of RAG to reduce hallucinations and incorporate business data, and a sample API integration. The guide emphasizes reproducible evaluation, cost analysis, and licensing considerations.

    Many technical leaders in Chinese enterprises are currently facing the question of how to select and use open-source large language models. Open-source models can already handle a wide range of business tasks, but a high benchmark score does not guarantee a good fit for your specific business. This article provides actionable steps covering benchmark interpretation, model selection methodology, fine‑tuning and retrieval‑augmented generation (RAG) practices on the Qianfan platform, as well as cost and safety considerations.

    How to Read Public Benchmark Scores

    Many articles claim that a model “approaches international mainstream quality” or “outperforms competitors on a certain test.” Before accepting such conclusions, verify four things: the benchmark name, the exact model version, the prompt and decoding parameters, and the test date. If any of these is missing, the result cannot be reproduced.

    The same model can rank very differently across different benchmarks. Mathematical reasoning, code generation, long‑context retrieval, and multi‑turn dialogue each stress distinct capabilities. Therefore, during selection, prioritize tests that resemble your business use cases rather than a single aggregate score from a leaderboard.

    This article intentionally avoids specific scores. Model versions evolve quickly, and cached numbers become obsolete. Readers should verify the latest data on official model pages, model cards, and public leaderboards, and record those numbers as selection evidence.

    What Dimensions to Compare During Selection

    Before selecting, break down business requirements into measurable criteria, then use the same sample set to compare candidate models. The table below lists common dimensions that you can copy into your team’s documentation and fill in.

    Dimension What to Ask Suggested Measurement
    Task fit Can the model handle core tasks such as classification, extraction, QA, code generation? Blind test with 100–300 real business samples
    Instruction following Is the output format stable (e.g., JSON or fixed fields)? Calculate format compliance rate
    Long-context capability Can it accurately locate information in long documents like contracts or financial reports? Measure recall and precision on documents with ground truth
    Hallucination rate Are answers supported by source material? Manual sampling; record the proportion of unsupported statements
    Inference cost Is the cost per request and latency acceptable? Estimate token usage and P95 latency based on real traffic
    License Does it allow commercial use? Are there restrictions? Read the license text line by line
    Deployment Public cloud managed service or on‑premises? Combine with data compliance requirements

    There is no need to always choose the strongest model. For simple classification or information extraction, a smaller model is often faster and cheaper while still achieving sufficient quality.

    What to Prepare Before Fine‑Tuning

    Many teams jump straight into fine‑tuning and find that improvements are minimal. Fine‑tuning is most suitable for solving problems like fixed output formats, industry‑specific terminology and style, and stability for specific tasks. If the issue is knowledge freshness or retrieving existing information, RAG is usually more appropriate.

    On the Qianfan platform, for parameter‑efficient fine‑tuning (such as LoRA or P‑Tuning), follow these steps.

    1. Prepare data. Each sample contains an input and expected output, saved uniformly in JSONL format, e.g., {"messages": [...]} or {"prompt": "...", "completion": "..."}. Refer to the platform documentation for exact field requirements.
    2. Clean data. Remove duplicates, garbled text, and content containing personal privacy, and ensure annotation consistency. Annotator disagreements should be reconciled before training.
    3. Split into training, validation, and test sets. The test set must be completely unseen during training, otherwise evaluation results will be overly optimistic.
    4. Set initial parameters. Start with small values for learning rate, number of epochs, and LoRA rank. Change only one variable at a time and record results.
    5. Evaluate. Use the test set to compute task metrics such as accuracy, F1, or format compliance rate, and also perform manual sampling.
    6. Compare against a baseline. The fine‑tuned model must outperform the base model without fine‑tuning and the prompting approach. If not, fine‑tuning has not delivered value.

    Training data does not need to be huge from the beginning. A few hundred high‑quality samples sometimes outperforms tens of thousands of noisy ones.

    Using RAG to Reduce Hallucinations and Integrate Business Data

    Retrieval‑augmented generation (RAG) works as follows: first retrieve relevant fragments from a knowledge base, then pass those fragments together with the question to the model to generate an answer. Knowledge can be updated at any time, and answers can include sources—these are its main benefits.

    When implementing, focus on the following areas.

    • Document chunking: overly large chunks introduce irrelevant content; overly small chunks lose context. A common approach is to split by section or paragraph and store headings as metadata.
    • Vector retrieval: the number of candidate fragments retrieved should match the model’s context window. Too many fragments increase token cost and may confuse the model.
    • Prompt constraints: require the model to answer only based on the provided material, and explicitly say it cannot answer when material is insufficient.
    • Evaluation: build a set of questions with ground truth, then measure retrieval hit rate and final answer accuracy separately. Only by looking at both can you tell whether the issue lies in retrieval or generation.

    The choice of vector database and object storage should depend on data size, query latency, and data residency requirements.

    API Integration Example

    After deployment, business systems typically call the model via an HTTP endpoint. The following example uses Python’s requests library and incorporates several key practices: reading endpoint and key from environment variables, setting a timeout, performing a limited number of exponential‑backoff retries for rate limits and server errors, and checking the response structure.

    1. import os
    2. import time
    3. import requests
    4. # Read configuration from environment variables; never hardcode keys or commit them to a repository
    5. API_BASE_URL = os.environ["LLM_API_BASE_URL"] # Use the address from the Qianfan console or official documentation
    6. API_KEY = os.environ["LLM_API_KEY"] # Use a dedicated key with the least privilege possible
    7. MODEL_NAME = os.environ.get("LLM_MODEL_NAME", "your-deployed-model")
    8. REQUEST_TIMEOUT = 30 # seconds
    9. MAX_RETRIES = 3
    10. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    11. class LLMCallError(Exception):
    12. """Raised when the model call fails; handles at a higher level as needed."""
    13. def chat_completion(prompt: str) -> str:
    14. url = f"{API_BASE_URL.rstrip('/')}/chat/completions"
    15. headers = {
    16. "Content-Type": "application/json",
    17. "Authorization": f"Bearer {API_KEY}",
    18. }
    19. payload = {
    20. "model": MODEL_NAME,
    21. "messages": [
    22. {"role": "system", "content": "You are a rigorous technical assistant."},
    23. {"role": "user", "content": prompt},
    24. ],
    25. "temperature": 0.7,
    26. "max_tokens": 1024,
    27. "stream": False,
    28. }
    29. last_error = None
    30. for attempt in range(1, MAX_RETRIES + 1):
    31. try:
    32. resp = requests.post(url, headers=headers, json=payload, timeout=REQUEST_TIMEOUT)
    33. except requests.RequestException as exc:
    34. last_error = f"Network exception: {exc}"
    35. else:
    36. if resp.status_code == 200:
    37. try:
    38. data = resp.json()
    39. return data["choices"][0]["message"]["content"]
    40. except (ValueError, KeyError, IndexError, TypeError) as exc:
    41. raise LLMCallError(f"Unexpected response structure: {exc}") from exc
    42. if resp.status_code not in RETRYABLE_STATUS:
    43. # 400, 401, 403 etc. usually indicate request or permission issues; retrying is pointless
    44. raise LLMCallError(f"HTTP {resp.status_code}: {resp.text[:200]}")
    45. # Retry only for retryable status codes or network errors
    46. if attempt < MAX_RETRIES:
    47. sleep_time = 2 ** (attempt - 1) # 1, 2, 4 seconds
    48. time.sleep(sleep_time)
    49. raise LLMCallError(f"Request failed after {MAX_RETRIES} attempts: {last_error}")

    The example demonstrates error handling, retry logic, and secure configuration. Adjust the endpoint, model name, and parameters according to the official application documentation for your specific deployment.