zeekay huihui-ai commited on
Commit
4ed9ab3
·
0 Parent(s):

Duplicate from huihui-ai/Huihui-Qwen3-Coder-Next-abliterated

Browse files

Co-authored-by: huihui.ai <huihui-ai@users.noreply.huggingface.co>

Files changed (47) hide show
  1. .gitattributes +36 -0
  2. README.md +241 -0
  3. added_tokens.json +28 -0
  4. chat_template-vl.jinja +120 -0
  5. chat_template.jinja +117 -0
  6. config.json +94 -0
  7. generation_config.json +12 -0
  8. merges.txt +0 -0
  9. model-00001-of-00032.safetensors +3 -0
  10. model-00002-of-00032.safetensors +3 -0
  11. model-00003-of-00032.safetensors +3 -0
  12. model-00004-of-00032.safetensors +3 -0
  13. model-00005-of-00032.safetensors +3 -0
  14. model-00006-of-00032.safetensors +3 -0
  15. model-00007-of-00032.safetensors +3 -0
  16. model-00008-of-00032.safetensors +3 -0
  17. model-00009-of-00032.safetensors +3 -0
  18. model-00010-of-00032.safetensors +3 -0
  19. model-00011-of-00032.safetensors +3 -0
  20. model-00012-of-00032.safetensors +3 -0
  21. model-00013-of-00032.safetensors +3 -0
  22. model-00014-of-00032.safetensors +3 -0
  23. model-00015-of-00032.safetensors +3 -0
  24. model-00016-of-00032.safetensors +3 -0
  25. model-00017-of-00032.safetensors +3 -0
  26. model-00018-of-00032.safetensors +3 -0
  27. model-00019-of-00032.safetensors +3 -0
  28. model-00020-of-00032.safetensors +3 -0
  29. model-00021-of-00032.safetensors +3 -0
  30. model-00022-of-00032.safetensors +3 -0
  31. model-00023-of-00032.safetensors +3 -0
  32. model-00024-of-00032.safetensors +3 -0
  33. model-00025-of-00032.safetensors +3 -0
  34. model-00026-of-00032.safetensors +3 -0
  35. model-00027-of-00032.safetensors +3 -0
  36. model-00028-of-00032.safetensors +3 -0
  37. model-00029-of-00032.safetensors +3 -0
  38. model-00030-of-00032.safetensors +3 -0
  39. model-00031-of-00032.safetensors +3 -0
  40. model-00032-of-00032.safetensors +3 -0
  41. model.safetensors.index.json +0 -0
  42. qwen3_coder_detector_sgl.py +474 -0
  43. qwen3coder_tool_parser_vllm.py +690 -0
  44. special_tokens_map.json +31 -0
  45. tokenizer.json +3 -0
  46. tokenizer_config.json +239 -0
  47. vocab.json +0 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ base_model:
