Update chat_template and tool_parser (#22)
Browse files- Update chat_template and tool_parser (864979f7d29f93cb0084800778b754c36b944b91)
Co-authored-by: Ruisheng Cao <[email protected]>
- chat_template.jinja +117 -0
- qwen3coder_tool_parser.py +320 -306
- tokenizer_config.json +1 -1
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 mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
|
| 5 |
+
{{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
|
| 6 |
+
{%- else %}
|
| 7 |
+
{{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ 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 | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
|
| 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\n' }}
|
| 102 |
+
{%- endif %}
|
| 103 |
+
{{- '<tool_response>\n' }}
|
| 104 |
+
{{- message.content }}
|
| 105 |
+
{{- '\n</tool_response>\n' }}
|
| 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 %}
|
qwen3coder_tool_parser.py
CHANGED
|
@@ -1,34 +1,30 @@
|
|
| 1 |
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
-
|
|
|
|
| 3 |
import json
|
| 4 |
-
import re
|
| 5 |
import uuid
|
| 6 |
from collections.abc import Sequence
|
| 7 |
-
from typing import
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
FunctionCall,
|
| 18 |
-
ToolCall,
|
| 19 |
-
)
|
| 20 |
from vllm.entrypoints.openai.tool_parsers.abstract_tool_parser import (
|
| 21 |
-
ToolParser,
|
| 22 |
-
ToolParserManager,
|
| 23 |
-
)
|
| 24 |
from vllm.logger import init_logger
|
| 25 |
from vllm.transformers_utils.tokenizer import AnyTokenizer
|
| 26 |
|
| 27 |
logger = init_logger(__name__)
|
| 28 |
|
| 29 |
|
| 30 |
-
@ToolParserManager.register_module("
|
| 31 |
-
class
|
|
|
|
| 32 |
def __init__(self, tokenizer: AnyTokenizer):
|
| 33 |
super().__init__(tokenizer)
|
| 34 |
|
|
@@ -52,34 +48,32 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 52 |
|
| 53 |
# Regex patterns
|
| 54 |
self.tool_call_complete_regex = re.compile(
|
| 55 |
-
r"<tool_call>(.*?)</tool_call>", re.DOTALL
|
| 56 |
-
)
|
| 57 |
self.tool_call_regex = re.compile(
|
| 58 |
-
r"<tool_call>(.*?)</tool_call>|<tool_call>(.*?)$", re.DOTALL
|
| 59 |
-
)
|
| 60 |
self.tool_call_function_regex = re.compile(
|
| 61 |
-
r"<function=(.*?)</function>|<function=(.*)$", re.DOTALL
|
| 62 |
-
)
|
| 63 |
self.tool_call_parameter_regex = re.compile(
|
| 64 |
-
r"<parameter=(.*?)
|
| 65 |
-
|
| 66 |
|
| 67 |
if not self.model_tokenizer:
|
| 68 |
raise ValueError(
|
| 69 |
"The model tokenizer must be passed to the ToolParser "
|
| 70 |
-
"constructor during construction."
|
| 71 |
-
)
|
| 72 |
|
| 73 |
-
self.tool_call_start_token_id = self.vocab.get(
|
|
|
|
| 74 |
self.tool_call_end_token_id = self.vocab.get(self.tool_call_end_token)
|
| 75 |
|
| 76 |
if self.tool_call_start_token_id is None or self.tool_call_end_token_id is None:
|
| 77 |
raise RuntimeError(
|
| 78 |
"Qwen3 XML Tool parser could not locate tool call start/end "
|
| 79 |
-
"tokens in the tokenizer!"
|
| 80 |
-
)
|
| 81 |
|
| 82 |
-
logger.info(
|
|
|
|
|
|
|
| 83 |
|
| 84 |
def _generate_tool_call_id(self) -> str:
|
| 85 |
"""Generate a unique tool call ID."""
|
|
@@ -100,130 +94,130 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 100 |
self.accumulated_text = ""
|
| 101 |
self.json_started = False
|
| 102 |
self.json_closed = False
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
self
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
hasattr(config, "function") and hasattr(config.function, "name")
|
| 113 |
-
):
|
| 114 |
-
continue
|
| 115 |
-
if config.type == "function" and config.function.name == func_name:
|
| 116 |
-
if not hasattr(config.function, "parameters"):
|
| 117 |
-
return {}
|
| 118 |
-
params = config.function.parameters
|
| 119 |
-
if isinstance(params, dict) and "properties" in params:
|
| 120 |
-
return params["properties"]
|
| 121 |
-
elif isinstance(params, dict):
|
| 122 |
-
return params
|
| 123 |
-
else:
|
| 124 |
-
return {}
|
| 125 |
-
logger.warning(f"Tool '{func_name}' is not defined in the tools list.")
|
| 126 |
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
if param_name not in param_config:
|
| 136 |
-
if param_config != {}:
|
| 137 |
-
logger.warning(
|
| 138 |
-
f"Parsed parameter '{param_name}' is not defined in the tool "
|
| 139 |
-
f"parameters for tool '{func_name}', directly returning the string value."
|
| 140 |
-
)
|
| 141 |
-
return param_value
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
)
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
)
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
)
|
| 183 |
-
return param_value == "true"
|
| 184 |
-
else:
|
| 185 |
-
if param_type == "object" or param_type.startswith("dict"):
|
| 186 |
-
try:
|
| 187 |
-
param_value = json.loads(param_value)
|
| 188 |
-
return param_value
|
| 189 |
-
except:
|
| 190 |
-
logger.warning(
|
| 191 |
-
f"Parsed value '{param_value}' of parameter '{param_name}' is not a valid JSON object in tool "
|
| 192 |
-
f"'{func_name}', will try other methods to parse it."
|
| 193 |
-
)
|
| 194 |
try:
|
| 195 |
-
param_value =
|
|
|
|
| 196 |
except:
|
| 197 |
logger.warning(
|
| 198 |
-
f"Parsed value '{param_value}' of parameter '{param_name}' cannot be
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
# Extract function name
|
| 203 |
end_index = function_call_str.index(">")
|
| 204 |
function_name = function_call_str[:end_index]
|
| 205 |
-
param_config =
|
| 206 |
-
parameters = function_call_str[end_index + 1
|
| 207 |
param_dict = {}
|
| 208 |
-
for
|
| 209 |
-
match_text = match[0] if match[0] else match[1]
|
| 210 |
idx = match_text.index(">")
|
| 211 |
param_name = match_text[:idx]
|
| 212 |
-
param_value = str(match_text[idx + 1
|
| 213 |
# Remove prefix and trailing \n
|
| 214 |
if param_value.startswith("\n"):
|
| 215 |
param_value = param_value[1:]
|
| 216 |
if param_value.endswith("\n"):
|
| 217 |
param_value = param_value[:-1]
|
| 218 |
|
| 219 |
-
param_dict[param_name] =
|
| 220 |
-
param_value, param_name, param_config, function_name
|
| 221 |
-
)
|
| 222 |
return ToolCall(
|
| 223 |
type="function",
|
| 224 |
-
function=FunctionCall(
|
| 225 |
-
|
| 226 |
-
|
| 227 |
)
|
| 228 |
|
| 229 |
def _get_function_calls(self, model_output: str) -> List[str]:
|
|
@@ -239,7 +233,8 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 239 |
|
| 240 |
raw_function_calls = []
|
| 241 |
for tool_call in raw_tool_calls:
|
| 242 |
-
raw_function_calls.extend(
|
|
|
|
| 243 |
|
| 244 |
function_calls = [
|
| 245 |
match[0] if match[0] else match[1] for match in raw_function_calls
|
|
@@ -253,16 +248,16 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 253 |
) -> ExtractedToolCallInformation:
|
| 254 |
# Quick check to avoid unnecessary processing
|
| 255 |
if self.tool_call_prefix not in model_output:
|
| 256 |
-
return ExtractedToolCallInformation(
|
| 257 |
-
|
| 258 |
-
|
| 259 |
|
| 260 |
try:
|
| 261 |
function_calls = self._get_function_calls(model_output)
|
| 262 |
if len(function_calls) == 0:
|
| 263 |
-
return ExtractedToolCallInformation(
|
| 264 |
-
|
| 265 |
-
|
| 266 |
|
| 267 |
tool_calls = [
|
| 268 |
self._parse_xml_function_call(function_call_str, request.tools)
|
|
@@ -273,20 +268,17 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 273 |
self.prev_tool_call_arr.clear() # Clear previous calls
|
| 274 |
for tool_call in tool_calls:
|
| 275 |
if tool_call:
|
| 276 |
-
self.prev_tool_call_arr.append(
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
)
|
| 282 |
|
| 283 |
# Extract content before tool calls
|
| 284 |
content_index = model_output.find(self.tool_call_start_token)
|
| 285 |
-
content_index = (
|
| 286 |
-
|
| 287 |
-
if content_index >= 0
|
| 288 |
-
else model_output.find(self.tool_call_prefix)
|
| 289 |
-
)
|
| 290 |
content = model_output[:content_index] # .rstrip()
|
| 291 |
|
| 292 |
return ExtractedToolCallInformation(
|
|
@@ -297,9 +289,9 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 297 |
|
| 298 |
except Exception:
|
| 299 |
logger.exception("Error in extracting tool call from response.")
|
| 300 |
-
return ExtractedToolCallInformation(
|
| 301 |
-
|
| 302 |
-
|
| 303 |
|
| 304 |
def extract_tool_calls_streaming(
|
| 305 |
self,
|
|
@@ -311,6 +303,11 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 311 |
delta_token_ids: Sequence[int],
|
| 312 |
request: ChatCompletionRequest,
|
| 313 |
) -> Union[DeltaMessage, None]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
# If no delta text, return None unless it's an EOS token after tool calls
|
| 315 |
if not delta_text:
|
| 316 |
# Check if this is an EOS token after all tool calls are complete
|
|
@@ -319,15 +316,14 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 319 |
if delta_token_ids and self.tool_call_end_token_id not in delta_token_ids:
|
| 320 |
# Count complete tool calls
|
| 321 |
complete_calls = len(
|
| 322 |
-
self.tool_call_complete_regex.findall(current_text)
|
| 323 |
-
)
|
| 324 |
|
| 325 |
# If we have completed tool calls and populated prev_tool_call_arr
|
| 326 |
if complete_calls > 0 and len(self.prev_tool_call_arr) > 0:
|
| 327 |
# Check if all tool calls are closed
|
| 328 |
open_calls = current_text.count(
|
| 329 |
-
self.tool_call_start_token
|
| 330 |
-
|
| 331 |
if open_calls == 0:
|
| 332 |
# Return empty delta message to allow finish_reason processing
|
| 333 |
return DeltaMessage(content="")
|
|
@@ -336,10 +332,6 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 336 |
return DeltaMessage(content="")
|
| 337 |
return None
|
| 338 |
|
| 339 |
-
# Check if this is the first call (reset state if needed)
|
| 340 |
-
if not previous_text:
|
| 341 |
-
self._reset_streaming_state()
|
| 342 |
-
|
| 343 |
# Update accumulated text
|
| 344 |
self.accumulated_text = current_text
|
| 345 |
|
|
@@ -354,6 +346,7 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 354 |
self.param_count = 0
|
| 355 |
self.json_started = False
|
| 356 |
self.json_closed = False
|
|
|
|
| 357 |
|
| 358 |
# Check if there are more tool calls
|
| 359 |
tool_starts = current_text.count(self.tool_call_start_token)
|
|
@@ -366,16 +359,12 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 366 |
# Handle normal content before tool calls
|
| 367 |
if not self.is_tool_call_started:
|
| 368 |
# Check if tool call is starting
|
| 369 |
-
if
|
| 370 |
-
self.tool_call_start_token_id in delta_token_ids
|
| 371 |
-
or self.tool_call_start_token in delta_text
|
| 372 |
-
):
|
| 373 |
self.is_tool_call_started = True
|
| 374 |
# Return any content before the tool call
|
| 375 |
if self.tool_call_start_token in delta_text:
|
| 376 |
-
content_before = delta_text[
|
| 377 |
-
|
| 378 |
-
]
|
| 379 |
if content_before:
|
| 380 |
return DeltaMessage(content=content_before)
|
| 381 |
return None
|
|
@@ -412,20 +401,19 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 412 |
|
| 413 |
tool_start_idx = tool_starts[self.current_tool_index]
|
| 414 |
# Find where this tool call ends (or current position if not ended yet)
|
| 415 |
-
tool_end_idx = current_text.find(self.tool_call_end_token,
|
|
|
|
| 416 |
if tool_end_idx == -1:
|
| 417 |
tool_text = current_text[tool_start_idx:]
|
| 418 |
else:
|
| 419 |
-
tool_text = current_text[
|
| 420 |
-
|
| 421 |
-
]
|
| 422 |
|
| 423 |
# Looking for function header
|
| 424 |
if not self.header_sent:
|
| 425 |
if self.tool_call_prefix in tool_text:
|
| 426 |
func_start = tool_text.find(self.tool_call_prefix) + len(
|
| 427 |
-
self.tool_call_prefix
|
| 428 |
-
)
|
| 429 |
func_end = tool_text.find(">", func_start)
|
| 430 |
|
| 431 |
if func_end != -1:
|
|
@@ -439,44 +427,37 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 439 |
# This ensures finish_reason="tool_calls" even if parsing isn't complete
|
| 440 |
already_added = any(
|
| 441 |
tool.get("name") == self.current_function_name
|
| 442 |
-
for tool in self.prev_tool_call_arr
|
| 443 |
-
)
|
| 444 |
if not already_added:
|
| 445 |
-
self.prev_tool_call_arr.append(
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
)
|
| 451 |
|
| 452 |
# Send header with function info
|
| 453 |
-
return DeltaMessage(
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
)
|
| 463 |
-
]
|
| 464 |
-
)
|
| 465 |
return None
|
| 466 |
|
| 467 |
# We've sent header, now handle function body
|
| 468 |
if self.in_function:
|
| 469 |
# Send opening brace if not sent yet
|
| 470 |
-
if not self.json_started and
|
| 471 |
self.json_started = True
|
| 472 |
-
return DeltaMessage(
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
]
|
| 479 |
-
)
|
| 480 |
|
| 481 |
# Make sure json_started is set if we're processing parameters
|
| 482 |
if not self.json_started:
|
|
@@ -490,58 +471,54 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 490 |
# Extract the complete tool call to update prev_tool_call_arr with final arguments
|
| 491 |
# Find the function content
|
| 492 |
func_start = tool_text.find(self.tool_call_prefix) + len(
|
| 493 |
-
self.tool_call_prefix
|
| 494 |
-
|
| 495 |
-
|
| 496 |
if func_content_end != -1:
|
| 497 |
func_content = tool_text[func_start:func_content_end]
|
| 498 |
# Parse to get the complete arguments
|
| 499 |
try:
|
| 500 |
parsed_tool = self._parse_xml_function_call(
|
| 501 |
-
func_content,
|
| 502 |
-
|
| 503 |
if parsed_tool:
|
| 504 |
# Update existing entry in prev_tool_call_arr with complete arguments
|
| 505 |
for i, tool in enumerate(self.prev_tool_call_arr):
|
| 506 |
-
if tool.get(
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
break
|
| 511 |
except Exception:
|
| 512 |
pass # Ignore parsing errors during streaming
|
| 513 |
|
| 514 |
-
result = DeltaMessage(
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
]
|
| 521 |
-
)
|
| 522 |
|
| 523 |
# Reset state for next tool
|
| 524 |
self.in_function = False
|
| 525 |
self.json_closed = True
|
|
|
|
| 526 |
|
| 527 |
return result
|
| 528 |
|
| 529 |
# Look for parameters
|
| 530 |
-
#
|
| 531 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 532 |
|
| 533 |
# Check if we should start a new parameter
|
| 534 |
-
if not self.in_param and self.param_count <
|
| 535 |
-
# Find the unprocessed parameter
|
| 536 |
-
# Count parameter starts
|
| 537 |
-
param_starts = []
|
| 538 |
-
idx = 0
|
| 539 |
-
while True:
|
| 540 |
-
idx = tool_text.find(self.parameter_prefix, idx)
|
| 541 |
-
if idx == -1:
|
| 542 |
-
break
|
| 543 |
-
param_starts.append(idx)
|
| 544 |
-
idx += len(self.parameter_prefix)
|
| 545 |
|
| 546 |
if len(param_starts) > self.param_count:
|
| 547 |
# Process the next parameter
|
|
@@ -561,45 +538,74 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 561 |
value_text = value_text[1:]
|
| 562 |
|
| 563 |
# Find where this parameter ends
|
| 564 |
-
param_end_idx = value_text.find(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 565 |
if param_end_idx != -1:
|
| 566 |
# Complete parameter found
|
| 567 |
param_value = value_text[:param_end_idx]
|
| 568 |
if param_value.endswith("\n"):
|
| 569 |
param_value = param_value[:-1]
|
| 570 |
|
| 571 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 572 |
if self.param_count == 0:
|
| 573 |
-
json_fragment =
|
| 574 |
-
'"'
|
| 575 |
-
+ self.current_param_name
|
| 576 |
-
+ '": "'
|
| 577 |
-
+ json.dumps(param_value)[1:-1]
|
| 578 |
-
+ '"'
|
| 579 |
-
)
|
| 580 |
else:
|
| 581 |
-
json_fragment =
|
| 582 |
-
', "'
|
| 583 |
-
+ self.current_param_name
|
| 584 |
-
+ '": "'
|
| 585 |
-
+ json.dumps(param_value)[1:-1]
|
| 586 |
-
+ '"'
|
| 587 |
-
)
|
| 588 |
|
| 589 |
self.param_count += 1
|
| 590 |
|
| 591 |
-
return DeltaMessage(
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
# Continue parameter value
|
| 603 |
if self.in_param:
|
| 604 |
if self.parameter_end_token in delta_text:
|
| 605 |
# End of parameter
|
|
@@ -609,34 +615,45 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 609 |
# Skip past > if at start
|
| 610 |
if not self.current_param_value and ">" in value_chunk:
|
| 611 |
gt_idx = value_chunk.find(">")
|
| 612 |
-
value_chunk = value_chunk[gt_idx + 1
|
| 613 |
|
| 614 |
-
if not self.current_param_value and value_chunk.startswith(
|
|
|
|
| 615 |
value_chunk = value_chunk[1:]
|
| 616 |
|
| 617 |
-
#
|
| 618 |
full_value = self.current_param_value + value_chunk
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 627 |
self.in_param = False
|
| 628 |
self.current_param_value = ""
|
| 629 |
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
]
|
| 639 |
-
)
|
| 640 |
else:
|
| 641 |
# Continue accumulating value
|
| 642 |
value_chunk = delta_text
|
|
@@ -644,32 +661,29 @@ class Qwen3XMLToolParser(ToolParser):
|
|
| 644 |
# Handle first chunk after param name
|
| 645 |
if not self.current_param_value and ">" in value_chunk:
|
| 646 |
gt_idx = value_chunk.find(">")
|
| 647 |
-
value_chunk = value_chunk[gt_idx + 1
|
| 648 |
|
| 649 |
-
if not self.current_param_value and value_chunk.startswith(
|
|
|
|
| 650 |
value_chunk = value_chunk[1:]
|
| 651 |
|
| 652 |
if value_chunk:
|
| 653 |
# Stream the escaped delta
|
| 654 |
-
prev_escaped = (
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
else ""
|
| 658 |
-
)
|
| 659 |
self.current_param_value += value_chunk
|
| 660 |
-
full_escaped = json.dumps(self.current_param_value
|
| 661 |
-
|
|
|
|
| 662 |
|
| 663 |
if delta_escaped:
|
| 664 |
-
return DeltaMessage(
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
)
|
| 672 |
-
]
|
| 673 |
-
)
|
| 674 |
|
| 675 |
return None
|
|
|
|
| 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 |
|
|
|
|
| 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."""
|
|
|
|
| 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 |
+
float_param_value = float(param_value)
|
| 160 |
+
param_value = float_param_value if float_param_value - int(
|
| 161 |
+
float_param_value) != 0 else int(float_param_value)
|
| 162 |
+
except:
|
| 163 |
+
logger.warning(
|
| 164 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' is not a float in tool "
|
| 165 |
+
f"'{func_name}', degenerating to string.")
|
| 166 |
+
return param_value
|
| 167 |
+
elif param_type in ["boolean", "bool", "binary"]:
|
| 168 |
+
param_value = param_value.lower()
|
| 169 |
+
if param_value not in ["true", "false"]:
|
| 170 |
+
logger.warning(
|
| 171 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' is not a boolean (`true` of `false`) in tool '{func_name}', degenerating to false."
|
| 172 |
+
)
|
| 173 |
+
return param_value == "true"
|
| 174 |
+
else:
|
| 175 |
+
if param_type in ["object", "array", "arr"
|
| 176 |
+
] or param_type.startswith(
|
| 177 |
+
"dict") or param_type.startswith("list"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
try:
|
| 179 |
+
param_value = json.loads(param_value)
|
| 180 |
+
return param_value
|
| 181 |
except:
|
| 182 |
logger.warning(
|
| 183 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' cannot be parsed with json.loads in tool "
|
| 184 |
+
f"'{func_name}', will try other methods to parse it.")
|
| 185 |
+
try:
|
| 186 |
+
param_value = ast.literal_eval(param_value) # safer
|
| 187 |
+
except:
|
| 188 |
+
logger.warning(
|
| 189 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' cannot be converted via Python `ast.literal_eval()` in tool '{func_name}', degenerating to string."
|
| 190 |
+
)
|
| 191 |
+
return param_value
|
| 192 |
+
|
| 193 |
+
def _parse_xml_function_call(
|
| 194 |
+
self, function_call_str: str,
|
| 195 |
+
tools: Optional[list[ChatCompletionToolsParam]]
|
| 196 |
+
) -> Optional[ToolCall]:
|
| 197 |
|
| 198 |
# Extract function name
|
| 199 |
end_index = function_call_str.index(">")
|
| 200 |
function_name = function_call_str[:end_index]
|
| 201 |
+
param_config = self._get_arguments_config(function_name, tools)
|
| 202 |
+
parameters = function_call_str[end_index + 1:]
|
| 203 |
param_dict = {}
|
| 204 |
+
for match_text in self.tool_call_parameter_regex.findall(parameters):
|
|
|
|
| 205 |
idx = match_text.index(">")
|
| 206 |
param_name = match_text[:idx]
|
| 207 |
+
param_value = str(match_text[idx + 1:])
|
| 208 |
# Remove prefix and trailing \n
|
| 209 |
if param_value.startswith("\n"):
|
| 210 |
param_value = param_value[1:]
|
| 211 |
if param_value.endswith("\n"):
|
| 212 |
param_value = param_value[:-1]
|
| 213 |
|
| 214 |
+
param_dict[param_name] = self._convert_param_value(
|
| 215 |
+
param_value, param_name, param_config, function_name)
|
|
|
|
| 216 |
return ToolCall(
|
| 217 |
type="function",
|
| 218 |
+
function=FunctionCall(name=function_name,
|
| 219 |
+
arguments=json.dumps(param_dict,
|
| 220 |
+
ensure_ascii=False)),
|
| 221 |
)
|
| 222 |
|
| 223 |
def _get_function_calls(self, model_output: str) -> List[str]:
|
|
|
|
| 233 |
|
| 234 |
raw_function_calls = []
|
| 235 |
for tool_call in raw_tool_calls:
|
| 236 |
+
raw_function_calls.extend(
|
| 237 |
+
self.tool_call_function_regex.findall(tool_call))
|
| 238 |
|
| 239 |
function_calls = [
|
| 240 |
match[0] if match[0] else match[1] for match in raw_function_calls
|
|
|
|
| 248 |
) -> ExtractedToolCallInformation:
|
| 249 |
# Quick check to avoid unnecessary processing
|
| 250 |
if self.tool_call_prefix not in model_output:
|
| 251 |
+
return ExtractedToolCallInformation(tools_called=False,
|
| 252 |
+
tool_calls=[],
|
| 253 |
+
content=model_output)
|
| 254 |
|
| 255 |
try:
|
| 256 |
function_calls = self._get_function_calls(model_output)
|
| 257 |
if len(function_calls) == 0:
|
| 258 |
+
return ExtractedToolCallInformation(tools_called=False,
|
| 259 |
+
tool_calls=[],
|
| 260 |
+
content=model_output)
|
| 261 |
|
| 262 |
tool_calls = [
|
| 263 |
self._parse_xml_function_call(function_call_str, request.tools)
|
|
|
|
| 268 |
self.prev_tool_call_arr.clear() # Clear previous calls
|
| 269 |
for tool_call in tool_calls:
|
| 270 |
if tool_call:
|
| 271 |
+
self.prev_tool_call_arr.append({
|
| 272 |
+
"name":
|
| 273 |
+
tool_call.function.name,
|
| 274 |
+
"arguments":
|
| 275 |
+
tool_call.function.arguments,
|
| 276 |
+
})
|
| 277 |
|
| 278 |
# Extract content before tool calls
|
| 279 |
content_index = model_output.find(self.tool_call_start_token)
|
| 280 |
+
content_index = content_index if content_index >= 0 else model_output.find(
|
| 281 |
+
self.tool_call_prefix)
|
|
|
|
|
|
|
|
|
|
| 282 |
content = model_output[:content_index] # .rstrip()
|
| 283 |
|
| 284 |
return ExtractedToolCallInformation(
|
|
|
|
| 289 |
|
| 290 |
except Exception:
|
| 291 |
logger.exception("Error in extracting tool call from response.")
|
| 292 |
+
return ExtractedToolCallInformation(tools_called=False,
|
| 293 |
+
tool_calls=[],
|
| 294 |
+
content=model_output)
|
| 295 |
|
| 296 |
def extract_tool_calls_streaming(
|
| 297 |
self,
|
|
|
|
| 303 |
delta_token_ids: Sequence[int],
|
| 304 |
request: ChatCompletionRequest,
|
| 305 |
) -> Union[DeltaMessage, None]:
|
| 306 |
+
# Store request for type conversion
|
| 307 |
+
if not previous_text:
|
| 308 |
+
self._reset_streaming_state()
|
| 309 |
+
self.streaming_request = request
|
| 310 |
+
|
| 311 |
# If no delta text, return None unless it's an EOS token after tool calls
|
| 312 |
if not delta_text:
|
| 313 |
# Check if this is an EOS token after all tool calls are complete
|
|
|
|
| 316 |
if delta_token_ids and self.tool_call_end_token_id not in delta_token_ids:
|
| 317 |
# Count complete tool calls
|
| 318 |
complete_calls = len(
|
| 319 |
+
self.tool_call_complete_regex.findall(current_text))
|
|
|
|
| 320 |
|
| 321 |
# If we have completed tool calls and populated prev_tool_call_arr
|
| 322 |
if complete_calls > 0 and len(self.prev_tool_call_arr) > 0:
|
| 323 |
# Check if all tool calls are closed
|
| 324 |
open_calls = current_text.count(
|
| 325 |
+
self.tool_call_start_token) - current_text.count(
|
| 326 |
+
self.tool_call_end_token)
|
| 327 |
if open_calls == 0:
|
| 328 |
# Return empty delta message to allow finish_reason processing
|
| 329 |
return DeltaMessage(content="")
|
|
|
|
| 332 |
return DeltaMessage(content="")
|
| 333 |
return None
|
| 334 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
# Update accumulated text
|
| 336 |
self.accumulated_text = current_text
|
| 337 |
|
|
|
|
| 346 |
self.param_count = 0
|
| 347 |
self.json_started = False
|
| 348 |
self.json_closed = False
|
| 349 |
+
self.accumulated_params = {}
|
| 350 |
|
| 351 |
# Check if there are more tool calls
|
| 352 |
tool_starts = current_text.count(self.tool_call_start_token)
|
|
|
|
| 359 |
# Handle normal content before tool calls
|
| 360 |
if not self.is_tool_call_started:
|
| 361 |
# Check if tool call is starting
|
| 362 |
+
if self.tool_call_start_token_id in delta_token_ids or self.tool_call_start_token in delta_text:
|
|
|
|
|
|
|
|
|
|
| 363 |
self.is_tool_call_started = True
|
| 364 |
# Return any content before the tool call
|
| 365 |
if self.tool_call_start_token in delta_text:
|
| 366 |
+
content_before = delta_text[:delta_text.index(
|
| 367 |
+
self.tool_call_start_token)]
|
|
|
|
| 368 |
if content_before:
|
| 369 |
return DeltaMessage(content=content_before)
|
| 370 |
return None
|
|
|
|
| 401 |
|
| 402 |
tool_start_idx = tool_starts[self.current_tool_index]
|
| 403 |
# Find where this tool call ends (or current position if not ended yet)
|
| 404 |
+
tool_end_idx = current_text.find(self.tool_call_end_token,
|
| 405 |
+
tool_start_idx)
|
| 406 |
if tool_end_idx == -1:
|
| 407 |
tool_text = current_text[tool_start_idx:]
|
| 408 |
else:
|
| 409 |
+
tool_text = current_text[tool_start_idx:tool_end_idx +
|
| 410 |
+
len(self.tool_call_end_token)]
|
|
|
|
| 411 |
|
| 412 |
# Looking for function header
|
| 413 |
if not self.header_sent:
|
| 414 |
if self.tool_call_prefix in tool_text:
|
| 415 |
func_start = tool_text.find(self.tool_call_prefix) + len(
|
| 416 |
+
self.tool_call_prefix)
|
|
|
|
| 417 |
func_end = tool_text.find(">", func_start)
|
| 418 |
|
| 419 |
if func_end != -1:
|
|
|
|
| 427 |
# This ensures finish_reason="tool_calls" even if parsing isn't complete
|
| 428 |
already_added = any(
|
| 429 |
tool.get("name") == self.current_function_name
|
| 430 |
+
for tool in self.prev_tool_call_arr)
|
|
|
|
| 431 |
if not already_added:
|
| 432 |
+
self.prev_tool_call_arr.append({
|
| 433 |
+
"name": self.current_function_name,
|
| 434 |
+
"arguments":
|
| 435 |
+
"{}", # Placeholder, will be updated later
|
| 436 |
+
})
|
|
|
|
| 437 |
|
| 438 |
# Send header with function info
|
| 439 |
+
return DeltaMessage(tool_calls=[
|
| 440 |
+
DeltaToolCall(
|
| 441 |
+
index=self.current_tool_index,
|
| 442 |
+
id=self.current_tool_id,
|
| 443 |
+
function=DeltaFunctionCall(
|
| 444 |
+
name=self.current_function_name, arguments=""),
|
| 445 |
+
type="function",
|
| 446 |
+
)
|
| 447 |
+
])
|
|
|
|
|
|
|
|
|
|
| 448 |
return None
|
| 449 |
|
| 450 |
# We've sent header, now handle function body
|
| 451 |
if self.in_function:
|
| 452 |
# Send opening brace if not sent yet
|
| 453 |
+
if not self.json_started and self.parameter_prefix not in delta_text:
|
| 454 |
self.json_started = True
|
| 455 |
+
return DeltaMessage(tool_calls=[
|
| 456 |
+
DeltaToolCall(
|
| 457 |
+
index=self.current_tool_index,
|
| 458 |
+
function=DeltaFunctionCall(arguments="{"),
|
| 459 |
+
)
|
| 460 |
+
])
|
|
|
|
|
|
|
| 461 |
|
| 462 |
# Make sure json_started is set if we're processing parameters
|
| 463 |
if not self.json_started:
|
|
|
|
| 471 |
# Extract the complete tool call to update prev_tool_call_arr with final arguments
|
| 472 |
# Find the function content
|
| 473 |
func_start = tool_text.find(self.tool_call_prefix) + len(
|
| 474 |
+
self.tool_call_prefix)
|
| 475 |
+
func_content_end = tool_text.find(self.function_end_token,
|
| 476 |
+
func_start)
|
| 477 |
if func_content_end != -1:
|
| 478 |
func_content = tool_text[func_start:func_content_end]
|
| 479 |
# Parse to get the complete arguments
|
| 480 |
try:
|
| 481 |
parsed_tool = self._parse_xml_function_call(
|
| 482 |
+
func_content, self.streaming_request.tools
|
| 483 |
+
if self.streaming_request else None)
|
| 484 |
if parsed_tool:
|
| 485 |
# Update existing entry in prev_tool_call_arr with complete arguments
|
| 486 |
for i, tool in enumerate(self.prev_tool_call_arr):
|
| 487 |
+
if tool.get(
|
| 488 |
+
"name") == parsed_tool.function.name:
|
| 489 |
+
self.prev_tool_call_arr[i][
|
| 490 |
+
"arguments"] = parsed_tool.function.arguments
|
| 491 |
break
|
| 492 |
except Exception:
|
| 493 |
pass # Ignore parsing errors during streaming
|
| 494 |
|
| 495 |
+
result = DeltaMessage(tool_calls=[
|
| 496 |
+
DeltaToolCall(
|
| 497 |
+
index=self.current_tool_index,
|
| 498 |
+
function=DeltaFunctionCall(arguments="}"),
|
| 499 |
+
)
|
| 500 |
+
])
|
|
|
|
|
|
|
| 501 |
|
| 502 |
# Reset state for next tool
|
| 503 |
self.in_function = False
|
| 504 |
self.json_closed = True
|
| 505 |
+
self.accumulated_params = {}
|
| 506 |
|
| 507 |
return result
|
| 508 |
|
| 509 |
# Look for parameters
|
| 510 |
+
# Find all parameter starts
|
| 511 |
+
param_starts = []
|
| 512 |
+
idx = 0
|
| 513 |
+
while True:
|
| 514 |
+
idx = tool_text.find(self.parameter_prefix, idx)
|
| 515 |
+
if idx == -1:
|
| 516 |
+
break
|
| 517 |
+
param_starts.append(idx)
|
| 518 |
+
idx += len(self.parameter_prefix)
|
| 519 |
|
| 520 |
# Check if we should start a new parameter
|
| 521 |
+
if not self.in_param and self.param_count < len(param_starts):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
|
| 523 |
if len(param_starts) > self.param_count:
|
| 524 |
# Process the next parameter
|
|
|
|
| 538 |
value_text = value_text[1:]
|
| 539 |
|
| 540 |
# Find where this parameter ends
|
| 541 |
+
param_end_idx = value_text.find(
|
| 542 |
+
self.parameter_end_token)
|
| 543 |
+
if param_end_idx == -1:
|
| 544 |
+
# No closing tag, look for next parameter or function end
|
| 545 |
+
next_param_idx = value_text.find(
|
| 546 |
+
self.parameter_prefix)
|
| 547 |
+
func_end_idx = value_text.find(
|
| 548 |
+
self.function_end_token)
|
| 549 |
+
|
| 550 |
+
if next_param_idx != -1 and (func_end_idx == -1
|
| 551 |
+
or next_param_idx
|
| 552 |
+
< func_end_idx):
|
| 553 |
+
param_end_idx = next_param_idx
|
| 554 |
+
elif func_end_idx != -1:
|
| 555 |
+
param_end_idx = func_end_idx
|
| 556 |
+
else:
|
| 557 |
+
# Neither found, check if tool call is complete
|
| 558 |
+
if self.tool_call_end_token in tool_text:
|
| 559 |
+
# Tool call is complete, so parameter must be complete too
|
| 560 |
+
# Use all remaining text before function end as value
|
| 561 |
+
param_end_idx = len(value_text)
|
| 562 |
+
else:
|
| 563 |
+
# Still streaming, wait for more content
|
| 564 |
+
return None
|
| 565 |
+
|
| 566 |
if param_end_idx != -1:
|
| 567 |
# Complete parameter found
|
| 568 |
param_value = value_text[:param_end_idx]
|
| 569 |
if param_value.endswith("\n"):
|
| 570 |
param_value = param_value[:-1]
|
| 571 |
|
| 572 |
+
# Store raw value for later processing
|
| 573 |
+
self.accumulated_params[
|
| 574 |
+
self.current_param_name] = param_value
|
| 575 |
+
|
| 576 |
+
# Get parameter configuration for type conversion
|
| 577 |
+
param_config = self._get_arguments_config(
|
| 578 |
+
self.current_function_name,
|
| 579 |
+
self.streaming_request.tools
|
| 580 |
+
if self.streaming_request else None)
|
| 581 |
+
|
| 582 |
+
# Convert the parameter value to the appropriate type
|
| 583 |
+
converted_value = self._convert_param_value(
|
| 584 |
+
param_value, self.current_param_name,
|
| 585 |
+
param_config, self.current_function_name)
|
| 586 |
+
|
| 587 |
+
# Build JSON fragment based on the converted type
|
| 588 |
+
# Use json.dumps to properly serialize the value
|
| 589 |
+
serialized_value = json.dumps(converted_value,
|
| 590 |
+
ensure_ascii=False)
|
| 591 |
+
|
| 592 |
if self.param_count == 0:
|
| 593 |
+
json_fragment = f'"{self.current_param_name}": {serialized_value}'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 594 |
else:
|
| 595 |
+
json_fragment = f', "{self.current_param_name}": {serialized_value}'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 596 |
|
| 597 |
self.param_count += 1
|
| 598 |
|
| 599 |
+
return DeltaMessage(tool_calls=[
|
| 600 |
+
DeltaToolCall(
|
| 601 |
+
index=self.current_tool_index,
|
| 602 |
+
function=DeltaFunctionCall(
|
| 603 |
+
arguments=json_fragment),
|
| 604 |
+
)
|
| 605 |
+
])
|
| 606 |
+
|
| 607 |
+
# Continue parameter value - Not used in the current implementation
|
| 608 |
+
# since we process complete parameters above
|
|
|
|
|
|
|
| 609 |
if self.in_param:
|
| 610 |
if self.parameter_end_token in delta_text:
|
| 611 |
# End of parameter
|
|
|
|
| 615 |
# Skip past > if at start
|
| 616 |
if not self.current_param_value and ">" in value_chunk:
|
| 617 |
gt_idx = value_chunk.find(">")
|
| 618 |
+
value_chunk = value_chunk[gt_idx + 1:]
|
| 619 |
|
| 620 |
+
if not self.current_param_value and value_chunk.startswith(
|
| 621 |
+
"\n"):
|
| 622 |
value_chunk = value_chunk[1:]
|
| 623 |
|
| 624 |
+
# Store complete value
|
| 625 |
full_value = self.current_param_value + value_chunk
|
| 626 |
+
self.accumulated_params[
|
| 627 |
+
self.current_param_name] = full_value
|
| 628 |
+
|
| 629 |
+
# Get parameter configuration for type conversion
|
| 630 |
+
param_config = self._get_arguments_config(
|
| 631 |
+
self.current_function_name,
|
| 632 |
+
self.streaming_request.tools
|
| 633 |
+
if self.streaming_request else None)
|
| 634 |
+
|
| 635 |
+
# Convert the parameter value to the appropriate type
|
| 636 |
+
converted_value = self._convert_param_value(
|
| 637 |
+
full_value, self.current_param_name, param_config,
|
| 638 |
+
self.current_function_name)
|
| 639 |
+
|
| 640 |
+
# Serialize the converted value
|
| 641 |
+
serialized_value = json.dumps(converted_value,
|
| 642 |
+
ensure_ascii=False)
|
| 643 |
+
|
| 644 |
+
# Since we've been streaming the quoted version, we need to close it properly
|
| 645 |
+
# This is complex - for now just complete the value
|
| 646 |
self.in_param = False
|
| 647 |
self.current_param_value = ""
|
| 648 |
|
| 649 |
+
# Just close the current parameter string
|
| 650 |
+
return DeltaMessage(tool_calls=[
|
| 651 |
+
DeltaToolCall(
|
| 652 |
+
index=self.current_tool_index,
|
| 653 |
+
function=DeltaFunctionCall(
|
| 654 |
+
arguments='"'), # Close the string quote
|
| 655 |
+
)
|
| 656 |
+
])
|
|
|
|
|
|
|
| 657 |
else:
|
| 658 |
# Continue accumulating value
|
| 659 |
value_chunk = delta_text
|
|
|
|
| 661 |
# Handle first chunk after param name
|
| 662 |
if not self.current_param_value and ">" in value_chunk:
|
| 663 |
gt_idx = value_chunk.find(">")
|
| 664 |
+
value_chunk = value_chunk[gt_idx + 1:]
|
| 665 |
|
| 666 |
+
if not self.current_param_value and value_chunk.startswith(
|
| 667 |
+
"\n"):
|
| 668 |
value_chunk = value_chunk[1:]
|
| 669 |
|
| 670 |
if value_chunk:
|
| 671 |
# Stream the escaped delta
|
| 672 |
+
prev_escaped = json.dumps(
|
| 673 |
+
self.current_param_value, ensure_ascii=False
|
| 674 |
+
)[1:-1] if self.current_param_value else ""
|
|
|
|
|
|
|
| 675 |
self.current_param_value += value_chunk
|
| 676 |
+
full_escaped = json.dumps(self.current_param_value,
|
| 677 |
+
ensure_ascii=False)[1:-1]
|
| 678 |
+
delta_escaped = full_escaped[len(prev_escaped):]
|
| 679 |
|
| 680 |
if delta_escaped:
|
| 681 |
+
return DeltaMessage(tool_calls=[
|
| 682 |
+
DeltaToolCall(
|
| 683 |
+
index=self.current_tool_index,
|
| 684 |
+
function=DeltaFunctionCall(
|
| 685 |
+
arguments=delta_escaped),
|
| 686 |
+
)
|
| 687 |
+
])
|
|
|
|
|
|
|
|
|
|
| 688 |
|
| 689 |
return None
|
tokenizer_config.json
CHANGED
|
@@ -226,7 +226,7 @@
|
|
| 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 mapping %}\n {{- '\\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}\n {%- else %}\n {{-'\\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ 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\\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 | tojson | safe if args_value is mapping else args_value | string %}\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' }}\n {%- endif %}\n {{- '<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>\\n' }}\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 %}\n",
|
| 230 |
"clean_up_tokenization_spaces": false,
|
| 231 |
"eos_token": "<|im_end|>",
|
| 232 |
"errors": "replace",
|
|
|
|
| 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 mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}\n {{- '\\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}\n {%- else %}\n {{-'\\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ 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 | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}\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' }}\n {%- endif %}\n {{- '<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>\\n' }}\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 %}\n",
|
| 230 |
"clean_up_tokenization_spaces": false,
|
| 231 |
"eos_token": "<|im_end|>",
|
| 232 |
"errors": "replace",
|