Evolving Chinese LLM Capabilities and Practical Token Cost Optimization
As Chinese large language models improve in reasoning, code generation, and tool use, developers must also manage rising token costs, agent reliability, and answer accuracy. This article presents practical engineering methods for evaluating reasoning performance, constraining AI agent workflows, reducing token usage, monitoring budgets, and controlling hallucinations with retrieval-augmented generation (RAG).
Introduction: What Happens to Cost and Reliability as Models Improve?
Over the past one to two years, Chinese large language models have made significant progress in complex reasoning, code generation, and tool use. Most public benchmarks show that leading models have improved their overall performance. For developers and enterprises, however, the more important questions are:
- Can operating costs remain under control as model capabilities improve?
- Can agent tasks complete reliably?
- Can generated content be verified?
This article examines these questions from a general engineering perspective and provides methods that can be applied directly. The figures mentioned below are illustrative only. Actual values should be determined through each team’s own testing.
1. Complex Reasoning: Improvements Need Data Support
Newer models commonly use more sophisticated Chain-of-Thought (CoT) training and reinforcement learning from human feedback (RLHF). These techniques can reduce mid-process deviations and logical breaks during multi-step reasoning. In engineering workflows, models can now participate in business process orchestration, database query planning, and system architecture evaluation, going beyond the code-completion use cases common in earlier systems.
However, longer reasoning chains also increase token consumption and response latency. When evaluating a model, teams should record at least three metrics:
- Task success rate
- Average token usage
- End-to-end latency
Looking only at accuracy can hide the fact that the cost of completing a task may have doubled.
Reasoning acceleration techniques also require careful validation. Common approaches include:
- Model quantization: INT8 quantization generally causes relatively small losses, while INT4 quantization may produce noticeable accuracy degradation on certain tasks. Before deployment, compare quantized and unquantized versions using business-specific samples.
- Weight pruning: The higher the pruning ratio, the greater the potential impact on long-tail tasks. These tasks should be validated separately.
- Speculative decoding: The acceleration effect depends on the draft model’s acceptance rate. If output patterns vary significantly across business requests, the actual speedup may be far lower than expected.
All of these techniques should be accompanied by regression testing. Whenever the model version or inference configuration changes, run the same test suite again.
2. Agentic Programming: Reliability Comes from Engineering Constraints
A typical agentic programming workflow includes understanding requirements, decomposing tasks, writing code, running tests, debugging, and fixing errors. Without clear boundaries, this loop can result in timeouts and infinite retries. Common causes include context-window overflow, unresponsive tools, and repeated attempts to resolve the same error.
Therefore, model capability alone is not enough. The orchestration layer must also enforce operational constraints. The following timeout and reliability checklist can serve as a baseline for pre-production reviews:
- Maximum step limit: Set an upper bound for each task. When the limit is reached, terminate the task and return the progress already made.
- Tool-call timeouts: Configure an independent timeout for each external tool so that one slow service does not block the entire workflow.
- Retries and backoff: Limit the number of retries and use exponential backoff to prevent temporary failures from becoming a cascading overload.
- Idempotent operations: Write operations, such as code submission and configuration changes, should produce the same result when executed repeatedly. Otherwise, retries may create duplicate side effects.
- Rollback mechanisms: Keep recoverable snapshots or versions for file and database changes.
- Observability: Record the input, output, duration, and token usage of every step to simplify failure analysis.
- Human handoff thresholds: Escalate to a human when failures reach a configured limit or when the workflow involves sensitive actions such as financial transactions or permission changes.
Some systems also allow models to identify interface elements and operate a computer directly. This capability can be useful for front-end testing and robotic process automation (RPA), but three issues require special attention.
First, operations should run inside an isolated sandbox to prevent mistakes from affecting production environments. Second, changes in screen resolution or interface design can cause coordinate offsets, so positioning rules or screenshot comparisons should be used for validation. Third, screenshots and operation logs should be retained for critical steps to support later audits.
3. Token Costs: Control the Budget at the Invocation Layer
Token usage mainly comes from four sources:
- Historical conversations
- Retrieved documents
- System prompts
- Model output
Many projects lose control of costs because conversation history continues to grow or entire retrieval results are inserted into prompts without filtering.
Common cost-reduction methods include:
- Context trimming: Keep only the most recent conversation turns and replace older content with a summary.
- Summary compression: Use a smaller model to summarize long text before passing the summary to the primary model.
- Caching: Return cached results for exactly identical requests. For semantically similar requests, vector similarity can be used to determine whether a cache entry is applicable.
- Output limits: Set a maximum output token count based on business requirements to prevent long, irrelevant responses.
- Tiered routing: Send simple questions to smaller models and route complex questions to larger models.
When measuring results, do not focus only on the cost of an individual API call. A more useful metric is the average cost per successfully completed task. Retries and failed calls must also be included; otherwise, actual spending will be underestimated.
Recommended metrics include:
- Input and output tokens per request
- Context compression ratio, calculated as compressed tokens divided by original tokens
- Cache hit rate
- Average cost per successful task
- Percentage of requests blocked for exceeding the budget
The following example uses only the Python standard library. It demonstrates budget checks and usage logging at the invocation layer. The client is a mock implementation; in production, replace it with the relevant provider SDK.
from dataclasses import dataclass@dataclassclass Usage:prompt_tokens: intcompletion_tokens: int@dataclassclass Response:text: strusage: Usageclass FakeLLMClient:"""Mock client. Replace generate with a provider SDK call in production."""def generate(self, prompt: str, max_tokens: int = 256) -> Response:answer = "Example response"return Response(text=answer,usage=Usage(prompt_tokens=len(prompt) // 2, completion_tokens=len(answer)),)class LLMProxy:def __init__(self, client, max_input_tokens=4000,price_per_1k_input=0.001, price_per_1k_output=0.002,history_turns=6):self.client = clientself.max_input_tokens = max_input_tokensself.price_in = price_per_1k_inputself.price_out = price_per_1k_outputself.history_turns = history_turnsself.logs = []@staticmethoddef estimate_tokens(text: str) -> int:# Rough estimate: approximately one token for every two Chinese characters.# Use the provider's tokenizer in production.return max(1, len(text) // 2)def compress_context(self, question: str, history: list) -> str:# Keep only the most recent conversation turns.recent = history[-self.history_turns:]return "\n".join(recent + [question])def invoke(self, question: str, history: list) -> str:prompt = self.compress_context(question, history)estimated = self.estimate_tokens(prompt)if estimated > self.max_input_tokens:raise ValueError(f"Estimated input: {estimated} tokens; "f"budget: {self.max_input_tokens}. Trim the context.")resp = self.client.generate(prompt)cost = (resp.usage.prompt_tokens / 1000 * self.price_in+ resp.usage.completion_tokens / 1000 * self.price_out)self.logs.append({"input_tokens": resp.usage.prompt_tokens,"output_tokens": resp.usage.completion_tokens,"cost": round(cost, 6),})return resp.textif __name__ == "__main__":proxy = LLMProxy(FakeLLMClient())print(proxy.invoke("What is RAG?",["User: Hello", "Assistant: Hello, how can I help you?"]))print(proxy.logs)
Save the code as llm_proxy.py and run:
python llm_proxy.py
The example requires Python 3.7 or later and has no external dependencies.
Expected output:
Example response[{'input_tokens': 15, 'output_tokens': 4, 'cost': 2.3e-05}]
This example is only a skeleton. A production implementation should also:
- Use the provider’s tokenizer for accurate token counts
- Add a caching layer
- Add timeouts and retries to model calls
- Send logs to a centralized monitoring system
4. Hallucination Control: Retrieval Augmentation and Continuous Evaluation
A hallucination occurs when a model generates content that appears reasonable but is inconsistent with facts. In professional domains, hallucinations are one of the main obstacles to production adoption. Retrieval-augmented generation (RAG) is one of the most widely used approaches for reducing this risk.
The basic RAG workflow is:
- Split internal enterprise documents into passages.
- Convert the passages into vectors and store them in a vector database.
- Retrieve the most relevant passages when a user submits a question.
- Insert the retrieved passages into the prompt.
The prompt will typically instruct the model to answer only according to the provided references and to explicitly state when the available information is insufficient.
RAG performance depends on multiple stages. Common failure modes include:
- Retrieval failure: The relevant document is not retrieved.
- Noisy chunking: Passages are split too aggressively, breaking the meaning of individual sentences.
- Conflicting context: Different documents provide contradictory information, but the model fails to recognize the conflict.
- Context neglect: The model does not use the retrieved content and instead relies on its internal parametric knowledge.
Recommended evaluation metrics include:
- Recall@K: The proportion of queries for which the correct passage appears among the top K retrieved results.
- Citation accuracy: Whether the cited sources genuinely support the model’s conclusions.
- Answer faithfulness: Whether each factual claim in the answer can be supported by the reference material.
- Correct refusal rate: Whether the model refuses to answer appropriately when the available information is insufficient instead of fabricating an answer.
For high-accuracy domains such as healthcare and finance, a knowledge graph can be added on top of RAG as a factual constraint layer. During generation, the system performs entity linking and relationship validation, then blocks or flags content that clearly conflicts with known facts.
This approach has relatively high construction and maintenance costs, so it is more suitable for domains with stable rules and high error penalties. Regardless of the approach used, high-risk outputs should retain a human review step.
5. Model Selection and Pre-Launch Review
General principles can be difficult to apply directly. The following checklist can be used during model selection and production-readiness reviews. Each team should define its own pass criteria according to business risk.
| Review item | Key metric | Description |
|---|---|---|
| Task success rate | Success ratio on a custom test set | Samples should come from real business scenarios. |