7
+ - Qwen/Qwen3-Coder-Next
8
+ tags:
9
+ - abliterated
10
+ - uncensored
11
+ ---
12
+
13
+ # huihui-ai/Huihui-Qwen3-Coder-Next-abliterated
14
+
15
+
16
+ This is an uncensored version of [Qwen/Qwen3-Coder-Next](https://huggingface.co/Qwen/Qwen3-Coder-Next) created with abliteration (see [remove-refusals-with-transformers](https://github.com/Sumandora/remove-refusals-with-transformers) to know more about it).
17
+ This is a crude, proof-of-concept implementation to remove refusals from an LLM model without using TransformerLens.
18
+
19
+ ## ollama
20
+
21
+ Please use the latest version of [ollama 0.15.5](https://github.com/ollama/ollama/releases/tag/v0.15.5)
22
+
23
+ You can use [huihui_ai/qwen3-coder-next-abliterated](https://ollama.com/huihui_ai/qwen3-coder-next-abliterated) directly,
24
+ ```
25
+ ollama run huihui_ai/qwen3-coder-next-abliterated
26
+ ```
27
+
28
+ ## chat_template-vl.jinja
29
+
30
+ We have added a new file named [chat_template-vl.jinja](https://huggingface.co/huihui-ai/Huihui-Qwen3-Coder-Next-abliterated/blob/main/chat_template-vl.jinja), which comes from the path `huihui-ai/Huihui-Qwen3-VL-30B-A3B-Instruct-abliterated`.
31
+
32
+ The new file chat_template-vl.jinja is more compatible with using Tool Calling in [llama-server](https://github.com/ggml-org/llama.cpp/releases/tag/b7952),
33
+ especially when [opencode](https://github.com/anomalyco/opencode/releases/tag/v1.1.53) is involved.
34
+
35
+
36
+ ## Usage
37
+ You can use this model in your applications by loading it with Hugging Face's `transformers` library:
38
+
39
+ ```python
40
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer, BitsAndBytesConfig
41
+ import torch
42
+ import os
43
+ import signal
44
+ import random
45
+ import numpy as np
46
+ import time
47
+ import sys
48
+
49
+ if (
50
+ "PYTORCH_ALLOC_CONF" not in os.environ
51
+ and "PYTORCH_CUDA_ALLOC_CONF" not in os.environ
52
+ ):
53
+ print(f"PYTORCH_ALLOC_CONF.")
54
+ os.environ["PYTORCH_ALLOC_CONF"] = "expandable_segments:True"
55
+
56
+ cpu_count = os.cpu_count()
57
+ print(f"Number of CPU cores in the system: {cpu_count}")
58
+ half_cpu_count = cpu_count // 2
59
+ os.environ["MKL_NUM_THREADS"] = str(half_cpu_count)
60
+ os.environ["OMP_NUM_THREADS"] = str(half_cpu_count)
61
+ torch.set_num_threads(half_cpu_count)
62
+
63
+ print(f"PyTorch threads: {torch.get_num_threads()}")
64
+ print(f"MKL threads: {os.getenv('MKL_NUM_THREADS')}")
65
+ print(f"OMP threads: {os.getenv('OMP_NUM_THREADS')}")
66
+
67
+ # Load the model and tokenizer
68
+ MODEL_ID = "huihui-ai/Huihui-Qwen3-Coder-Next-abliterated"
69
+
70
+ print(f"Load Model {MODEL_ID} ... ")
71
+ quant_config_4 = BitsAndBytesConfig(
72
+ load_in_4bit=True,
73
+ bnb_4bit_compute_dtype=torch.bfloat16,
74
+ bnb_4bit_use_double_quant=True,
75
+ llm_int8_enable_fp32_cpu_offload=True,
76
+ )
77
+
78
+ model = AutoModelForCausalLM.from_pretrained(
79
+ MODEL_ID,
80
+ device_map="auto",
81
+ trust_remote_code=True,
82
+ torch_dtype="auto",
83
+ low_cpu_mem_usage=True,
84
+ quantization_config=quant_config_4,
85
+ )
86
+
87
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
88
+
89
+ messages = []
90
+ skip_prompt=True
91
+ skip_special_tokens=True
92
+
93
+ class CustomTextStreamer(TextStreamer):
94
+ def __init__(self, tokenizer, skip_prompt=True, skip_special_tokens=True):
95
+ super().__init__(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
96
+ self.generated_text = ""
97
+ self.stop_flag = False
98
+ self.init_time = time.time() # Record initialization time
99
+ self.end_time = None # To store end time
100
+ self.first_token_time = None # To store first token generation time
101
+ self.token_count = 0 # To track total tokens
102
+
103
+ def on_finalized_text(self, text: str, stream_end: bool = False):
104
+ if self.first_token_time is None and text.strip(): # Set first token time on first non-empty text
105
+ self.first_token_time = time.time()
106
+ self.generated_text += text
107
+
108
+ self.token_count += 1
109
+
110
+ print(text, end="", flush=True)
111
+ if stream_end:
112
+ self.end_time = time.time() # Record end time when streaming ends
113
+ if self.stop_flag:
114
+ raise StopIteration
115
+
116
+ def stop_generation(self):
117
+ self.stop_flag = True
118
+ self.end_time = time.time() # Record end time when generation is stopped
119
+
120
+ def get_metrics(self):
121
+ """Returns initialization time, first token time, first token latency, end time, total time, total tokens, and tokens per second."""
122
+ if self.end_time is None:
123
+ self.end_time = time.time() # Set end time if not already set
124
+ total_time = self.end_time - self.init_time # Total time from init to end
125
+ tokens_per_second = self.token_count / total_time if total_time > 0 else 0
126
+ first_token_latency = (self.first_token_time - self.init_time) if self.first_token_time is not None else None
127
+ metrics = {
128
+ "init_time": self.init_time,
129
+ "first_token_time": self.first_token_time,
130
+ "first_token_latency": first_token_latency,
131
+ "end_time": self.end_time,
132
+ "total_time": total_time, # Total time in seconds
133
+ "total_tokens": self.token_count,
134
+ "tokens_per_second": tokens_per_second
135
+ }
136
+ return metrics
137
+
138
+ def generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, max_new_tokens):
139
+ text = tokenizer.apply_chat_template(
140
+ messages,
141
+ tokenize=False,
142
+ add_generation_prompt=True,
143
+ )
144
+ model_inputs = tokenizer(
145
+ [text],
146
+ return_tensors="pt",
147
+ ).to(model.device)
148
+
149
+ streamer = CustomTextStreamer(tokenizer, skip_prompt=skip_prompt, skip_special_tokens=skip_special_tokens)
150
+
151
+ def signal_handler(sig, frame):
152
+ streamer.stop_generation()
153
+ print("\n[Generation stopped by user with Ctrl+C]")
154
+
155
+ signal.signal(signal.SIGINT, signal_handler)
156
+
157
+ print("Response: ", end="", flush=True)
158
+ try:
159
+ generated_ids = model.generate(
160
+ **model_inputs,
161
+ max_new_tokens = max_new_tokens,
162
+ streamer=streamer,
163
+ )
164
+ del generated_ids
165
+ except StopIteration:
166
+ print("\n[Stopped by user]")
167
+
168
+ del model_inputs
169
+ torch.cuda.empty_cache()
170
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
171
+
172
+ return streamer.generated_text, streamer.stop_flag, streamer.get_metrics()
173
+
174
+
175
+ while True:
176
+ print(f"skip_prompt: {skip_prompt}")
177
+ print(f"skip_special_tokens: {skip_special_tokens}")
178
+
179
+ user_input = input("User: ").strip()
180
+ if user_input.lower() == "/exit":
181
+ print("Exiting chat.")
182
+ break
183
+ if user_input.lower() == "/clear":
184
+ messages = []
185
+ print("Chat history cleared. Starting a new conversation.")
186
+ continue
187
+ if user_input.lower() == "/skip_prompt":
188
+ skip_prompt = not skip_prompt
189
+ continue
190
+ if user_input.lower() == "/skip_special_tokens":
191
+ skip_special_tokens = not skip_special_tokens
192
+ continue
193
+ if not user_input:
194
+ print("Input cannot be empty. Please enter something.")
195
+ continue
196
+
197
+
198
+ messages.append({
199
+ "role": "user",
200
+ "content": user_input
201
+ })
202
+
203
+ response, stop_flag, metrics = generate_stream(model, tokenizer, messages, skip_prompt, skip_special_tokens, 40960)
204
+ print("\n\nMetrics:")
205
+ for key, value in metrics.items():
206
+ print(f" {key}: {value}")
207
+
208
+
209
+ print("", flush=True)
210
+ if stop_flag:
211
+ continue
212
+ messages.append({
213
+ "role": "assistant",
214
+ "content": response.strip()
215
+ })
216
+ ```
217
+
218
+ ### Usage Warnings
219
+
220
+
221
+ - **Risk of Sensitive or Controversial Outputs**: This model’s safety filtering has been significantly reduced, potentially generating sensitive, controversial, or inappropriate content. Users should exercise caution and rigorously review generated outputs.
222
+
223
+ - **Not Suitable for All Audiences**: Due to limited content filtering, the model’s outputs may be inappropriate for public settings, underage users, or applications requiring high security.
224
+
225
+ - **Legal and Ethical Responsibilities**: Users must ensure their usage complies with local laws and ethical standards. Generated content may carry legal or ethical risks, and users are solely responsible for any consequences.
226
+
227
+ - **Research and Experimental Use**: It is recommended to use this model for research, testing, or controlled environments, avoiding direct use in production or public-facing commercial applications.
228
+
229
+ - **Monitoring and Review Recommendations**: Users are strongly advised to monitor model outputs in real-time and conduct manual reviews when necessary to prevent the dissemination of inappropriate content.
230
+
231
+ - **No Default Safety Guarantees**: Unlike standard models, this model has not undergone rigorous safety optimization. huihui.ai bears no responsibility for any consequences arising from its use.
232
+
233
+
234
+ ### Donation
235
+ ##### Your donation helps us continue our further development and improvement, a cup of coffee can do it.
236
+ - bitcoin:
237
+ ```
238
+ bc1qqnkhuchxw0zqjh2ku3lu4hq45hc6gy84uk70ge
239
+ ```
240
+ - Support our work on [Ko-fi](https://ko-fi.com/huihuiai)!
241
+
added_tokens.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</think>": 151668,
3
+ "</tool_call>": 151658,
4
+ "</tool_response>": 151666,
5
+ "<think>": 151667,
6
+ "<tool_call>": 151657,
7
+ "<tool_response>": 151665,
8
+ "<|box_end|>": 151649,
9
+ "<|box_start|>": 151648,
10
+ "<|endoftext|>": 151643,
11
+ "<|file_sep|>": 151664,
12
+ "<|fim_middle|>": 151660,
13
+ "<|fim_pad|>": 151662,
14
+ "<|fim_prefix|>": 151659,
15
+ "<|fim_suffix|>": 151661,
16
+ "<|im_end|>": 151645,
17
+ "<|im_start|>": 151644,
18
+ "<|image_pad|>": 151655,
19
+ "<|object_ref_end|>": 151647,
20
+ "<|object_ref_start|>": 151646,
21
+ "<|quad_end|>": 151651,
22
+ "<|quad_start|>": 151650,
23
+ "<|repo_name|>": 151663,
24
+ "<|video_pad|>": 151656,
25
+ "<|vision_end|>": 151653,
26
+ "<|vision_pad|>": 151654,
27
+ "<|vision_start|>": 151652
28
+ }
chat_template-vl.jinja ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {%- if messages[0].content is string %}
5
+ {{- messages[0].content }}
6
+ {%- else %}
7
+ {%- for content in messages[0].content %}
8
+ {%- if 'text' in content %}
9
+ {{- content.text }}
10
+ {%- endif %}
11
+ {%- endfor %}
12
+ {%- endif %}
13
+ {{- '\n\n' }}
14
+ {%- endif %}
15
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
16
+ {%- for tool in tools %}
17
+ {{- "\n" }}
18
+ {{- tool | tojson }}
19
+ {%- endfor %}
20
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
21
+ {%- else %}
22
+ {%- if messages[0].role == 'system' %}
23
+ {{- '<|im_start|>system\n' }}
24
+ {%- if messages[0].content is string %}
25
+ {{- messages[0].content }}
26
+ {%- else %}
27
+ {%- for content in messages[0].content %}
28
+ {%- if 'text' in content %}
29
+ {{- content.text }}
30
+ {%- endif %}
31
+ {%- endfor %}
32
+ {%- endif %}
33
+ {{- '<|im_end|>\n' }}
34
+ {%- endif %}
35
+ {%- endif %}
36
+ {%- set image_count = namespace(value=0) %}
37
+ {%- set video_count = namespace(value=0) %}
38
+ {%- for message in messages %}
39
+ {%- if message.role == "user" %}
40
+ {{- '<|im_start|>' + message.role + '\n' }}
41
+ {%- if message.content is string %}
42
+ {{- message.content }}
43
+ {%- else %}
44
+ {%- for content in message.content %}
45
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
46
+ {%- set image_count.value = image_count.value + 1 %}
47
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
48
+ <|vision_start|><|image_pad|><|vision_end|>
49
+ {%- elif content.type == 'video' or 'video' in content %}
50
+ {%- set video_count.value = video_count.value + 1 %}
51
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
52
+ <|vision_start|><|video_pad|><|vision_end|>
53
+ {%- elif 'text' in content %}
54
+ {{- content.text }}
55
+ {%- endif %}
56
+ {%- endfor %}
57
+ {%- endif %}
58
+ {{- '<|im_end|>\n' }}
59
+ {%- elif message.role == "assistant" %}
60
+ {{- '<|im_start|>' + message.role + '\n' }}
61
+ {%- if message.content is string %}
62
+ {{- message.content }}
63
+ {%- else %}
64
+ {%- for content_item in message.content %}
65
+ {%- if 'text' in content_item %}
66
+ {{- content_item.text }}
67
+ {%- endif %}
68
+ {%- endfor %}
69
+ {%- endif %}
70
+ {%- if message.tool_calls %}
71
+ {%- for tool_call in message.tool_calls %}
72
+ {%- if (loop.first and message.content) or (not loop.first) %}
73
+ {{- '\n' }}
74
+ {%- endif %}
75
+ {%- if tool_call.function %}
76
+ {%- set tool_call = tool_call.function %}
77
+ {%- endif %}
78
+ {{- '<tool_call>\n{"name": "' }}
79
+ {{- tool_call.name }}
80
+ {{- '", "arguments": ' }}
81
+ {%- if tool_call.arguments is string %}
82
+ {{- tool_call.arguments }}
83
+ {%- else %}
84
+ {{- tool_call.arguments | tojson }}
85
+ {%- endif %}
86
+ {{- '}\n</tool_call>' }}
87
+ {%- endfor %}
88
+ {%- endif %}
89
+ {{- '<|im_end|>\n' }}
90
+ {%- elif message.role == "tool" %}
91
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
92
+ {{- '<|im_start|>user' }}
93
+ {%- endif %}
94
+ {{- '\n<tool_response>\n' }}
95
+ {%- if message.content is string %}
96
+ {{- message.content }}
97
+ {%- else %}
98
+ {%- for content in message.content %}
99
+ {%- if content.type == 'image' or 'image' in content or 'image_url' in content %}
100
+ {%- set image_count.value = image_count.value + 1 %}
101
+ {%- if add_vision_id %}Picture {{ image_count.value }}: {% endif -%}
102
+ <|vision_start|><|image_pad|><|vision_end|>
103
+ {%- elif content.type == 'video' or 'video' in content %}
104
+ {%- set video_count.value = video_count.value + 1 %}
105
+ {%- if add_vision_id %}Video {{ video_count.value }}: {% endif -%}
106
+ <|vision_start|><|video_pad|><|vision_end|>
107
+ {%- elif 'text' in content %}
108
+ {{- content.text }}
109
+ {%- endif %}
110
+ {%- endfor %}
111
+ {%- endif %}
112
+ {{- '\n</tool_response>' }}
113
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
114
+ {{- '<|im_end|>\n' }}
115
+ {%- endif %}
116
+ {%- endif %}
117
+ {%- endfor %}
118
+ {%- if add_generation_prompt %}
119
+ {{- '<|im_start|>assistant\n' }}
120
+ {%- endif %}
chat_template.jinja ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro render_extra_keys(json_dict, handled_keys) %}
2
+ {%- if json_dict is mapping %}
3
+ {%- for json_key in json_dict if json_key not in handled_keys %}
4
+ {%- if json_dict[json_key] is string %}
5
+ {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
6
+ {%- else %}
7
+ {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
8
+ {%- endif %}
9
+ {%- endfor %}
10
+ {%- endif %}
11
+ {%- endmacro %}
12
+
13
+ {%- if messages[0]["role"] == "system" %}
14
+ {%- set system_message = messages[0]["content"] %}
15
+ {%- set loop_messages = messages[1:] %}
16
+ {%- else %}
17
+ {%- set loop_messages = messages %}
18
+ {%- endif %}
19
+
20
+ {%- if not tools is defined %}
21
+ {%- set tools = [] %}
22
+ {%- endif %}
23
+
24
+ {%- if system_message is defined %}
25
+ {{- "<|im_start|>system\n" + system_message }}
26
+ {%- else %}
27
+ {%- if tools is iterable and tools | length > 0 %}
28
+ {{- "<|im_start|>system\nYou are Qwen, a helpful AI assistant that can interact with a computer to solve tasks." }}
29
+ {%- endif %}
30
+ {%- endif %}
31
+ {%- if tools is iterable and tools | length > 0 %}
32
+ {{- "\n\n# Tools\n\nYou have access to the following functions:\n\n" }}
33
+ {{- "<tools>" }}
34
+ {%- for tool in tools %}
35
+ {%- if tool.function is defined %}
36
+ {%- set tool = tool.function %}
37
+ {%- endif %}
38
+ {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
39
+ {%- if tool.description is defined %}
40
+ {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
41
+ {%- endif %}
42
+ {{- '\n<parameters>' }}
43
+ {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
44
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
45
+ {{- '\n<parameter>' }}
46
+ {{- '\n<name>' ~ param_name ~ '</name>' }}
47
+ {%- if param_fields.type is defined %}
48
+ {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
49
+ {%- endif %}
50
+ {%- if param_fields.description is defined %}
51
+ {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
52
+ {%- endif %}
53
+ {%- set handled_keys = ['name', 'type', 'description'] %}
54
+ {{- render_extra_keys(param_fields, handled_keys) }}
55
+ {{- '\n</parameter>' }}
56
+ {%- endfor %}
57
+ {%- endif %}
58
+ {%- set handled_keys = ['type', 'properties'] %}
59
+ {{- render_extra_keys(tool.parameters, handled_keys) }}
60
+ {{- '\n</parameters>' }}
61
+ {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
62
+ {{- render_extra_keys(tool, handled_keys) }}
63
+ {{- '\n</function>' }}
64
+ {%- endfor %}
65
+ {{- "\n</tools>" }}
66
+ {{- '\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>' }}
67
+ {%- endif %}
68
+ {%- if system_message is defined %}
69
+ {{- '<|im_end|>\n' }}
70
+ {%- else %}
71
+ {%- if tools is iterable and tools | length > 0 %}
72
+ {{- '<|im_end|>\n' }}
73
+ {%- endif %}
74
+ {%- endif %}
75
+ {%- for message in loop_messages %}
76
+ {%- if message.role == "assistant" and message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
77
+ {{- '<|im_start|>' + message.role }}
78
+ {%- if message.content is defined and message.content is string and message.content | trim | length > 0 %}
79
+ {{- '\n' + message.content | trim + '\n' }}
80
+ {%- endif %}
81
+ {%- for tool_call in message.tool_calls %}
82
+ {%- if tool_call.function is defined %}
83
+ {%- set tool_call = tool_call.function %}
84
+ {%- endif %}
85
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
86
+ {%- if tool_call.arguments is defined %}
87
+ {%- for args_name, args_value in tool_call.arguments|items %}
88
+ {{- '<parameter=' + args_name + '>\n' }}
89
+ {%- set args_value = args_value if args_value is string else args_value | tojson | safe %}
90
+ {{- args_value }}
91
+ {{- '\n</parameter>\n' }}
92
+ {%- endfor %}
93
+ {%- endif %}
94
+ {{- '</function>\n</tool_call>' }}
95
+ {%- endfor %}
96
+ {{- '<|im_end|>\n' }}
97
+ {%- elif message.role == "user" or message.role == "system" or message.role == "assistant" %}
98
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
99
+ {%- elif message.role == "tool" %}
100
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
101
+ {{- '<|im_start|>user' }}
102
+ {%- endif %}
103
+ {{- '\n<tool_response>\n' }}
104
+ {{- message.content }}
105
+ {{- '\n</tool_response>' }}
106
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
107
+ {{- '<|im_end|>\n' }}
108
+ {%- elif loop.last %}
109
+ {{- '<|im_end|>\n' }}
110
+ {%- endif %}
111
+ {%- else %}
112
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
113
+ {%- endif %}
114
+ {%- endfor %}
115
+ {%- if add_generation_prompt %}
116
+ {{- '<|im_start|>assistant\n' }}
117
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3NextForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0,
7
+ "bos_token_id": 151643,
8
+ "decoder_sparse_step": 1,
9
+ "dtype": "bfloat16",
10
+ "eos_token_id": 151645,
11
+ "full_attention_interval": 4,
12
+ "head_dim": 256,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 2048,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 5120,
17
+ "layer_types": [
18
+ "linear_attention",
19
+ "linear_attention",
20
+ "linear_attention",
21
+ "full_attention",
22
+ "linear_attention",
23
+ "linear_attention",
24
+ "linear_attention",
25
+ "full_attention",
26
+ "linear_attention",
27
+ "linear_attention",
28
+ "linear_attention",
29
+ "full_attention",
30
+ "linear_attention",
31
+ "linear_attention",
32
+ "linear_attention",
33
+ "full_attention",
34
+ "linear_attention",
35
+ "linear_attention",
36
+ "linear_attention",
37
+ "full_attention",
38
+ "linear_attention",
39
+ "linear_attention",
40
+ "linear_attention",
41
+ "full_attention",
42
+ "linear_attention",
43
+ "linear_attention",
44
+ "linear_attention",
45
+ "full_attention",
46
+ "linear_attention",
47
+ "linear_attention",
48
+ "linear_attention",
49
+ "full_attention",
50
+ "linear_attention",
51
+ "linear_attention",
52
+ "linear_attention",
53
+ "full_attention",
54
+ "linear_attention",
55
+ "linear_attention",
56
+ "linear_attention",
57
+ "full_attention",
58
+ "linear_attention",
59
+ "linear_attention",
60
+ "linear_attention",
61
+ "full_attention",
62
+ "linear_attention",
63
+ "linear_attention",
64
+ "linear_attention",
65
+ "full_attention"
66
+ ],
67
+ "linear_conv_kernel_dim": 4,
68
+ "linear_key_head_dim": 128,
69
+ "linear_num_key_heads": 16,
70
+ "linear_num_value_heads": 32,
71
+ "linear_value_head_dim": 128,
72
+ "max_position_embeddings": 262144,
73
+ "mlp_only_layers": [],
74
+ "model_type": "qwen3_next",
75
+ "moe_intermediate_size": 512,
76
+ "norm_topk_prob": true,
77
+ "num_attention_heads": 16,
78
+ "num_experts": 512,
79
+ "num_experts_per_tok": 10,
80
+ "num_hidden_layers": 48,
81
+ "num_key_value_heads": 2,
82
+ "output_router_logits": false,
83
+ "partial_rotary_factor": 0.25,
84
+ "rms_norm_eps": 1e-06,
85
+ "rope_scaling": null,
86
+ "rope_theta": 5000000,
87
+ "router_aux_loss_coef": 0.001,
88
+ "shared_expert_intermediate_size": 512,
89
+ "tie_word_embeddings": false,
90
+ "transformers_version": "4.57.3",
91
+ "use_cache": true,
92
+ "use_sliding_window": false,
93
+ "vocab_size": 151936
94
+ }
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "top_k": 40,
10
+ "top_p": 0.95,
11
+ "transformers_version": "4.57.3"
12
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7742dee28eed9b2b6d7c2ba09c39204774cfc6eccf91bdf13f057f6111d592b
3
+ size 5000007128
model-00002-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cbe43addb17224f42808722bb8b72f1a9ac1e69f35b29db5f350fcd465f97b60
3
+ size 5000242936
model-00003-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:325a1b7fd5c207ced92e73878a59f3f7d55e01c62be32cf1d7232e53060a87c5
3
+ size 5000253712
model-00004-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7159d0a65ae2d5cc19eaae354466d0afceee28419581de374d23ff698c8bdeaf
3
+ size 5000242936
model-00005-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f2c5363db8a86bd98c53d0c9760b80924de3b1fea2e58f1ff27441baf7b82c2
3
+ size 5000253760
model-00006-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50aeda421ae42201207d469a039cfe53dc89d74947e69906dd6c5d5031b58d0a
3
+ size 5000242936
model-00007-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0cfbc0dd9dcd77151b1e071531fc56f1999ad8c4f29148180e4f0ef971368160
3
+ size 4998483600
model-00008-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a99f4913b603c09cad6a4513432c94fe0ea69fa9d38f1dd2344bac61ba757b77
3
+ size 4999918888
model-00009-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3e1dc03ff11037805d8c53ef61fd5d562c785d29e6742830a0713b6021c51c9
3
+ size 4998485240
model-00010-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2bb17978fcc800b9f8e72b35b3171570f39f698f9c57d13a51f165fc37ba7735
3
+ size 5000245296
model-00011-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:316d96cd9cd636957ef089bc6dd307a660f838c5f0b6cc830e53d64ccda5d0a0
3
+ size 5000256048
model-00012-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8bb1116c58f883f27c97c8f77166531239c21a86d148ae18a539844b8e8ba277
3
+ size 4998485520
model-00013-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:306f572e66da8ed5401794956b98d157b38ac86df958dca462f56780163f2808
3
+ size 4999918568
model-00014-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b271e8c1eeb25e48d0a91c412c21e87b890d7842fec401a78acd90097b49cc3
3
+ size 4998485432
model-00015-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f02fef45ca8a8a2e181364bed47b02d2cafd371de72447d774b38c7182ee1aeb
3
+ size 5000245056
model-00016-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cfa396498c606cb1af64a04624a73390aef58e10d15682f1c05fa8030a9bcdd6
3
+ size 5000256248
model-00017-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9332eb2604728f1800c41da5d7348f5ac3c8b2e6d11c6673504adb76de2d7e16
3
+ size 5000245120
model-00018-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd3ad2214399a40205b16f29398955e470d09bed031527ebd97ffc371086a007
3
+ size 5000256184
model-00019-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6deeecc53230f7b68036cedb2bd08ea3fb8a9cf4652bd24c2a106f41e7044add
3
+ size 5000245176
model-00020-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68a261627efcba2d1b4834a4a60f5e388060d672ae7e0419979d10753bcdc60c
3
+ size 4998485264
model-00021-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f7d836f9972b563d47c0c18368421140f0a6d2ec716eac2d7b451f5ef94d07c
3
+ size 4999918824
model-00022-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46785a76c70cce79eef743d78def866e9c3efe55718e6e8abedbcf4734810aed
3
+ size 4998485208
model-00023-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01e0b19eda5c994984d2fc5c7e339f917be776c3aa79e0842098d1795ce16622
3
+ size 5000245288
model-00024-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb3d17a18ed4d8e059faa97c7a39f897d3b9db24fb1bf8b8ced2da18a91a59b9
3
+ size 5000256056
model-00025-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ffc6d28db22d1096c293c6f8d1c3353b0ebe9cb2e2fcc33a06e76dfe4edda2fc
3
+ size 5000245296
model-00026-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1fc851b1a94b5a65510ce42956827f6c8b2001c494bbde6047a44bc7a0aaadf0
3
+ size 5000256104
model-00027-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e2e38993c8398dbc885e859be96986520659e671f06b0a43b5727a04c2e22ec
3
+ size 5000245296
model-00028-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f83450cab3992e05421532b1c2d5f32afa4047e50068baa529c21cb0d2e086f
3
+ size 4998485240
model-00029-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:79c28c2c9580daed3682a495fa919fac47df3544cb49c2b31c932bce2c56c6a7
3
+ size 4999918888
model-00030-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e2d014fe732578e969d131c7f91d8e75813f7624ba9364e423caa7e824c00db
3
+ size 4998485240
model-00031-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc238ec36871ba09006dc3ae607ab4c91a62d3a642d2f5b9d13e2b1192202477
3
+ size 5000245296
model-00032-of-00032.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:853be074450c496d8434fda9043d5d1d28964d6ce498583ce3a0990719a50917
3
+ size 4365997256
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
qwen3coder_tool_parser_vllm.py ADDED
@@ -0,0 +1,690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ import ast
4
+ import json
5
+ import uuid
6
+ from collections.abc import Sequence
7
+ from typing import Any, List, Optional, Union
8
+
9
+ import regex as re
10
+
11
+ from vllm.entrypoints.openai.protocol import (ChatCompletionRequest,
12
+ ChatCompletionToolsParam,
13
+ DeltaFunctionCall, DeltaMessage,
14
+ DeltaToolCall,
15
+ ExtractedToolCallInformation,
16
+ FunctionCall, ToolCall)
17
+ from vllm.entrypoints.openai.tool_parsers.abstract_tool_parser import (
18
+ ToolParser, ToolParserManager)
19
+ from vllm.logger import init_logger
20
+ from vllm.transformers_utils.tokenizer import AnyTokenizer
21
+
22
+ logger = init_logger(__name__)
23
+
24
+
25
+ @ToolParserManager.register_module("qwen3_coder")
26
+ class Qwen3CoderToolParser(ToolParser):
27
+
28
+ def __init__(self, tokenizer: AnyTokenizer):
29
+ super().__init__(tokenizer)
30
+
31
+ self.current_tool_name_sent: bool = False
32
+ self.prev_tool_call_arr: list[dict] = []
33
+ self.current_tool_id: int = -1
34
+ self.streamed_args_for_tool: list[str] = []
35
+
36
+ # Sentinel tokens for streaming mode
37
+ self.tool_call_start_token: str = "<tool_call>"
38
+ self.tool_call_end_token: str = "</tool_call>"
39
+ self.tool_call_prefix: str = "<function="
40
+ self.function_end_token: str = "</function>"
41
+ self.parameter_prefix: str = "<parameter="
42
+ self.parameter_end_token: str = "</parameter>"
43
+ self.is_tool_call_started: bool = False
44
+ self.failed_count: int = 0
45
+
46
+ # Enhanced streaming state - reset for each new message
47
+ self._reset_streaming_state()
48
+
49
+ # Regex patterns
50
+ self.tool_call_complete_regex = re.compile(
51
+ r"<tool_call>(.*?)</tool_call>", re.DOTALL)
52
+ self.tool_call_regex = re.compile(
53
+ r"<tool_call>(.*?)</tool_call>|<tool_call>(.*?)$", re.DOTALL)
54
+ self.tool_call_function_regex = re.compile(
55
+ r"<function=(.*?)</function>|<function=(.*)$", re.DOTALL)
56
+ self.tool_call_parameter_regex = re.compile(
57
+ r"<parameter=(.*?)(?:</parameter>|(?=<parameter=)|(?=</function>)|$)",
58
+ re.DOTALL)
59
+
60
+ if not self.model_tokenizer:
61
+ raise ValueError(
62
+ "The model tokenizer must be passed to the ToolParser "
63
+ "constructor during construction.")
64
+
65
+ self.tool_call_start_token_id = self.vocab.get(
66
+ self.tool_call_start_token)
67
+ self.tool_call_end_token_id = self.vocab.get(self.tool_call_end_token)
68
+
69
+ if self.tool_call_start_token_id is None or self.tool_call_end_token_id is None:
70
+ raise RuntimeError(
71
+ "Qwen3 XML Tool parser could not locate tool call start/end "
72
+ "tokens in the tokenizer!")
73
+
74
+ logger.info(
75
+ f"vLLM Successfully import tool parser {self.__class__.__name__} !"
76
+ )
77
+
78
+ def _generate_tool_call_id(self) -> str:
79
+ """Generate a unique tool call ID."""
80
+ return f"call_{uuid.uuid4().hex[:24]}"
81
+
82
+ def _reset_streaming_state(self):
83
+ """Reset all streaming state."""
84
+ self.current_tool_index = 0
85
+ self.is_tool_call_started = False
86
+ self.header_sent = False
87
+ self.current_tool_id = None
88
+ self.current_function_name = None
89
+ self.current_param_name = None
90
+ self.current_param_value = ""
91
+ self.param_count = 0
92
+ self.in_param = False
93
+ self.in_function = False
94
+ self.accumulated_text = ""
95
+ self.json_started = False
96
+ self.json_closed = False
97
+ # Store accumulated parameters for type conversion
98
+ self.accumulated_params = {}
99
+ self.streaming_request = None
100
+
101
+ def _get_arguments_config(
102
+ self, func_name: str,
103
+ tools: Optional[list[ChatCompletionToolsParam]]) -> dict:
104
+ """Extract argument configuration for a function."""
105
+ if tools is None:
106
+ return {}
107
+ for config in tools:
108
+ if not hasattr(config, "type") or not (hasattr(
109
+ config, "function") and hasattr(config.function, "name")):
110
+ continue
111
+ if config.type == "function" and config.function.name == func_name:
112
+ if not hasattr(config.function, "parameters"):
113
+ return {}
114
+ params = config.function.parameters
115
+ if isinstance(params, dict) and "properties" in params:
116
+ return params["properties"]
117
+ elif isinstance(params, dict):
118
+ return params
119
+ else:
120
+ return {}
121
+ logger.warning(f"Tool '{func_name}' is not defined in the tools list.")
122
+ return {}
123
+
124
+ def _convert_param_value(self, param_value: str, param_name: str,
125
+ param_config: dict, func_name: str) -> Any:
126
+ """Convert parameter value based on its type in the schema."""
127
+ # Handle null value for any type
128
+ if param_value.lower() == "null":
129
+ return None
130
+
131
+ if param_name not in param_config:
132
+ if param_config != {}:
133
+ logger.warning(
134
+ f"Parsed parameter '{param_name}' is not defined in the tool "
135
+ f"parameters for tool '{func_name}', directly returning the string value."
136
+ )
137
+ return param_value
138
+
139
+ if isinstance(param_config[param_name],
140
+ dict) and "type" in param_config[param_name]:
141
+ param_type = str(param_config[param_name]["type"]).strip().lower()
142
+ else:
143
+ param_type = "string"
144
+ if param_type in ["string", "str", "text", "varchar", "char", "enum"]:
145
+ return param_value
146
+ elif param_type.startswith("int") or param_type.startswith(
147
+ "uint") or param_type.startswith(
148
+ "long") or param_type.startswith(
149
+ "short") or param_type.startswith("unsigned"):
150
+ try:
151
+ param_value = int(param_value)
152
+ except:
153
+ logger.warning(
154
+ f"Parsed value '{param_value}' of parameter '{param_name}' is not an integer in tool "
155
+ f"'{func_name}', degenerating to string.")
156
+ return param_value
157
+ elif param_type.startswith("num") or param_type.startswith("float"):
158
+ try:
159
+ maybe_convert = False if "." in param_value or "e" in param_value.lower() else True
160
+ param_value: float = float(param_value)
161
+ if maybe_convert and param_value.is_integer():
162
+ param_value = int(param_value)
163
+ except:
164
+ logger.warning(
165
+ f"Parsed value '{param_value}' of parameter '{param_name}' is not a float in tool "
166
+ f"'{func_name}', degenerating to string.")
167
+ return param_value
168
+ elif param_type in ["boolean", "bool", "binary"]:
169
+ param_value = param_value.lower()
170
+ if param_value not in ["true", "false"]:
171
+ logger.warning(
172
+ f"Parsed value '{param_value}' of parameter '{param_name}' is not a boolean (`true` of `false`) in tool '{func_name}', degenerating to false."
173
+ )
174
+ return param_value == "true"
175
+ else:
176
+ if param_type in ["object", "array", "arr"
177
+ ] or param_type.startswith(
178
+ "dict") or param_type.startswith("list"):
179
+ try:
180
+ param_value = json.loads(param_value)
181
+ return param_value
182
+ except:
183
+ logger.warning(
184
+ f"Parsed value '{param_value}' of parameter '{param_name}' cannot be parsed with json.loads in tool "
185
+ f"'{func_name}', will try other methods to parse it.")
186
+ try:
187
+ param_value = ast.literal_eval(param_value) # safer
188
+ except:
189
+ logger.warning(
190
+ f"Parsed value '{param_value}' of parameter '{param_name}' cannot be converted via Python `ast.literal_eval()` in tool '{func_name}', degenerating to string."
191
+ )
192
+ return param_value
193
+
194
+ def _parse_xml_function_call(
195
+ self, function_call_str: str,
196
+ tools: Optional[list[ChatCompletionToolsParam]]
197
+ ) -> Optional[ToolCall]:
198
+
199
+ # Extract function name
200
+ end_index = function_call_str.index(">")
201
+ function_name = function_call_str[:end_index]
202
+ param_config = self._get_arguments_config(function_name, tools)
203
+ parameters = function_call_str[end_index + 1:]
204
+ param_dict = {}
205
+ for match_text in self.tool_call_parameter_regex.findall(parameters):
206
+ idx = match_text.index(">")
207
+ param_name = match_text[:idx]
208
+ param_value = str(match_text[idx + 1:])
209
+ # Remove prefix and trailing \n
210
+ if param_value.startswith("\n"):
211
+ param_value = param_value[1:]
212
+ if param_value.endswith("\n"):
213
+ param_value = param_value[:-1]
214
+
215
+ param_dict[param_name] = self._convert_param_value(
216
+ param_value, param_name, param_config, function_name)
217
+ return ToolCall(
218
+ type="function",
219
+ function=FunctionCall(name=function_name,
220
+ arguments=json.dumps(param_dict,
221
+ ensure_ascii=False)),
222
+ )
223
+
224
+ def _get_function_calls(self, model_output: str) -> List[str]:
225
+ # Find all tool calls
226
+ matched_ranges = self.tool_call_regex.findall(model_output)
227
+ raw_tool_calls = [
228
+ match[0] if match[0] else match[1] for match in matched_ranges
229
+ ]
230
+
231
+ # Back-off strategy if no tool_call tags found
232
+ if len(raw_tool_calls) == 0:
233
+ raw_tool_calls = [model_output]
234
+
235
+ raw_function_calls = []
236
+ for tool_call in raw_tool_calls:
237
+ raw_function_calls.extend(
238
+ self.tool_call_function_regex.findall(tool_call))
239
+
240
+ function_calls = [
241
+ match[0] if match[0] else match[1] for match in raw_function_calls
242
+ ]
243
+ return function_calls
244
+
245
+ def extract_tool_calls(
246
+ self,
247
+ model_output: str,
248
+ request: ChatCompletionRequest,
249
+ ) -> ExtractedToolCallInformation:
250
+ # Quick check to avoid unnecessary processing
251
+ if self.tool_call_prefix not in model_output:
252
+ return ExtractedToolCallInformation(tools_called=False,
253
+ tool_calls=[],
254
+ content=model_output)
255
+
256
+ try:
257
+ function_calls = self._get_function_calls(model_output)
258
+ if len(function_calls) == 0:
259
+ return ExtractedToolCallInformation(tools_called=False,
260
+ tool_calls=[],
261
+ content=model_output)
262
+
263
+ tool_calls = [
264
+ self._parse_xml_function_call(function_call_str, request.tools)
265
+ for function_call_str in function_calls
266
+ ]
267
+
268
+ # Populate prev_tool_call_arr for serving layer to set finish_reason
269
+ self.prev_tool_call_arr.clear() # Clear previous calls
270
+ for tool_call in tool_calls:
271
+ if tool_call:
272
+ self.prev_tool_call_arr.append({
273
+ "name":
274
+ tool_call.function.name,
275
+ "arguments":
276
+ tool_call.function.arguments,
277
+ })
278
+
279
+ # Extract content before tool calls
280
+ content_index = model_output.find(self.tool_call_start_token)
281
+ content_index = content_index if content_index >= 0 else model_output.find(
282
+ self.tool_call_prefix)
283
+ content = model_output[:content_index] # .rstrip()
284
+
285
+ return ExtractedToolCallInformation(
286
+ tools_called=(len(tool_calls) > 0),
287
+ tool_calls=tool_calls,
288
+ content=content if content else None,
289
+ )
290
+
291
+ except Exception:
292
+ logger.exception("Error in extracting tool call from response.")
293
+ return ExtractedToolCallInformation(tools_called=False,
294
+ tool_calls=[],
295
+ content=model_output)
296
+
297
+ def extract_tool_calls_streaming(
298
+ self,
299
+ previous_text: str,
300
+ current_text: str,
301
+ delta_text: str,
302
+ previous_token_ids: Sequence[int],
303
+ current_token_ids: Sequence[int],
304
+ delta_token_ids: Sequence[int],
305
+ request: ChatCompletionRequest,
306
+ ) -> Union[DeltaMessage, None]:
307
+ # Store request for type conversion
308
+ if not previous_text:
309
+ self._reset_streaming_state()
310
+ self.streaming_request = request
311
+
312
+ # If no delta text, return None unless it's an EOS token after tool calls
313
+ if not delta_text:
314
+ # Check if this is an EOS token after all tool calls are complete
315
+ # We check for tool calls in the text even if is_tool_call_started is False
316
+ # because it might have been reset after processing all tools
317
+ if delta_token_ids and self.tool_call_end_token_id not in delta_token_ids:
318
+ # Count complete tool calls
319
+ complete_calls = len(
320
+ self.tool_call_complete_regex.findall(current_text))
321
+
322
+ # If we have completed tool calls and populated prev_tool_call_arr
323
+ if complete_calls > 0 and len(self.prev_tool_call_arr) > 0:
324
+ # Check if all tool calls are closed
325
+ open_calls = current_text.count(
326
+ self.tool_call_start_token) - current_text.count(
327
+ self.tool_call_end_token)
328
+ if open_calls == 0:
329
+ # Return empty delta message to allow finish_reason processing
330
+ return DeltaMessage(content="")
331
+ elif not self.is_tool_call_started and current_text:
332
+ # This is a regular content response that's now complete
333
+ return DeltaMessage(content="")
334
+ return None
335
+
336
+ # Update accumulated text
337
+ self.accumulated_text = current_text
338
+
339
+ # Check if we need to advance to next tool
340
+ if self.json_closed and not self.in_function:
341
+ # Check if this tool call has ended
342
+ tool_ends = current_text.count(self.tool_call_end_token)
343
+ if tool_ends > self.current_tool_index:
344
+ # This tool has ended, advance to next
345
+ self.current_tool_index += 1
346
+ self.header_sent = False
347
+ self.param_count = 0
348
+ self.json_started = False
349
+ self.json_closed = False
350
+ self.accumulated_params = {}
351
+
352
+ # Check if there are more tool calls
353
+ tool_starts = current_text.count(self.tool_call_start_token)
354
+ if self.current_tool_index >= tool_starts:
355
+ # No more tool calls
356
+ self.is_tool_call_started = False
357
+ # Continue processing next tool
358
+ return None
359
+
360
+ # Handle normal content before tool calls
361
+ if not self.is_tool_call_started:
362
+ # Check if tool call is starting
363
+ if self.tool_call_start_token_id in delta_token_ids or self.tool_call_start_token in delta_text:
364
+ self.is_tool_call_started = True
365
+ # Return any content before the tool call
366
+ if self.tool_call_start_token in delta_text:
367
+ content_before = delta_text[:delta_text.index(
368
+ self.tool_call_start_token)]
369
+ if content_before:
370
+ return DeltaMessage(content=content_before)
371
+ return None
372
+ else:
373
+ # Check if we're between tool calls - skip whitespace
374
+ if current_text.rstrip().endswith(self.tool_call_end_token):
375
+ # We just ended a tool call, skip whitespace
376
+ if delta_text.strip() == "":
377
+ return None
378
+ # Normal content, no tool call
379
+ return DeltaMessage(content=delta_text)
380
+
381
+ # Check if we're between tool calls (waiting for next one)
382
+ # Count tool calls we've seen vs processed
383
+ tool_starts_count = current_text.count(self.tool_call_start_token)
384
+ if self.current_tool_index >= tool_starts_count:
385
+ # We're past all tool calls, shouldn't be here
386
+ return None
387
+
388
+ # We're in a tool call, find the current tool call portion
389
+ # Need to find the correct tool call based on current_tool_index
390
+ tool_starts = []
391
+ idx = 0
392
+ while True:
393
+ idx = current_text.find(self.tool_call_start_token, idx)
394
+ if idx == -1:
395
+ break
396
+ tool_starts.append(idx)
397
+ idx += len(self.tool_call_start_token)
398
+
399
+ if self.current_tool_index >= len(tool_starts):
400
+ # No more tool calls to process yet
401
+ return None
402
+
403
+ tool_start_idx = tool_starts[self.current_tool_index]
404
+ # Find where this tool call ends (or current position if not ended yet)
405
+ tool_end_idx = current_text.find(self.tool_call_end_token,
406
+ tool_start_idx)
407
+ if tool_end_idx == -1:
408
+ tool_text = current_text[tool_start_idx:]
409
+ else:
410
+ tool_text = current_text[tool_start_idx:tool_end_idx +
411
+ len(self.tool_call_end_token)]
412
+
413
+ # Looking for function header
414
+ if not self.header_sent:
415
+ if self.tool_call_prefix in tool_text:
416
+ func_start = tool_text.find(self.tool_call_prefix) + len(
417
+ self.tool_call_prefix)
418
+ func_end = tool_text.find(">", func_start)
419
+
420
+ if func_end != -1:
421
+ # Found complete function name
422
+ self.current_function_name = tool_text[func_start:func_end]
423
+ self.current_tool_id = self._generate_tool_call_id()
424
+ self.header_sent = True
425
+ self.in_function = True
426
+
427
+ # IMPORTANT: Add to prev_tool_call_arr immediately when we detect a tool call
428
+ # This ensures finish_reason="tool_calls" even if parsing isn't complete
429
+ already_added = any(
430
+ tool.get("name") == self.current_function_name
431
+ for tool in self.prev_tool_call_arr)
432
+ if not already_added:
433
+ self.prev_tool_call_arr.append({
434
+ "name": self.current_function_name,
435
+ "arguments":
436
+ "{}", # Placeholder, will be updated later
437
+ })
438
+
439
+ # Send header with function info
440
+ return DeltaMessage(tool_calls=[
441
+ DeltaToolCall(
442
+ index=self.current_tool_index,
443
+ id=self.current_tool_id,
444
+ function=DeltaFunctionCall(
445
+ name=self.current_function_name, arguments=""),
446
+ type="function",
447
+ )
448
+ ])
449
+ return None
450
+
451
+ # We've sent header, now handle function body
452
+ if self.in_function:
453
+ # Send opening brace if not sent yet
454
+ if not self.json_started and self.parameter_prefix not in delta_text:
455
+ self.json_started = True
456
+ return DeltaMessage(tool_calls=[
457
+ DeltaToolCall(
458
+ index=self.current_tool_index,
459
+ function=DeltaFunctionCall(arguments="{"),
460
+ )
461
+ ])
462
+
463
+ # Make sure json_started is set if we're processing parameters
464
+ if not self.json_started:
465
+ self.json_started = True
466
+
467
+ # Check for function end in accumulated text
468
+ if not self.json_closed and self.function_end_token in tool_text:
469
+ # Close JSON
470
+ self.json_closed = True
471
+
472
+ # Extract the complete tool call to update prev_tool_call_arr with final arguments
473
+ # Find the function content
474
+ func_start = tool_text.find(self.tool_call_prefix) + len(
475
+ self.tool_call_prefix)
476
+ func_content_end = tool_text.find(self.function_end_token,
477
+ func_start)
478
+ if func_content_end != -1:
479
+ func_content = tool_text[func_start:func_content_end]
480
+ # Parse to get the complete arguments
481
+ try:
482
+ parsed_tool = self._parse_xml_function_call(
483
+ func_content, self.streaming_request.tools
484
+ if self.streaming_request else None)
485
+ if parsed_tool:
486
+ # Update existing entry in prev_tool_call_arr with complete arguments
487
+ for i, tool in enumerate(self.prev_tool_call_arr):
488
+ if tool.get(
489
+ "name") == parsed_tool.function.name:
490
+ self.prev_tool_call_arr[i][
491
+ "arguments"] = parsed_tool.function.arguments
492
+ break
493
+ except Exception:
494
+ pass # Ignore parsing errors during streaming
495
+
496
+ result = DeltaMessage(tool_calls=[
497
+ DeltaToolCall(
498
+ index=self.current_tool_index,
499
+ function=DeltaFunctionCall(arguments="}"),
500
+ )
501
+ ])
502
+
503
+ # Reset state for next tool
504
+ self.in_function = False
505
+ self.json_closed = True
506
+ self.accumulated_params = {}
507
+
508
+ return result
509
+
510
+ # Look for parameters
511
+ # Find all parameter starts
512
+ param_starts = []
513
+ idx = 0
514
+ while True:
515
+ idx = tool_text.find(self.parameter_prefix, idx)
516
+ if idx == -1:
517
+ break
518
+ param_starts.append(idx)
519
+ idx += len(self.parameter_prefix)
520
+
521
+ # Check if we should start a new parameter
522
+ if not self.in_param and self.param_count < len(param_starts):
523
+
524
+ if len(param_starts) > self.param_count:
525
+ # Process the next parameter
526
+ param_idx = param_starts[self.param_count]
527
+ param_start = param_idx + len(self.parameter_prefix)
528
+ remaining = tool_text[param_start:]
529
+
530
+ if ">" in remaining:
531
+ # We have the complete parameter name
532
+ name_end = remaining.find(">")
533
+ self.current_param_name = remaining[:name_end]
534
+
535
+ # Find the parameter value
536
+ value_start = param_start + name_end + 1
537
+ value_text = tool_text[value_start:]
538
+ if value_text.startswith("\n"):
539
+ value_text = value_text[1:]
540
+
541
+ # Find where this parameter ends
542
+ param_end_idx = value_text.find(
543
+ self.parameter_end_token)
544
+ if param_end_idx == -1:
545
+ # No closing tag, look for next parameter or function end
546
+ next_param_idx = value_text.find(
547
+ self.parameter_prefix)
548
+ func_end_idx = value_text.find(
549
+ self.function_end_token)
550
+
551
+ if next_param_idx != -1 and (func_end_idx == -1
552
+ or next_param_idx
553
+ < func_end_idx):
554
+ param_end_idx = next_param_idx
555
+ elif func_end_idx != -1:
556
+ param_end_idx = func_end_idx
557
+ else:
558
+ # Neither found, check if tool call is complete
559
+ if self.tool_call_end_token in tool_text:
560
+ # Tool call is complete, so parameter must be complete too
561
+ # Use all remaining text before function end as value
562
+ param_end_idx = len(value_text)
563
+ else:
564
+ # Still streaming, wait for more content
565
+ return None
566
+
567
+ if param_end_idx != -1:
568
+ # Complete parameter found
569
+ param_value = value_text[:param_end_idx]
570
+ if param_value.endswith("\n"):
571
+ param_value = param_value[:-1]
572
+
573
+ # Store raw value for later processing
574
+ self.accumulated_params[
575
+ self.current_param_name] = param_value
576
+
577
+ # Get parameter configuration for type conversion
578
+ param_config = self._get_arguments_config(
579
+ self.current_function_name,
580
+ self.streaming_request.tools
581
+ if self.streaming_request else None)
582
+
583
+ # Convert the parameter value to the appropriate type
584
+ converted_value = self._convert_param_value(
585
+ param_value, self.current_param_name,
586
+ param_config, self.current_function_name)
587
+
588
+ # Build JSON fragment based on the converted type
589
+ # Use json.dumps to properly serialize the value
590
+ serialized_value = json.dumps(converted_value,
591
+ ensure_ascii=False)
592
+
593
+ if self.param_count == 0:
594
+ json_fragment = f'"{self.current_param_name}": {serialized_value}'
595
+ else:
596
+ json_fragment = f', "{self.current_param_name}": {serialized_value}'
597
+
598
+ self.param_count += 1
599
+
600
+ return DeltaMessage(tool_calls=[
601
+ DeltaToolCall(
602
+ index=self.current_tool_index,
603
+ function=DeltaFunctionCall(
604
+ arguments=json_fragment),
605
+ )
606
+ ])
607
+
608
+ # Continue parameter value - Not used in the current implementation
609
+ # since we process complete parameters above
610
+ if self.in_param:
611
+ if self.parameter_end_token in delta_text:
612
+ # End of parameter
613
+ end_idx = delta_text.find(self.parameter_end_token)
614
+ value_chunk = delta_text[:end_idx]
615
+
616
+ # Skip past > if at start
617
+ if not self.current_param_value and ">" in value_chunk:
618
+ gt_idx = value_chunk.find(">")
619
+ value_chunk = value_chunk[gt_idx + 1:]
620
+
621
+ if not self.current_param_value and value_chunk.startswith(
622
+ "\n"):
623
+ value_chunk = value_chunk[1:]
624
+
625
+ # Store complete value
626
+ full_value = self.current_param_value + value_chunk
627
+ self.accumulated_params[
628
+ self.current_param_name] = full_value
629
+
630
+ # Get parameter configuration for type conversion
631
+ param_config = self._get_arguments_config(
632
+ self.current_function_name,
633
+ self.streaming_request.tools
634
+ if self.streaming_request else None)
635
+
636
+ # Convert the parameter value to the appropriate type
637
+ converted_value = self._convert_param_value(
638
+ full_value, self.current_param_name, param_config,
639
+ self.current_function_name)
640
+
641
+ # Serialize the converted value
642
+ serialized_value = json.dumps(converted_value,
643
+ ensure_ascii=False)
644
+
645
+ # Since we've been streaming the quoted version, we need to close it properly
646
+ # This is complex - for now just complete the value
647
+ self.in_param = False
648
+ self.current_param_value = ""
649
+
650
+ # Just close the current parameter string
651
+ return DeltaMessage(tool_calls=[
652
+ DeltaToolCall(
653
+ index=self.current_tool_index,
654
+ function=DeltaFunctionCall(
655
+ arguments='"'), # Close the string quote
656
+ )
657
+ ])
658
+ else:
659
+ # Continue accumulating value
660
+ value_chunk = delta_text
661
+
662
+ # Handle first chunk after param name
663
+ if not self.current_param_value and ">" in value_chunk:
664
+ gt_idx = value_chunk.find(">")
665
+ value_chunk = value_chunk[gt_idx + 1:]
666
+
667
+ if not self.current_param_value and value_chunk.startswith(
668
+ "\n"):
669
+ value_chunk = value_chunk[1:]
670
+
671
+ if value_chunk:
672
+ # Stream the escaped delta
673
+ prev_escaped = json.dumps(
674
+ self.current_param_value, ensure_ascii=False
675
+ )[1:-1] if self.current_param_value else ""
676
+ self.current_param_value += value_chunk
677
+ full_escaped = json.dumps(self.current_param_value,
678
+ ensure_ascii=False)[1:-1]
679
+ delta_escaped = full_escaped[len(prev_escaped):]
680
+
681
+ if delta_escaped:
682
+ return DeltaMessage(tool_calls=[
683
+ DeltaToolCall(
684
+ index=self.current_tool_index,
685
+ function=DeltaFunctionCall(
686
+ arguments=delta_escaped),
687
+ )
688
+ ])
689
+
690
+ return None
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|im_end|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
3
+ size 11422654
tokenizer_config.json ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ },
181
+ "151665": {
182
+ "content": "<tool_response>",
183
+ "lstrip": false,
184
+ "normalized": false,
185
+ "rstrip": false,
186
+ "single_word": false,
187
+ "special": false
188
+ },
189
+ "151666": {
190
+ "content": "</tool_response>",
191
+ "lstrip": false,
192
+ "normalized": false,
193
+ "rstrip": false,
194
+ "single_word": false,
195
+ "special": false
196
+ },
197
+ "151667": {
198
+ "content": "<think>",
199
+ "lstrip": false,
200
+ "normalized": false,
201
+ "rstrip": false,
202
+ "single_word": false,
203
+ "special": false
204
+ },
205
+ "151668": {
206
+ "content": "</think>",
207
+ "lstrip": false,
208
+ "normalized": false,
209
+ "rstrip": false,
210
+ "single_word": false,
211
+ "special": false
212
+ }
213
+ },
214
+ "additional_special_tokens": [
215
+ "<|im_start|>",
216
+ "<|im_end|>",
217
+ "<|object_ref_start|>",
218
+ "<|object_ref_end|>",
219
+ "<|box_start|>",
220
+ "<|box_end|>",
221
+ "<|quad_start|>",
222
+ "<|quad_end|>",
223
+ "<|vision_start|>",
224
+ "<|vision_end|>",
225
+ "<|vision_pad|>",
226
+ "<|image_pad|>",
227
+ "<|video_pad|>"
228
+ ],
229
+ "bos_token": null,
230
+ "clean_up_tokenization_spaces": false,
231
+ "eos_token": "<|im_end|>",
232
+ "errors": "replace",
233
+ "extra_special_tokens": {},
234
+ "model_max_length": 1048576,
235
+ "pad_token": "<|endoftext|>",
236
+ "split_special_tokens": false,
237
+ "tokenizer_class": "Qwen2Tokenizer",
238
+ "unk_token": null
239
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff