JunHowie commited on
Commit
0cc8bc7
·
verified ·
1 Parent(s): bf07921

Add files using upload-large-folder tool

Browse files
README.md ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: apache-2.0
4
+ license_link: https://huggingface.co/Qwen/Qwen3-Coder-Next/blob/main/LICENSE
5
+ pipeline_tag: text-generation
6
+ tags:
7
+ - vLLM
8
+ - sglang
9
+ base_model:
10
+ - Qwen/Qwen3-Coder-Next
11
+ base_model_relation: quantized
12
+ ---
13
+ # Qwen3-Coder-Next-E336
14
+ Base model: [Qwen/Qwen3-Coder-Next](https://www.modelscope.cn/models/Qwen/Qwen3-Coder-Next)
15
+
16
+ This repo trims 34% of the experts (512 → 336);
17
+
18
+ The model format and serving setup (vLLM/SGLang versions and launch commands) match the original release.
19
+
20
+ ### 【Logs】
21
+ ```
22
+ 2026-02-05
23
+ 1. Initial commit
24
+ ```
25
+
26
+ ### 【Model Files】
27
+ | File Size | Last Updated |
28
+ |-----------|--------------|
29
+ | `99 GiB` | `2026-02-05` |
30
+
31
+ ### 【Model Download】
32
+ ```python
33
+ from modelscope import snapshot_download
34
+ snapshot_download('tclf90/Qwen3-Coder-Next-E336', cache_dir="your_local_path")
35
+ ```
36
+
37
+ ### 【Overview】
38
+ # Qwen3-Coder-Next
39
+
40
+ ## Highlights
41
+
42
+ Today, we're announcing **Qwen3-Coder-Next**, an open-weight language model designed specifically for coding agents and local development. It features the following key enhancements:
43
+
44
+ - **Super Efficient with Significant Performance**: With only 3B activated parameters (80B total parameters), it achieves performance comparable to models with 10–20x more active parameters, making it highly cost-effective for agent deployment.
45
+ - **Advanced Agentic Capabilities**: Through an elaborate training recipe, it excels at long-horizon reasoning, complex tool usage, and recovery from execution failures, ensuring robust performance in dynamic coding tasks.
46
+ - **Versatile Integration with Real-World IDE**: Its 256k context length, combined with adaptability to various scaffold templates, enables seamless integration with different CLI/IDE platforms (e.g., Claude Code, Qwen Code, Qoder, Kilo, Trae, Cline, etc.), supporting diverse development environments.
47
+
48
+ ![image/jpeg](https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen3-Coder-Next/benchmarks.png)
49
+
50
+ ![image/jpeg](https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen3-Coder-Next/swebench_pro.png)
51
+
52
+ ## Model Overview
53
+
54
+ **Qwen3-Coder-Next** has the following features:
55
+ - Type: Causal Language Models
56
+ - Training Stage: Pretraining & Post-training
57
+ - Number of Parameters: 80B in total and 3B activated
58
+ - Number of Parameters (Non-Embedding): 79B
59
+ - Hidden Dimension: 2048
60
+ - Number of Layers: 48
61
+ - Hybrid Layout: 12 \* (3 \* (Gated DeltaNet -> MoE) -> 1 \* (Gated Attention -> MoE))
62
+ - Gated Attention:
63
+ - Number of Attention Heads: 16 for Q and 2 for KV
64
+ - Head Dimension: 256
65
+ - Rotary Position Embedding Dimension: 64
66
+ - Gated DeltaNet:
67
+ - Number of Linear Attention Heads: 32 for V and 16 for QK
68
+ - Head Dimension: 128
69
+ - Mixture of Experts:
70
+ - Number of Experts: 512
71
+ - Number of Activated Experts: 10
72
+ - Number of Shared Experts: 1
73
+ - Expert Intermediate Dimension: 512
74
+ - Context Length: 262,144 natively
75
+
76
+ **NOTE: This model supports only non-thinking mode and does not generate ``<think></think>`` blocks in its output. Meanwhile, specifying `enable_thinking=False` is no longer required.**
77
+
78
+ For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwen.ai/blog?id=qwen3-coder-next), [GitHub](https://github.com/QwenLM/Qwen3-Coder), and [Documentation](https://qwen.readthedocs.io/en/latest/).
79
+
80
+
81
+ ## Quickstart
82
+
83
+ We advise you to use the latest version of `transformers`.
84
+
85
+ The following contains a code snippet illustrating how to use the model generate content based on given inputs.
86
+ ```python
87
+ from transformers import AutoModelForCausalLM, AutoTokenizer
88
+
89
+ model_name = "Qwen/Qwen3-Coder-Next"
90
+
91
+ # load the tokenizer and the model
92
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
93
+ model = AutoModelForCausalLM.from_pretrained(
94
+ model_name,
95
+ torch_dtype="auto",
96
+ device_map="auto"
97
+ )
98
+
99
+ # prepare the model input
100
+ prompt = "Write a quick sort algorithm."
101
+ messages = [
102
+ {"role": "user", "content": prompt}
103
+ ]
104
+ text = tokenizer.apply_chat_template(
105
+ messages,
106
+ tokenize=False,
107
+ add_generation_prompt=True,
108
+ )
109
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
110
+
111
+ # conduct text completion
112
+ generated_ids = model.generate(
113
+ **model_inputs,
114
+ max_new_tokens=65536
115
+ )
116
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
117
+
118
+ content = tokenizer.decode(output_ids, skip_special_tokens=True)
119
+
120
+ print("content:", content)
121
+ ```
122
+
123
+ **Note: If you encounter out-of-memory (OOM) issues, consider reducing the context length to a shorter value, such as `32,768`.**
124
+
125
+ For local use, applications such as Ollama, LMStudio, MLX-LM, llama.cpp, and KTransformers have also supported Qwen3.
126
+
127
+ ## Deployment
128
+
129
+ For deployment, you can use the latest `sglang` or `vllm` to create an OpenAI-compatible API endpoint.
130
+
131
+ ### SGLang
132
+
133
+ [SGLang](https://github.com/sgl-project/sglang) is a fast serving framework for large language models and vision language models.
134
+ SGLang could be used to launch a server with OpenAI-compatible API service.
135
+
136
+ `sglang>=v0.5.8` is required for Qwen3-Coder-Next, which can be installed using:
137
+ ```shell
138
+ pip install 'sglang[all]>=v0.5.8'
139
+ ```
140
+ See [its documentation](https://docs.sglang.ai/get_started/install.html) for more details.
141
+
142
+ The following command can be used to create an API endpoint at `http://localhost:30000/v1` with maximum context length 256K tokens using tensor parallel on 4 GPUs.
143
+ ```shell
144
+ python -m sglang.launch_server --model Qwen/Qwen3-Coder-Next --port 30000 --tp-size 2 --tool-call-parser qwen3_coder
145
+ ```
146
+
147
+ > [!Note]
148
+ > The default context length is 256K. Consider reducing the context length to a smaller value, e.g., `32768`, if the server fails to start.
149
+
150
+
151
+ ### vLLM
152
+
153
+ [vLLM](https://github.com/vllm-project/vllm) is a high-throughput and memory-efficient inference and serving engine for LLMs.
154
+ vLLM could be used to launch a server with OpenAI-compatible API service.
155
+
156
+ `vllm>=0.15.0` is required for Qwen3-Coder-Next, which can be installed using:
157
+ ```shell
158
+ pip install 'vllm>=0.15.0'
159
+ ```
160
+ See [its documentation](https://docs.vllm.ai/en/stable/getting_started/installation/index.html) for more details.
161
+
162
+ The following command can be used to create an API endpoint at `http://localhost:8000/v1` with maximum context length 256K tokens using tensor parallel on 4 GPUs.
163
+ ```shell
164
+ vllm serve Qwen/Qwen3-Coder-Next --port 8000 --tensor-parallel-size 2 --enable-auto-tool-choice --tool-call-parser qwen3_coder
165
+ ```
166
+
167
+ > [!Note]
168
+ > The default context length is 256K. Consider reducing the context length to a smaller value, e.g., `32768`, if the server fails to start.
169
+
170
+
171
+ ## Agentic Coding
172
+
173
+ Qwen3-Coder-Next excels in tool calling capabilities.
174
+
175
+ You can simply define or use any tools as following example.
176
+ ```python
177
+ # Your tool implementation
178
+ def square_the_number(num: float) -> dict:
179
+ return num ** 2
180
+
181
+ # Define Tools
182
+ tools=[
183
+ {
184
+ "type":"function",
185
+ "function":{
186
+ "name": "square_the_number",
187
+ "description": "output the square of the number.",
188
+ "parameters": {
189
+ "type": "object",
190
+ "required": ["input_num"],
191
+ "properties": {
192
+ 'input_num': {
193
+ 'type': 'number',
194
+ 'description': 'input_num is a number that will be squared'
195
+ }
196
+ },
197
+ }
198
+ }
199
+ }
200
+ ]
201
+
202
+ from openai import OpenAI
203
+ # Define LLM
204
+ client = OpenAI(
205
+ # Use a custom endpoint compatible with OpenAI API
206
+ base_url='http://localhost:8000/v1', # api_base
207
+ api_key="EMPTY"
208
+ )
209
+
210
+ messages = [{'role': 'user', 'content': 'square the number 1024'}]
211
+
212
+ completion = client.chat.completions.create(
213
+ messages=messages,
214
+ model="Qwen3-Coder-Next",
215
+ max_tokens=65536,
216
+ tools=tools,
217
+ )
218
+
219
+ print(completion.choices[0])
220
+ ```
221
+
222
+ ## Best Practices
223
+
224
+ To achieve optimal performance, we recommend the following sampling parameters: `temperature=1.0`, `top_p=0.95`, `top_k=40`.
225
+
226
+
227
+ ## Citation
228
+
229
+ If you find our work helpful, feel free to give us a cite.
230
+
231
+ ```
232
+ @techreport{qwen_qwen3_coder_next_tech_report,
233
+ title = {Qwen3-Coder-Next Technical Report},
234
+ author = {{Qwen Team}},
235
+ url = {https://github.com/QwenLM/Qwen3-Coder/blob/main/qwen3_coder_next_tech_report.pdf},
236
+ note = {Accessed: 2026-02-03}
237
+ }
238
+ ```
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"Pytorch","task":"text-generation"}
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 1.0,
10
+ "top_k": 40,
11
+ "top_p": 0.95,
12
+ "transformers_version": "4.57.3"
13
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00022-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbb5a850149bdb1e22421ddca3aaf7b521df8d7fe5118bc068d60e94a563daf3
3
+ size 2998993464
model-00035-of-00036.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ec2c6e3455ab2506a14430721a04b156919a1d7bb2c9514483608ef1aebb0af
3
+ size 2973172496
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
qwen3_coder_detector_sgl.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import json
3
+ import logging
4
+ import re
5
+ from typing import Any, List, Optional
6
+
7
+ from sglang.srt.entrypoints.openai.protocol import Tool
8
+ from sglang.srt.function_call.base_format_detector import BaseFormatDetector
9
+ from sglang.srt.function_call.core_types import (
10
+ StreamingParseResult,
11
+ ToolCallItem,
12
+ _GetInfoFunc,
13
+ )
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class Qwen3CoderDetector(BaseFormatDetector):
19
+ def __init__(self):
20
+ super().__init__()
21
+
22
+ # Sentinel tokens
23
+ self.tool_call_start_token: str = "<tool_call>"
24
+ self.tool_call_end_token: str = "</tool_call>"
25
+ self.tool_call_prefix: str = "<function="
26
+ self.function_end_token: str = "</function>"
27
+ self.parameter_prefix: str = "<parameter="
28
+ self.parameter_end_token: str = "</parameter>"
29
+
30
+ # Regex for non-streaming fallback
31
+ self.tool_call_regex = re.compile(r"<tool_call>(.*?)</tool_call>", re.DOTALL)
32
+ self.tool_call_function_regex = re.compile(
33
+ r"<function=(.*?)</function>|<function=(.*)$", re.DOTALL
34
+ )
35
+ self.tool_call_parameter_regex = re.compile(
36
+ r"<parameter=(.*?)(?:</parameter>|(?=<parameter=)|(?=</function>)|$)",
37
+ re.DOTALL,
38
+ )
39
+
40
+ # Streaming State
41
+ # Base class already initializes _buffer, we just use it directly
42
+ # No need to check with hasattr - we control the lifecycle through inheritance
43
+
44
+ # Index pointing to the next character to be processed in buffer
45
+ self.parsed_pos: int = 0
46
+ # Parameter count inside the current tool being processed, used to determine whether to add comma
47
+ self.current_tool_param_count: int = 0
48
+ # Flag indicating whether current tool has already sent '{'
49
+ self.json_started: bool = False
50
+
51
+ # [FIX] New state flag: mark whether inside tool_call structure block
52
+ self.is_inside_tool_call: bool = False
53
+
54
+ # Initialize attributes that were missing in the original PR
55
+ self.current_func_name: Optional[str] = None
56
+
57
+ def has_tool_call(self, text: str) -> bool:
58
+ return self.tool_call_start_token in text
59
+
60
+ def _get_arguments_config(
61
+ self, func_name: str, tools: Optional[list[Tool]]
62
+ ) -> dict:
63
+ """Extract argument configuration for a function."""
64
+ if tools is None:
65
+ return {}
66
+ for config in tools:
67
+ try:
68
+ config_type = config.type
69
+ config_function = config.function
70
+ config_function_name = config_function.name
71
+ except AttributeError:
72
+ continue
73
+
74
+ if config_type == "function" and config_function_name == func_name:
75
+ try:
76
+ params = config_function.parameters
77
+ except AttributeError:
78
+ return {}
79
+
80
+ if isinstance(params, dict) and "properties" in params:
81
+ return params["properties"]
82
+ elif isinstance(params, dict):
83
+ return params
84
+ else:
85
+ return {}
86
+ logger.warning(f"Tool '{func_name}' is not defined in the tools list.")
87
+ return {}
88
+
89
+ def _convert_param_value(
90
+ self, param_value: str, param_name: str, param_config: dict, func_name: str
91
+ ) -> Any:
92
+ """Convert parameter value based on its type in the schema."""
93
+ # Handle null value for any type
94
+ if param_value.lower() == "null":
95
+ return None
96
+
97
+ if param_name not in param_config:
98
+ if param_config != {}:
99
+ logger.warning(
100
+ f"Parsed parameter '{param_name}' is not defined in the tool "
101
+ f"parameters for tool '{func_name}', directly returning the string value."
102
+ )
103
+ return param_value
104
+
105
+ if (
106
+ isinstance(param_config[param_name], dict)
107
+ and "type" in param_config[param_name]
108
+ ):
109
+ param_type = str(param_config[param_name]["type"]).strip().lower()
110
+ else:
111
+ param_type = "string"
112
+ if param_type in ["string", "str", "text", "varchar", "char", "enum"]:
113
+ return param_value
114
+ elif (
115
+ param_type.startswith("int")
116
+ or param_type.startswith("uint")
117
+ or param_type.startswith("long")
118
+ or param_type.startswith("short")
119
+ or param_type.startswith("unsigned")
120
+ ):
121
+ try:
122
+ param_value = int(param_value)
123
+ except Exception:
124
+ logger.warning(
125
+ f"Parsed value '{param_value}' of parameter '{param_name}' is not an integer in tool "
126
+ f"'{func_name}', degenerating to string."
127
+ )
128
+ return param_value
129
+ elif param_type.startswith("num") or param_type.startswith("float"):
130
+ try:
131
+ maybe_convert = (
132
+ False if "." in param_value or "e" in param_value.lower() else True
133
+ )
134
+ param_value: float = float(param_value)
135
+ if maybe_convert and param_value.is_integer():
136
+ param_value = int(param_value)
137
+ except Exception:
138
+ logger.warning(
139
+ f"Parsed value '{param_value}' of parameter '{param_name}' is not a float in tool "
140
+ f"'{func_name}', degenerating to string."
141
+ )
142
+ return param_value
143
+ elif param_type in ["boolean", "bool", "binary"]:
144
+ param_value = param_value.lower()
145
+ if param_value not in ["true", "false"]:
146
+ logger.warning(
147
+ f"Parsed value '{param_value}' of parameter '{param_name}' is not a boolean (`true` of `false`) in tool '{func_name}', degenerating to false."
148
+ )
149
+ return param_value == "true"
150
+ else:
151
+ if (
152
+ param_type in ["object", "array", "arr"]
153
+ or param_type.startswith("dict")
154
+ or param_type.startswith("list")
155
+ ):
156
+ try:
157
+ param_value = json.loads(param_value)
158
+ return param_value
159
+ except Exception:
160
+ logger.warning(
161
+ f"Parsed value '{param_value}' of parameter '{param_name}' cannot be parsed with json.loads in tool "
162
+ f"'{func_name}', will try other methods to parse it."
163
+ )
164
+ try:
165
+ param_value = ast.literal_eval(param_value) # safer
166
+ except Exception:
167
+ logger.warning(
168
+ f"Parsed value '{param_value}' of parameter '{param_name}' cannot be converted via Python `ast.literal_eval()` in tool '{func_name}', degenerating to string."
169
+ )
170
+ return param_value
171
+
172
+ def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult:
173
+ """One-shot parsing for non-streaming scenarios."""
174
+ if self.tool_call_start_token not in text:
175
+ return StreamingParseResult(normal_text=text)
176
+
177
+ calls = []
178
+ try:
179
+ # Simple cleanup of the text to find tool calls
180
+ # Note: This is a simplified regex approach consistent with vLLM
181
+ raw_tool_calls = self.tool_call_regex.findall(text)
182
+ if not raw_tool_calls:
183
+ # Fallback: maybe the whole text is inside the tag or tags are stripped
184
+ if self.tool_call_prefix in text:
185
+ raw_tool_calls = [text]
186
+
187
+ tool_idx = 0
188
+ for tool_content in raw_tool_calls:
189
+ # Find function calls
190
+ funcs = self.tool_call_function_regex.findall(tool_content)
191
+ for func_match in funcs:
192
+ func_body = func_match[0] or func_match[1]
193
+ if ">" not in func_body:
194
+ continue
195
+
196
+ name_end = func_body.index(">")
197
+ func_name = func_body[:name_end]
198
+ params_str = func_body[name_end + 1 :]
199
+
200
+ param_config = self._get_arguments_config(func_name, tools)
201
+ parsed_params = {}
202
+
203
+ for p_match in self.tool_call_parameter_regex.findall(params_str):
204
+ if ">" not in p_match:
205
+ continue
206
+ p_idx = p_match.index(">")
207
+ p_name = p_match[:p_idx]
208
+ p_val = p_match[p_idx + 1 :]
209
+ # Remove prefixing and trailing \n
210
+ if p_val.startswith("\n"):
211
+ p_val = p_val[1:]
212
+ if p_val.endswith("\n"):
213
+ p_val = p_val[:-1]
214
+
215
+ parsed_params[p_name] = self._convert_param_value(
216
+ p_val, p_name, param_config, func_name
217
+ )
218
+
219
+ calls.append(
220
+ ToolCallItem(
221
+ tool_index=tool_idx,
222
+ name=func_name,
223
+ parameters=json.dumps(parsed_params, ensure_ascii=False),
224
+ )
225
+ )
226
+ tool_idx += 1
227
+
228
+ # Determine normal text (text before the first tool call)
229
+ start_idx = text.find(self.tool_call_start_token)
230
+ if start_idx == -1:
231
+ start_idx = text.find(self.tool_call_prefix)
232
+ normal_text = text[:start_idx] if start_idx > 0 else ""
233
+
234
+ return StreamingParseResult(normal_text=normal_text, calls=calls)
235
+
236
+ except Exception as e:
237
+ logger.error(f"Error in detect_and_parse: {e}")
238
+ return StreamingParseResult(normal_text=text)
239
+
240
+ def parse_streaming_increment(
241
+ self, new_text: str, tools: List[Tool]
242
+ ) -> StreamingParseResult:
243
+ """
244
+ Robust cursor-based streaming parser.
245
+ """
246
+ self._buffer += new_text
247
+
248
+ # Guard against empty buffer
249
+ if not self._buffer:
250
+ return StreamingParseResult()
251
+
252
+ calls = []
253
+ normal_text_chunks = []
254
+
255
+ while True:
256
+ # Working text slice
257
+ current_slice = self._buffer[self.parsed_pos :]
258
+
259
+ # Optimization: If almost empty, wait for more
260
+ if not current_slice:
261
+ break
262
+
263
+ # -------------------------------------------------------
264
+ # 1. Priority detection: check if it's the start of Tool Call
265
+ # -------------------------------------------------------
266
+ if current_slice.startswith(self.tool_call_start_token):
267
+ self.parsed_pos += len(self.tool_call_start_token)
268
+ self.is_inside_tool_call = True
269
+ continue
270
+
271
+ # -------------------------------------------------------
272
+ # 2. Function Name: <function=name>
273
+ # -------------------------------------------------------
274
+ if current_slice.startswith(self.tool_call_prefix):
275
+ end_angle = current_slice.find(">")
276
+ if end_angle != -1:
277
+ func_name = current_slice[len(self.tool_call_prefix) : end_angle]
278
+
279
+ self.current_tool_id += 1
280
+ self.current_tool_name_sent = True
281
+ self.current_tool_param_count = 0
282
+ self.json_started = False
283
+ self.current_func_name = func_name
284
+
285
+ calls.append(
286
+ ToolCallItem(
287
+ tool_index=self.current_tool_id,
288
+ name=func_name,
289
+ parameters="",
290
+ )
291
+ )
292
+
293
+ self.parsed_pos += end_angle + 1
294
+ continue
295
+ else:
296
+ # Incomplete tag
297
+ break
298
+
299
+ # -------------------------------------------------------
300
+ # 3. Parameter: <parameter=name>value...
301
+ # -------------------------------------------------------
302
+ if current_slice.startswith(self.parameter_prefix):
303
+ name_end = current_slice.find(">")
304
+ if name_end != -1:
305
+ value_start_idx = name_end + 1
306
+ rest_of_slice = current_slice[value_start_idx:]
307
+
308
+ # A parameter can end in multiple ways:
309
+ # 1. [Normal] Encounter </parameter>
310
+ # 2. [Abnormal] Encounter next <parameter=
311
+ # 3. [Abnormal] Encounter </function>
312
+ # So we need to find the smallest one as the parameter end position.
313
+ cand_end_param = rest_of_slice.find(self.parameter_end_token)
314
+ cand_next_param = rest_of_slice.find(self.parameter_prefix)
315
+ cand_end_func = rest_of_slice.find(self.function_end_token)
316
+
317
+ candidates = []
318
+ if cand_end_param != -1:
319
+ candidates.append(
320
+ (cand_end_param, len(self.parameter_end_token))
321
+ )
322
+ if cand_next_param != -1:
323
+ candidates.append((cand_next_param, 0))
324
+ if cand_end_func != -1:
325
+ candidates.append((cand_end_func, 0))
326
+
327
+ if candidates:
328
+ best_cand = min(candidates, key=lambda x: x[0])
329
+ end_pos = best_cand[0]
330
+ end_token_len = best_cand[1]
331
+
332
+ param_name = current_slice[
333
+ len(self.parameter_prefix) : name_end
334
+ ]
335
+ raw_value = rest_of_slice[:end_pos]
336
+
337
+ # Cleanup value
338
+ if raw_value.startswith("\n"):
339
+ raw_value = raw_value[1:]
340
+ if raw_value.endswith("\n"):
341
+ raw_value = raw_value[:-1]
342
+
343
+ # JSON Construction
344
+ if not self.json_started:
345
+ calls.append(
346
+ ToolCallItem(
347
+ tool_index=self.current_tool_id, parameters="{"
348
+ )
349
+ )
350
+ self.json_started = True
351
+
352
+ param_config = self._get_arguments_config(
353
+ self.current_func_name, tools
354
+ )
355
+ converted_val = self._convert_param_value(
356
+ raw_value, param_name, param_config, self.current_func_name
357
+ )
358
+
359
+ # Construct JSON fragment: "key": value
360
+ # Note: We must be careful with json.dumps to ensure valid JSON streaming
361
+ json_key_val = f"{json.dumps(param_name)}: {json.dumps(converted_val, ensure_ascii=False)}"
362
+
363
+ if self.current_tool_param_count > 0:
364
+ fragment = f", {json_key_val}"
365
+ else:
366
+ fragment = json_key_val
367
+
368
+ calls.append(
369
+ ToolCallItem(
370
+ tool_index=self.current_tool_id, parameters=fragment
371
+ )
372
+ )
373
+ self.current_tool_param_count += 1
374
+
375
+ # Advance cursor
376
+ total_len = (name_end + 1) + end_pos + end_token_len
377
+ self.parsed_pos += total_len
378
+ continue
379
+
380
+ # Incomplete parameter tag or value
381
+ break
382
+
383
+ # -------------------------------------------------------
384
+ # 4. Function End: </function>
385
+ # -------------------------------------------------------
386
+ if current_slice.startswith(self.function_end_token):
387
+ if not self.json_started:
388
+ calls.append(
389
+ ToolCallItem(tool_index=self.current_tool_id, parameters="{")
390
+ )
391
+ self.json_started = True
392
+
393
+ calls.append(
394
+ ToolCallItem(tool_index=self.current_tool_id, parameters="}")
395
+ )
396
+ self.parsed_pos += len(self.function_end_token)
397
+ self.current_func_name = None
398
+ continue
399
+
400
+ # -------------------------------------------------------
401
+ # 5. Tool Call End: </tool_call>
402
+ # -------------------------------------------------------
403
+ if current_slice.startswith(self.tool_call_end_token):
404
+ self.parsed_pos += len(self.tool_call_end_token)
405
+ self.is_inside_tool_call = False # [FIX] Exit tool call region
406
+ continue
407
+
408
+ # -------------------------------------------------------
409
+ # 6. Handling content / whitespace / normal text
410
+ # -------------------------------------------------------
411
+ # If current position is not the start of a tag (i.e., doesn't start with <), it might be plain text,
412
+ # or a newline between two tags.
413
+ # But we need to be careful not to output truncated tags like "<fun" as text.
414
+
415
+ next_open_angle = current_slice.find("<")
416
+
417
+ if next_open_angle == -1:
418
+ # This entire segment is plain text
419
+ if not self.is_inside_tool_call:
420
+ normal_text_chunks.append(current_slice)
421
+ # [FIX] If inside tool call, discard this text (usually \n), don't append
422
+ self.parsed_pos += len(current_slice)
423
+ continue
424
+
425
+ elif next_open_angle == 0:
426
+ # Looks like a Tag, but doesn't match any known Tag above
427
+
428
+ possible_tags = [
429
+ self.tool_call_start_token,
430
+ self.tool_call_end_token,
431
+ self.tool_call_prefix,
432
+ self.function_end_token,
433
+ self.parameter_prefix,
434
+ self.parameter_end_token,
435
+ ]
436
+
437
+ is_potential_tag = False
438
+ for tag in possible_tags:
439
+ if tag.startswith(current_slice):
440
+ is_potential_tag = True
441
+ break
442
+
443
+ if is_potential_tag:
444
+ break # Wait for more
445
+ else:
446
+ # Just a plain '<' symbol
447
+ if not self.is_inside_tool_call:
448
+ normal_text_chunks.append("<")
449
+ self.parsed_pos += 1
450
+ continue
451
+
452
+ else:
453
+ # '<' is in the middle
454
+ text_segment = current_slice[:next_open_angle]
455
+ if not self.is_inside_tool_call:
456
+ normal_text_chunks.append(text_segment)
457
+ # [FIX] If inside tool call, discard whitespace/text before Tag
458
+ self.parsed_pos += next_open_angle
459
+ continue
460
+
461
+ # Memory Cleanup: Slice the buffer
462
+ # Keep unparsed part, discard parsed part
463
+ if self.parsed_pos > 0:
464
+ self._buffer = self._buffer[self.parsed_pos :]
465
+ self.parsed_pos = 0
466
+
467
+ normal_text = "".join(normal_text_chunks) if normal_text_chunks else ""
468
+ return StreamingParseResult(calls=calls, normal_text=normal_text)
469
+
470
+ def supports_structural_tag(self) -> bool:
471
+ return False
472
+
473
+ def structure_info(self) -> _GetInfoFunc:
474
+ raise NotImplementedError
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151646": {
29
+ "content": "<|object_ref_start|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "151647": {
37
+ "content": "<|object_ref_end|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "151648": {
45
+ "content": "<|box_start|>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "151649": {
53
+ "content": "<|box_end|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "151650": {
61
+ "content": "<|quad_start|>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "151651": {
69
+ "content": "<|quad_end|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "151652": {
77
+ "content": "<|vision_start|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "151653": {
85
+ "content": "<|vision_end|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "151654": {
93
+ "content": "<|vision_pad|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "151655": {
101
+ "content": "<|image_pad|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "151656": {
109
+ "content": "<|video_pad|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "151657": {
117
+ "content": "<tool_call>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": false
123
+ },
124
+ "151658": {
125
+ "content": "</tool_call>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": false
131
+ },
132
+ "151659": {
133
+ "content": "<|fim_prefix|>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": false
139
+ },
140
+ "151660": {
141
+ "content": "<|fim_middle|>",
142
+ "lstrip": false,
143
+ "normalized": false,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": false
147
+ },
148
+ "151661": {
149
+ "content": "<|fim_suffix|>",
150
+ "lstrip": false,
151
+ "normalized": false,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": false
155
+ },
156
+ "151662": {
157
+ "content": "<|fim_pad|>",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": false
163
+ },
164
+ "151663": {
165
+ "content": "<|repo_name|>",
166
+ "lstrip": false,
167
+ "normalized": false,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": false
171
+ },
172
+ "151664": {
173
+ "content": "<|file_sep|>",
174
+ "lstrip": false,
175
+ "normalized": false,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": false
179
+ },
180
+ "151665": {
181
+ "content": "<tool_response>",
182
+ "lstrip": false,
183
+ "normalized": false,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": false
187
+ },
188
+ "151666": {
189
+ "content": "</tool_response>",
190
+ "lstrip": false,
191
+ "normalized": false,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": false
195
+ },
196
+ "151667": {
197
+ "content": "<think>",
198
+ "lstrip": false,
199
+ "normalized": false,
200
+ "rstrip": false,
201
+ "single_word": false,
202
+ "special": false
203
+ },
204
+ "151668": {
205
+ "content": "</think>",
206
+ "lstrip": false,
207
+ "normalized": false,
208
+ "rstrip": false,
209
+ "single_word": false,
210
+ "special": false
211
+ }
212
+ },
213
+ "additional_special_tokens": [
214
+ "<|im_start|>",
215
+ "<|im_end|>",
216
+ "<|object_ref_start|>",
217
+ "<|object_ref_end|>",
218
+ "<|box_start|>",
219
+ "<|box_end|>",
220
+ "<|quad_start|>",
221
+ "<|quad_end|>",
222
+ "<|vision_start|>",
223
+ "<|vision_end|>",
224
+ "<|vision_pad|>",
225
+ "<|image_pad|>",
226
+ "<|video_pad|>"
227
+ ],
228
+ "bos_token": null,
229
+ "chat_template": "{% macro render_extra_keys(json_dict, handled_keys) %}\n {%- if json_dict is mapping %}\n {%- for json_key in json_dict if json_key not in handled_keys %}\n {%- if json_dict[json_key] is string %}\n {{-'\\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}\n {%- else %}\n {{- '\\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}\n {%- endif %}\n {%- endfor %}\n {%- endif %}\n{%- endmacro %}\n\n{%- if messages[0][\"role\"] == \"system\" %}\n {%- set system_message = messages[0][\"content\"] %}\n {%- set loop_messages = messages[1:] %}\n{%- else %}\n {%- set loop_messages = messages %}\n{%- endif %}\n\n{%- if not tools is defined %}\n {%- set tools = [] %}\n{%- endif %}\n\n{%- if system_message is defined %}\n {{- \"<|im_start|>system\\n\" + system_message }}\n{%- else %}\n {%- if tools is iterable and tools | length > 0 %}\n {{- \"<|im_start|>system\\nYou are Qwen, a helpful AI assistant that can interact with a computer to solve tasks.\" }}\n {%- endif %}\n{%- endif %}\n{%- if tools is iterable and tools | length > 0 %}\n {{- \"\\n\\n# Tools\\n\\nYou have access to the following functions:\\n\\n\" }}\n {{- \"<tools>\" }}\n {%- for tool in tools %}\n {%- if tool.function is defined %}\n {%- set tool = tool.function %}\n {%- endif %}\n {{- \"\\n<function>\\n<name>\" ~ tool.name ~ \"</name>\" }}\n {%- if tool.description is defined %}\n {{- '\\n<description>' ~ (tool.description | trim) ~ '</description>' }}\n {%- endif %}\n {{- '\\n<parameters>' }}\n {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}\n {%- for param_name, param_fields in tool.parameters.properties|items %}\n {{- '\\n<parameter>' }}\n {{- '\\n<name>' ~ param_name ~ '</name>' }}\n {%- if param_fields.type is defined %}\n {{- '\\n<type>' ~ (param_fields.type | string) ~ '</type>' }}\n {%- endif %}\n {%- if param_fields.description is defined %}\n {{- '\\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}\n {%- endif %}\n {%- set handled_keys = ['name', 'type', 'description'] %}\n {{- render_extra_keys(param_fields, handled_keys) }}\n {{- '\\n</parameter>' }}\n {%- endfor %}\n {%- endif %}\n {%- set handled_keys = ['type', 'properties'] %}\n {{- render_extra_keys(tool.parameters, handled_keys) }}\n {{- '\\n</parameters>' }}\n {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}\n {{- render_extra_keys(tool, handled_keys) }}\n {{- '\\n</function>' }}\n {%- endfor %}\n {{- \"\\n</tools>\" }}\n {{- '\\n\\nIf you choose to call a function ONLY reply in the following format with NO suffix:\\n\\n<tool_call>\\n<function=example_function_name>\\n<parameter=example_parameter_1>\\nvalue_1\\n</parameter>\\n<parameter=example_parameter_2>\\nThis is the value for the second parameter\\nthat can span\\nmultiple lines\\n</parameter>\\n</function>\\n</tool_call>\\n\\n<IMPORTANT>\\nReminder:\\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\\n- Required parameters MUST be specified\\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\\n</IMPORTANT>' }}\n{%- endif %}\n{%- if system_message is defined %}\n {{- '<|im_end|>\\n' }}\n{%- else %}\n {%- if tools is iterable and tools | length > 0 %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- for message in loop_messages %}\n {%- if message.role == \"assistant\" and message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}\n {{- '<|im_start|>' + message.role }}\n {%- if message.content is defined and message.content is string and message.content | trim | length > 0 %}\n {{- '\\n' + message.content | trim + '\\n' }}\n {%- endif %}\n {%- for tool_call in message.tool_calls %}\n {%- if tool_call.function is defined %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '\\n<tool_call>\\n<function=' + tool_call.name + '>\\n' }}\n {%- if tool_call.arguments is defined %}\n {%- for args_name, args_value in tool_call.arguments|items %}\n {{- '<parameter=' + args_name + '>\\n' }}\n {%- set args_value = args_value if args_value is string else args_value | tojson | safe %}\n {{- args_value }}\n {{- '\\n</parameter>\\n' }}\n {%- endfor %}\n {%- endif %}\n {{- '</function>\\n</tool_call>' }}\n {%- endfor %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"user\" or message.role == \"system\" or message.role == \"assistant\" %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.previtem and loop.previtem.role != \"tool\" %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if not loop.last and loop.nextitem.role != \"tool\" %}\n {{- '<|im_end|>\\n' }}\n {%- elif loop.last %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}",
230
+ "clean_up_tokenization_spaces": false,
231
+ "eos_token": "<|im_end|>",
232
+ "errors": "replace",
233
+ "model_max_length": 1048576,
234
+ "pad_token": "<|endoftext|>",
235
+ "split_special_tokens": false,
236
+ "tokenizer_class": "Qwen2Tokenizer",
237
+ "unk_token": null,
238
+ "add_bos_token": false
239
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff