How to Choose a Chinese LLM for Coding: Benchmark Speed, Cost, and Rate Limits

    A practical framework for evaluating Chinese large language models for software development. Learn how to build representative test cases, score quality, measure end-to-end and streaming speed, calculate token-based costs, account for caching, estimate rate-limit headroom, and select models using a repeatable decision process. The prices and limits shown are illustrative; always verify current values in the official pricing and API documentation.

    1. Define the Method Before Reviewing the Results

    A model that performs well on algorithm benchmarks may not perform equally well when completing business code in your project. Public leaderboards based on general-purpose evaluation sets are useful references, but they cannot replace testing with your own workloads.

    This article presents a reproducible evaluation process:

    1. Score models using representative internal samples.
    2. Measure speed with consistent definitions.
    3. Calculate cost using token-based formulas.
    4. Check available rate-limit headroom.
    5. Make a decision using a predefined evaluation table.

    The prices, quotas, and field names in this article are examples only. Use each provider’s current pricing page and API documentation for real values. Billing definitions also vary between providers.

    2. Test Samples and Scoring Criteria

    Prepare three to five prompts for each task category to reduce the impact of one-off results. At minimum, cover the following scenarios:

    • Function generation: Implement an HTTP retry decorator with exponential backoff.
    • Bug fixing: Provide code with a potential null-pointer issue and an error message, then ask the model to identify and fix the problem.
    • Format compliance: Require the model to output strict JSON containing the name and age fields.

    Score every sample from 1 to 5 in four areas:

    1. Executability: Can the code run directly or pass compilation?
    2. Correctness: Does it meet the requirements and handle edge cases?
    3. Format compliance: Does the response follow the required output format?
    4. Modification effort: How much manual editing is required before the result can be used?

    Use the average of the first three criteria as the quality score. Record modification effort separately as an efficiency indicator.

    If a particular task category matters more to your workflow, you can assign it a higher weight. However, determine the weights before testing and do not change them after seeing the results.

    Keep the following parameters fixed and store them with every result:

    • Model version
    • temperature
    • top_p
    • max_tokens
    • stream (set to false throughout this test)
    • System prompt
    • Input context length
    • Testing time window

    Results produced with different parameters should not be compared directly.

    When using real business code, anonymize it first. Remove API keys, internal domains, customer data, and non-public business logic. Third-party model providers receive the content you send to their APIs, so this step is essential.

    3. Defining Speed and Quality Metrics

    3.1 Measuring Speed

    With non-streaming requests, you can measure only end-to-end latency: the time from sending the request to receiving the complete response. This includes network round-trip time, queueing, and generation.

    The resulting metric should be called the end-to-end output rate:

    1. End-to-end output rate = output tokens ÷ end-to-end latency in seconds

    This metric is suitable for comparing models on the same network path, but it does not represent the model’s actual generation speed.

    To measure generation speed, use streaming output and record two timestamps:

    • Time to first token (TTFT)
    • Time when the final token arrives
    1. Generation speed = output tokens ÷ (final-token time − first-token time)

    TTFT reflects how long users wait before seeing a response. Generation speed reflects the output rhythm of a long response. Both metrics matter.

    3.2 Output Length as a Hidden Signal

    Given the same prompt, one model may complete the task with a short answer while another may produce a much longer response. A longer answer is not necessarily more detailed; it may simply be more verbose.

    When output tokens are billable, unnecessary verbosity directly increases cost. Evaluate whether the task was completed first, and examine output volume second.

    3.3 Speed and Task Type

    High-frequency, short requests—such as code completion and single-function generation—are especially sensitive to TTFT. Lightweight models often provide a better user experience for these tasks.

    Less frequent, resource-intensive tasks—such as refactoring an entire module or designing an architecture—can tolerate longer waits in exchange for stronger reasoning capabilities.

    Assign speed an appropriate weight based on the task types that account for the largest share of your workflow.

    4. Cost Formulas and Cache Fields

    4.1 A Unified Cost Model

    For many providers, the cost of a request can be divided into four components:

    1. Request cost = uncached input tokens × input price
    2. + cache creation tokens × cache creation price
    3. + cache hit tokens × cache hit price
    4. + output tokens × output price

    Total input tokens equal the sum of uncached input tokens, cache creation tokens, and cache hit tokens.

    Many providers return prompt_tokens as total input tokens. However, some providers return a value that excludes cached portions. Before integrating a provider, verify this behavior with one fixed request, then determine how to calculate uncached input tokens.

    Use consistent pricing units. Pricing tables commonly use currency per million tokens, so divide token counts by 1,000,000 during calculation. If a provider bills in credits, use the same unit for every candidate model.

    4.2 Cost Example

    The following prices are hypothetical and do not represent any provider’s actual pricing:

    • Uncached input: 2,000 tokens at 2 yuan per million tokens
    • Cache hits: 8,000 tokens at 0.2 yuan per million tokens
    • Cache creation: 0 tokens
    • Output: 1,500 tokens at 8 yuan per million tokens
    1. Request cost = (2,000 × 2 + 8,000 × 0.2 + 1,500 × 8) ÷ 1,000,000
    2. = 0.0176 yuan

    The price for cached input is much lower than the price for regular input, so repeated requests with long contexts can become significantly cheaper. Multiplying total input tokens by the standard input price would overestimate the cost of this request.

    4.3 Benchmark Script

    The following script fixes the key generation parameters, parses cache-related usage fields, and includes retry handling for rate limits and temporary server errors.

    Cache field names vary by provider. This example uses cache_creation_input_tokens and cache_read_input_tokens. Replace them with the field names specified in the relevant API documentation.

    1. import random
    2. import time
    3. import requests
    4. RETRY_STATUS = {429, 500, 502, 503, 504}
    5. def backoff(attempt, base=1.0, cap=30.0):
    6. # Exponential backoff with jitter prevents concurrent requests from retrying simultaneously.
    7. return min(cap, base * 2 ** attempt) * random.uniform(0.5, 1.0)
    8. def post_chat(api_base, api_key, payload, timeout=120, max_retries=3):
    9. url = f"{api_base}/chat/completions"
    10. headers = {"Authorization": f"Bearer {api_key}"}
    11. retries = 0
    12. for attempt in range(max_retries + 1):
    13. start = time.perf_counter()
    14. try:
    15. resp = requests.post(
    16. url,
    17. headers=headers,
    18. json=payload,
    19. timeout=timeout
    20. )
    21. except requests.RequestException as e:
    22. if attempt == max_retries:
    23. return {"error": f"request failed: {e}", "retries": retries}
    24. time.sleep(backoff(attempt))
    25. retries += 1
    26. continue
    27. elapsed = time.perf_counter() - start
    28. if resp.status_code == 200:
    29. return {
    30. "ok": resp.json(),
    31. "elapsed": elapsed,
    32. "retries": retries
    33. }
    34. if resp.status_code not in RETRY_STATUS or attempt == max_retries:
    35. return {
    36. "error": f"HTTP {resp.status_code}",
    37. "retries": retries
    38. }
    39. # If Retry-After is expressed in seconds, use it.
    40. # For HTTP-date values, fall back to exponential backoff.
    41. try:
    42. wait = min(float(resp.headers.get("Retry-After")), 60.0)
    43. except (TypeError, ValueError):
    44. wait = backoff(attempt)
    45. time.sleep(wait)
    46. retries += 1
    47. return {"error": "unreachable", "retries": retries}
    48. def parse_usage(body, prices):
    49. # prices are expressed as currency units per million tokens
    50. usage = body.get("usage") or {}
    51. total_in = usage.get("prompt_tokens", 0)
    52. out_tok = usage.get("completion_tokens", 0)
    53. cache_write = usage.get("cache_creation_input_tokens", 0)
    54. cache_hit = usage.get("cache_read_input_tokens", 0)
    55. uncached = max(total_in - cache_write - cache_hit, 0)
    56. cost = (
    57. uncached * prices["in"]
    58. + cache_write * prices["cache_write"]
    59. + cache_hit * prices["cache_hit"]
    60. + out_tok * prices["out"]
    61. ) / 1_000_000
    62. return {
    63. "uncached": uncached,
    64. "cache_write": cache_write,
    65. "cache_hit": cache_hit,
    66. "output": out_tok,
    67. "cost_yuan": round(cost, 6),
    68. }
    69. def run_case(
    70. model,
    71. prompt,
    72. api_base,
    73. api_key,
    74. prices,
    75. system="You are a senior Python engineer.",
    76. max_tokens=1024,
    77. temperature=0.0,
    78. top_p=1.0,
    79. ):
    80. payload = {
    81. "model": model,
    82. "messages": [
    83. {"role": "system", "content": system},
    84. {"role": "user", "content": prompt},
    85. ],
    86. "max_tokens": max_tokens,
    87. "temperature": temperature,
    88. "top_p": top_p,
    89. "stream": False,
    90. }
    91. res = post_chat(api_base, api_key, payload)
    92. if "error" in res:
    93. return {"model": model, **res}
    94. usage = parse_usage(res["ok"], prices)
    95. tps = usage["output"] / res["elapsed"] if res["elapsed"] > 0 else 0.0
    96. return {
    97. "model": model,
    98. "latency_ms": round(res["elapsed"] * 1000, 1),
    99. "end_to_end_tps": round(tps, 1),
    100. "retries": res["retries"],
    101. **usage,
    102. }

    The script reports end-to-end output rate. To measure generation speed, switch to streaming output and record the time to the first token and the time to the final token.

    5. Rate Limits and Retries

    5.1 Common Rate-Limit Dimensions

    Common rate limits include:

    • RPM: Requests per minute
    • TPM: Tokens per minute; the counting method may include input tokens, output tokens, or both
    • QPS: Queries per second
    • Concurrency limit: The maximum number of requests that can run at the same time

    For workloads with many short requests, RPM usually becomes the bottleneck first. For workloads with long contexts, TPM is more likely to be the limiting factor.

    5.2 Estimating Peak Usage and Headroom

    1. Rate-limit headroom = quota − peak usage

    To estimate peak TPM, multiply the average total tokens per request by the peak requests per minute.

    For example, if each request uses an average of 6,000 input tokens and 1,000 output tokens, with a peak of 10 requests per minute:

    1. Peak TPM = (6,000 + 1,000) × 10
    2. = 70,000 TPM

    If the provider’s limit is 100,000 TPM:

    1. Headroom = 100,000 − 70,000
    2. = 30,000 TPM

    The headroom is approximately 43% of peak usage. This is relatively tight. Unless occasional queueing is acceptable, the model should not be used as the only primary model.

    5.3 Handling 429 and Retry-After

    A 429 response indicates that the request was rate-limited. Handle it as follows:

    1. If the response includes Retry-After, wait for the specified duration. The example script parses the seconds-based form.
    2. If Retry-After is absent, use exponential backoff with random jitter and set a maximum wait time.
    3. Set a retry budget. For example, retry an individual task no more than three times. If daily retries exceed a threshold, raise an alert and reduce concurrency.

    Status codes 400, 401, and 403 generally indicate a problem with the request itself. Retrying will not help; record the error and investigate it directly.

    Statuses from 500 through 504 can generally be retried using the same approach.

    5.4 Controlling Concurrency

    Do not set concurrency to the maximum immediately. Start with one concurrent request and run all test samples successfully. Then increase concurrency gradually toward approximately half of the provider’s limit while monitoring the frequency of 429 responses.

    When occasional 429 responses appear, reducing concurrency is usually more effective than increasing the number of retries.

    6. A Decision Path for Model Selection

    The quality score is the average of executability, correctness, and format compliance.

    Cost is the per-request cost calculated using the formula in Section 4, multiplied by the expected number of calls per day or per month.

    Condition Decision Recommended action
    Quality score is at least 4, cost is within budget, and rate-limit headroom is at least twice peak usage Scale up Make the model the primary choice for daily workflows
    Quality score is at least 4, but the model is slow or headroom is less than twice peak usage Make targeted changes Use a lightweight model for frequent short tasks, reduce concurrency, and split long tasks
    Quality score is between 3 and 3.9, with clear weaknesses in format compliance or correctness Make targeted changes Tighten the system prompt and output constraints, then test again
    Quality score is below 3, or any sample fails the executability test Eliminate Remove the model from the candidate set
    Per-request cost exceeds the budget without a clear quality advantage Eliminate Do not include the model in the candidate set

    The recommended evaluation order is:

    1. Check quality score.
    2. Check rate-limit headroom.
    3. Check cost.
    4. Apply task-specific weighting to speed.

    A model that fails to meet the quality requirement should not remain a candidate simply because it is fast or inexpensive.

    7. Final Checks Before Use

    Prices, quotas, and caching rules can change frequently. Before each model-selection exercise, review the provider’s current pricing table and API documentation.

    Also use one fixed request to verify how prompt_tokens is defined. All final calculations should follow the provider’s official documentation.