[Frontend] Support strict mode for tool calling (#45003)
Signed-off-by: chaunceyjiang <chaunceyjiang@gmail.com> Co-authored-by: cjackal <44624812+cjackal@users.noreply.github.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
cjackal
mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent
bd59c913bc
commit
2043258dec
@@ -119,8 +119,8 @@ _TOOL_PARSERS_TO_REGISTER = {
|
||||
"LongcatFlashToolParser",
|
||||
),
|
||||
"mimo": (
|
||||
"qwen3xml_tool_parser",
|
||||
"Qwen3XMLToolParser",
|
||||
"qwen3coder_tool_parser",
|
||||
"Qwen3CoderToolParser",
|
||||
),
|
||||
"minimax_m2": (
|
||||
"minimax_m2_tool_parser",
|
||||
@@ -159,8 +159,8 @@ _TOOL_PARSERS_TO_REGISTER = {
|
||||
"Qwen3CoderToolParser",
|
||||
),
|
||||
"qwen3_xml": (
|
||||
"qwen3xml_tool_parser",
|
||||
"Qwen3XMLToolParser",
|
||||
"qwen3coder_tool_parser",
|
||||
"Qwen3CoderToolParser",
|
||||
),
|
||||
"seed_oss": (
|
||||
"seed_oss_tool_parser",
|
||||
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import os
|
||||
from collections.abc import Callable, Sequence
|
||||
from functools import cached_property
|
||||
from typing import Any
|
||||
|
||||
from openai.types.responses import (
|
||||
ResponseFormatTextJSONSchemaConfig,
|
||||
@@ -13,8 +14,8 @@ from openai.types.responses import (
|
||||
)
|
||||
from openai.types.responses.function_tool import FunctionTool
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionNamedToolChoiceParam,
|
||||
ChatCompletionRequest,
|
||||
ChatCompletionToolsParam,
|
||||
)
|
||||
@@ -25,7 +26,6 @@ from vllm.entrypoints.openai.engine.protocol import (
|
||||
from vllm.entrypoints.openai.responses.protocol import (
|
||||
ResponsesRequest,
|
||||
)
|
||||
from vllm.envs import VLLM_ENFORCE_STRICT_TOOL_CALLING
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import (
|
||||
StructuredOutputsParams,
|
||||
@@ -57,6 +57,17 @@ class ToolParser:
|
||||
# extract_tool_calls / extract_tool_calls_streaming methods for
|
||||
# required/named tool_choice, treating them the same as "auto".
|
||||
supports_required_and_named: bool = True
|
||||
# xgrammar builtin structural tag model key. Subclasses set this when
|
||||
# their parsed tool-call syntax matches a builtin xgrammar format.
|
||||
structural_tag_model: str | None = None
|
||||
|
||||
def __init_subclass__(cls, **kwargs: Any) -> None:
|
||||
super().__init_subclass__(**kwargs)
|
||||
if (
|
||||
cls.structural_tag_model is not None
|
||||
and envs.VLLM_ENFORCE_STRICT_TOOL_CALLING
|
||||
):
|
||||
cls.supports_required_and_named = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -112,32 +123,16 @@ class ToolParser:
|
||||
if not request.tools:
|
||||
return request
|
||||
|
||||
# Step 1 (highest priority for ChatCompletionRequest): apply
|
||||
# vLLM-owned structural tag support for model-specific tool formats.
|
||||
# Set structured output params when tool constraints are derived from
|
||||
# the tool schema. Unified parsers handle model-specific structural
|
||||
# tags before calling into the tool parser.
|
||||
structured_outputs = getattr(request, "structured_outputs", None)
|
||||
if (
|
||||
isinstance(request, ChatCompletionRequest)
|
||||
and VLLM_ENFORCE_STRICT_TOOL_CALLING
|
||||
structured_outputs is not None
|
||||
and structured_outputs.structural_tag is not None
|
||||
):
|
||||
need_tool_calling = (
|
||||
request.tool_choice == "auto"
|
||||
or request.tool_choice == "required"
|
||||
or isinstance(request.tool_choice, ChatCompletionNamedToolChoiceParam)
|
||||
)
|
||||
if need_tool_calling:
|
||||
structure_tag = self.get_structural_tag(request)
|
||||
if structure_tag is not None:
|
||||
if request.structured_outputs is None:
|
||||
request.structured_outputs = StructuredOutputsParams(
|
||||
structural_tag=json.dumps(structure_tag.model_dump()),
|
||||
)
|
||||
else:
|
||||
request.structured_outputs.structural_tag = json.dumps(
|
||||
structure_tag.model_dump()
|
||||
)
|
||||
return request
|
||||
return request
|
||||
|
||||
# Step 2: set structured output params when tool constraints are
|
||||
# derived from the tool schema.
|
||||
json_schema_from_tool = get_json_schema_from_tools(
|
||||
tool_choice=request.tool_choice, tools=request.tools
|
||||
)
|
||||
@@ -169,8 +164,21 @@ class ToolParser:
|
||||
|
||||
return request
|
||||
|
||||
def get_structural_tag(self, request: ChatCompletionRequest):
|
||||
return None
|
||||
def get_structural_tag(
|
||||
self, request: ChatCompletionRequest, *, reasoning: bool = False
|
||||
):
|
||||
if self.structural_tag_model is None:
|
||||
return None
|
||||
if not envs.VLLM_ENFORCE_STRICT_TOOL_CALLING:
|
||||
return None
|
||||
from vllm.tool_parsers.structural_tag_registry import get_model_structural_tag
|
||||
|
||||
return get_model_structural_tag(
|
||||
model=self.structural_tag_model,
|
||||
tools=request.tools,
|
||||
tool_choice=request.tool_choice,
|
||||
reasoning=reasoning,
|
||||
)
|
||||
|
||||
def extract_tool_calls(
|
||||
self, model_output: str, request: ChatCompletionRequest
|
||||
|
||||
@@ -25,6 +25,8 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class DeepSeekV31ToolParser(ToolParser):
|
||||
structural_tag_model = "deepseek_v3_1"
|
||||
|
||||
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
|
||||
super().__init__(tokenizer, tools)
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ class DeepSeekV32ToolParser(ToolParser):
|
||||
|
||||
tool_call_start_token: str = "<|DSML|function_calls>"
|
||||
tool_call_end_token: str = "</|DSML|function_calls>"
|
||||
structural_tag_model = "deepseek_v3_2"
|
||||
|
||||
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
|
||||
super().__init__(tokenizer, tools)
|
||||
|
||||
@@ -28,6 +28,8 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class DeepSeekV3ToolParser(ToolParser):
|
||||
structural_tag_model = "deepseek_r1"
|
||||
|
||||
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
|
||||
super().__init__(tokenizer, tools)
|
||||
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionRequest,
|
||||
)
|
||||
from vllm.tool_parsers.deepseekv32_tool_parser import DeepSeekV32ToolParser
|
||||
from vllm.tool_parsers.structural_tag_registry import (
|
||||
get_enable_structured_outputs_in_reasoning,
|
||||
get_model_structural_tag,
|
||||
)
|
||||
|
||||
|
||||
class DeepSeekV4ToolParser(DeepSeekV32ToolParser):
|
||||
@@ -21,11 +14,4 @@ class DeepSeekV4ToolParser(DeepSeekV32ToolParser):
|
||||
|
||||
tool_call_start_token: str = "<|DSML|tool_calls>"
|
||||
tool_call_end_token: str = "</|DSML|tool_calls>"
|
||||
|
||||
def get_structural_tag(self, request: ChatCompletionRequest):
|
||||
return get_model_structural_tag(
|
||||
model="deepseek_v4",
|
||||
tools=request.tools,
|
||||
tool_choice=request.tool_choice,
|
||||
reasoning=get_enable_structured_outputs_in_reasoning(),
|
||||
)
|
||||
structural_tag_model = "deepseek_v4"
|
||||
|
||||
@@ -24,6 +24,7 @@ logger = init_logger(__name__)
|
||||
|
||||
class Glm47MoeModelToolParser(Glm4MoeModelToolParser):
|
||||
supports_required_and_named = False
|
||||
structural_tag_model = "glm_4_7"
|
||||
|
||||
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
|
||||
super().__init__(tokenizer, tools)
|
||||
|
||||
@@ -32,6 +32,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class Hermes2ProToolParser(ToolParser):
|
||||
structural_tag_model = "hermes"
|
||||
tool_call_start_token: str = "<tool_call>"
|
||||
tool_call_end_token: str = "</tool_call>"
|
||||
tool_call_regex = re.compile(
|
||||
|
||||
@@ -29,6 +29,8 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class KimiK2ToolParser(ToolParser):
|
||||
structural_tag_model = "kimi"
|
||||
|
||||
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
|
||||
super().__init__(tokenizer, tools)
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ class Llama3JsonToolParser(ToolParser):
|
||||
"""
|
||||
|
||||
bot_token: str = "<|python_tag|>"
|
||||
structural_tag_model = "llama"
|
||||
# Simple regex to find opening braces - we'll use JSON decoder for parsing
|
||||
# This handles arbitrary nesting depth correctly
|
||||
tool_call_start_regex: re.Pattern = re.compile(r"\{")
|
||||
|
||||
@@ -34,6 +34,8 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class MinimaxM2ToolParser(ToolParser):
|
||||
structural_tag_model = "minimax"
|
||||
|
||||
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
|
||||
super().__init__(tokenizer, tools)
|
||||
|
||||
|
||||
@@ -18,17 +18,12 @@ from vllm.entrypoints.openai.engine.protocol import (
|
||||
FunctionCall,
|
||||
ToolCall,
|
||||
)
|
||||
from vllm.envs import VLLM_ENFORCE_STRICT_TOOL_CALLING
|
||||
from vllm.logger import init_logger
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.tool_parsers.abstract_tool_parser import (
|
||||
Tool,
|
||||
ToolParser,
|
||||
)
|
||||
from vllm.tool_parsers.structural_tag_registry import (
|
||||
get_enable_structured_outputs_in_reasoning,
|
||||
get_model_structural_tag,
|
||||
)
|
||||
from vllm.tool_parsers.utils import (
|
||||
coerce_to_schema_type,
|
||||
extract_types_from_schema,
|
||||
@@ -39,7 +34,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class Qwen3CoderToolParser(ToolParser):
|
||||
supports_required_and_named: bool = not VLLM_ENFORCE_STRICT_TOOL_CALLING
|
||||
structural_tag_model = "qwen_3_coder"
|
||||
|
||||
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
|
||||
super().__init__(tokenizer, tools)
|
||||
@@ -589,11 +584,3 @@ class Qwen3CoderToolParser(ToolParser):
|
||||
return result
|
||||
|
||||
return None
|
||||
|
||||
def get_structural_tag(self, request: ChatCompletionRequest):
|
||||
return get_model_structural_tag(
|
||||
model="qwen_3_5",
|
||||
tools=request.tools,
|
||||
tool_choice=request.tool_choice,
|
||||
reasoning=get_enable_structured_outputs_in_reasoning(),
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,14 +1,15 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# Model-specific structural tag builders adapted from XGrammar's
|
||||
# builtin structural tag implementations:
|
||||
# https://github.com/mlc-ai/xgrammar/blob/main/python/xgrammar/builtin_structural_tag.py
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any, Literal
|
||||
|
||||
from xgrammar import StructuralTag
|
||||
from xgrammar import StructuralTag, normalize_tool_choice
|
||||
from xgrammar import get_model_structural_tag as get_xgrammar_model_structural_tag
|
||||
from xgrammar.openai_tool_call_schema import (
|
||||
BuiltinToolParam,
|
||||
FunctionToolParam,
|
||||
)
|
||||
from xgrammar.structural_tag import (
|
||||
AnyTextFormat,
|
||||
ConstStringFormat,
|
||||
@@ -24,23 +25,51 @@ from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionToolsParam,
|
||||
)
|
||||
|
||||
SimplifiedToolChoice = Literal["auto", "required", "forced"]
|
||||
ToolChoice = (
|
||||
Literal["none", "auto", "required"] | ChatCompletionNamedToolChoiceParam | None
|
||||
)
|
||||
SimplifiedToolChoice = Literal["auto", "required", "forced"]
|
||||
StructuralTagBuilder = Callable[
|
||||
[list[ChatCompletionToolsParam], SimplifiedToolChoice, bool],
|
||||
[
|
||||
list[FunctionToolParam],
|
||||
list[BuiltinToolParam],
|
||||
SimplifiedToolChoice,
|
||||
bool,
|
||||
],
|
||||
StructuralTag,
|
||||
]
|
||||
|
||||
_structural_tag_registry: dict[str, StructuralTagBuilder] = {}
|
||||
# Keep this list in sync with xgrammar.builtin_structural_tag. It is used for
|
||||
# vLLM-side validation and for documenting the xgrammar builtin surface that
|
||||
# can be requested by tool parsers through ``structural_tag_model``.
|
||||
XGRAMMAR_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset(
|
||||
{
|
||||
"llama",
|
||||
"kimi",
|
||||
"deepseek_r1",
|
||||
"deepseek_v3_1",
|
||||
"qwen_3_5",
|
||||
"qwen_3_coder",
|
||||
"qwen_3",
|
||||
"harmony",
|
||||
"deepseek_v3_2",
|
||||
"glm_4_7",
|
||||
"deepseek_v4",
|
||||
}
|
||||
)
|
||||
VLLM_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset({"hermes"})
|
||||
SUPPORTED_STRUCTURAL_TAG_MODELS = (
|
||||
XGRAMMAR_BUILTIN_STRUCTURAL_TAG_MODELS | VLLM_BUILTIN_STRUCTURAL_TAG_MODELS
|
||||
)
|
||||
|
||||
_VLLM_STRUCTURAL_TAG_REGISTRY: dict[str, StructuralTagBuilder] = {}
|
||||
|
||||
|
||||
def register_model_structural_tag(name: str):
|
||||
"""Register a vLLM-owned model-specific structural tag builder."""
|
||||
def register_vllm_structural_tag(model: str):
|
||||
"""Register a vLLM-owned structural tag builder."""
|
||||
|
||||
def decorator(func: StructuralTagBuilder) -> StructuralTagBuilder:
|
||||
_structural_tag_registry[name] = func
|
||||
_VLLM_STRUCTURAL_TAG_REGISTRY[model] = func
|
||||
return func
|
||||
|
||||
return decorator
|
||||
@@ -52,279 +81,184 @@ def get_model_structural_tag(
|
||||
tool_choice: ToolChoice,
|
||||
reasoning: bool,
|
||||
) -> StructuralTag | None:
|
||||
"""Build a structural tag from vLLM-owned model-specific builders."""
|
||||
"""Build a structural tag with xgrammar's builtin model templates."""
|
||||
|
||||
builder = _structural_tag_registry.get(model)
|
||||
if builder is None:
|
||||
supported = list(_structural_tag_registry.keys())
|
||||
raise ValueError(f"Unknown format type: {model}, supported types: {supported}")
|
||||
|
||||
normalized_tools, simplified_tool_choice = _normalize_tool_choice(
|
||||
tools=tools,
|
||||
tool_choice=tool_choice,
|
||||
)
|
||||
if not normalized_tools:
|
||||
if not tools or tool_choice == "none":
|
||||
return None
|
||||
|
||||
return builder(normalized_tools, simplified_tool_choice, reasoning)
|
||||
dumped_tools = [_model_dump(tool) for tool in tools]
|
||||
dumped_tool_choice = _model_dump(tool_choice)
|
||||
|
||||
if model in _VLLM_STRUCTURAL_TAG_REGISTRY:
|
||||
function_tools, builtin_tools, simplified_tool_choice = normalize_tool_choice(
|
||||
dumped_tools,
|
||||
dumped_tool_choice,
|
||||
)
|
||||
return _VLLM_STRUCTURAL_TAG_REGISTRY[model](
|
||||
function_tools,
|
||||
builtin_tools,
|
||||
simplified_tool_choice,
|
||||
reasoning,
|
||||
)
|
||||
|
||||
if model not in XGRAMMAR_BUILTIN_STRUCTURAL_TAG_MODELS:
|
||||
supported = sorted(SUPPORTED_STRUCTURAL_TAG_MODELS)
|
||||
raise ValueError(f"Unknown format type: {model}, supported types: {supported}")
|
||||
|
||||
return get_xgrammar_model_structural_tag(
|
||||
model=model,
|
||||
tools=dumped_tools,
|
||||
tool_choice=dumped_tool_choice,
|
||||
reasoning=reasoning,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_tool_choice(
|
||||
tools: list[ChatCompletionToolsParam] | None,
|
||||
tool_choice: ToolChoice,
|
||||
) -> tuple[list[ChatCompletionToolsParam], SimplifiedToolChoice]:
|
||||
"""Normalize vLLM ChatCompletion tool_choice for structural tag builders."""
|
||||
def _model_dump(value: Any) -> Any:
|
||||
"""Convert vLLM/Pydantic request objects to xgrammar's dict protocol."""
|
||||
|
||||
if not tools:
|
||||
return [], "auto"
|
||||
|
||||
if tool_choice is None or tool_choice == "none":
|
||||
return [], "auto"
|
||||
|
||||
if tool_choice == "auto":
|
||||
return tools, "auto"
|
||||
|
||||
if tool_choice == "required":
|
||||
return tools, "required"
|
||||
|
||||
if isinstance(tool_choice, ChatCompletionNamedToolChoiceParam):
|
||||
tool_name = tool_choice.function.name
|
||||
filtered_tools = [tool for tool in tools if tool.function.name == tool_name]
|
||||
if not filtered_tools:
|
||||
raise ValueError(
|
||||
f"The tool with name '{tool_name}' is not found in the tools list."
|
||||
)
|
||||
return filtered_tools, "forced"
|
||||
|
||||
raise ValueError(f"Unsupported tool_choice for structural tag: {tool_choice}")
|
||||
if hasattr(value, "model_dump"):
|
||||
return value.model_dump(exclude_none=True)
|
||||
return value
|
||||
|
||||
|
||||
def _get_function_parameters(function: Any) -> dict[str, Any] | bool:
|
||||
"""Return the JSON schema used for constrained tool arguments."""
|
||||
|
||||
def _get_function_parameters(function) -> dict[str, Any] | bool:
|
||||
if getattr(function, "strict", None) is False:
|
||||
return True
|
||||
if function.parameters is None:
|
||||
return True
|
||||
return function.parameters
|
||||
return function.parameters if function.parameters is not None else True
|
||||
|
||||
|
||||
_enable_structured_outputs_in_reasoning: bool = False
|
||||
def _hermes_tool_tags(tools: list[FunctionToolParam]) -> list[TagFormat]:
|
||||
arguments_field_prefix = '", "arguments": '
|
||||
formats = [
|
||||
# <tool_call>
|
||||
# {"name": "t1", "arguments": {"q": "v"}}
|
||||
# </tool_call>
|
||||
('<tool_call>\n{"name": "', "}\n</tool_call>"),
|
||||
# <tool_call>{"name": "t1", "arguments": {"q": "v"}}</tool_call>
|
||||
('<tool_call>{"name": "', "}</tool_call>"),
|
||||
]
|
||||
|
||||
|
||||
def set_enable_structured_outputs_in_reasoning(enabled: bool) -> None:
|
||||
"""Publish the engine's ``enable_in_reasoning`` flag to tool parsers.
|
||||
|
||||
Called once during APIServer startup so request-time parsers can read
|
||||
it without going through the EngineCore-only contextvar.
|
||||
"""
|
||||
|
||||
global _enable_structured_outputs_in_reasoning
|
||||
_enable_structured_outputs_in_reasoning = bool(enabled)
|
||||
|
||||
|
||||
def get_enable_structured_outputs_in_reasoning() -> bool:
|
||||
"""Whether structured outputs are active during the reasoning phase.
|
||||
|
||||
When ``True``, the structural tag will cover the reasoning part:
|
||||
``<think>...</think>`` prefix (if available); when ``False`` (default), the tag only
|
||||
constrains the post-reasoning suffix.
|
||||
"""
|
||||
|
||||
return _enable_structured_outputs_in_reasoning
|
||||
|
||||
|
||||
@register_model_structural_tag("deepseek_v4")
|
||||
def get_deepseek_v4_structural_tag(
|
||||
tools: list[ChatCompletionToolsParam],
|
||||
tool_choice: SimplifiedToolChoice,
|
||||
reasoning: bool,
|
||||
) -> StructuralTag:
|
||||
"""Build DeepSeek V4 structural tags."""
|
||||
|
||||
invoke_begin_prefix = '<|DSML|invoke name="'
|
||||
invoke_begin_suffix = '">\n'
|
||||
invoke_end = "</|DSML|invoke>\n"
|
||||
tool_calls_prefix = "\n\n"
|
||||
function_calls_begin = "<|DSML|tool_calls>\n"
|
||||
function_calls_end = "</|DSML|tool_calls>"
|
||||
function_calls_trigger = "<|DSML|tool_calls>"
|
||||
think_tag_end = "</think>"
|
||||
think_exclude_tokens = ["<think>", "</think>"]
|
||||
xml_style = "deepseek_xml"
|
||||
|
||||
if tool_choice == "auto":
|
||||
tags = []
|
||||
for tool in tools:
|
||||
function = tool.function
|
||||
parameters = _get_function_parameters(function)
|
||||
tags.append(
|
||||
TagFormat(
|
||||
begin=invoke_begin_prefix + function.name + invoke_begin_suffix,
|
||||
content=JSONSchemaFormat(
|
||||
json_schema=parameters,
|
||||
style=xml_style,
|
||||
),
|
||||
end=invoke_end,
|
||||
)
|
||||
)
|
||||
|
||||
if tags:
|
||||
function_calling_tags = TagsWithSeparatorFormat(
|
||||
tags=tags,
|
||||
separator="\n",
|
||||
at_least_one=True,
|
||||
)
|
||||
suffix_tag = TriggeredTagsFormat(
|
||||
triggers=[function_calls_trigger],
|
||||
tags=[
|
||||
TagFormat(
|
||||
begin=function_calls_begin,
|
||||
content=function_calling_tags,
|
||||
end=function_calls_end,
|
||||
)
|
||||
],
|
||||
excludes=think_exclude_tokens,
|
||||
)
|
||||
else:
|
||||
suffix_tag = AnyTextFormat(excludes=think_exclude_tokens)
|
||||
|
||||
elif tool_choice == "forced":
|
||||
if not tools:
|
||||
raise ValueError("Forced tool choice must resolve to exactly one tool.")
|
||||
function = tools[0].function
|
||||
suffix_tag = SequenceFormat(
|
||||
elements=[
|
||||
ConstStringFormat(value=tool_calls_prefix + function_calls_begin),
|
||||
TagFormat(
|
||||
begin=invoke_begin_prefix + function.name + invoke_begin_suffix,
|
||||
content=JSONSchemaFormat(
|
||||
json_schema=_get_function_parameters(function),
|
||||
style=xml_style,
|
||||
),
|
||||
end=invoke_end,
|
||||
),
|
||||
ConstStringFormat(value=function_calls_end),
|
||||
]
|
||||
)
|
||||
|
||||
elif tool_choice == "required":
|
||||
tags = []
|
||||
for tool in tools:
|
||||
function = tool.function
|
||||
parameters = _get_function_parameters(function)
|
||||
tags.append(
|
||||
TagFormat(
|
||||
begin=invoke_begin_prefix + function.name + invoke_begin_suffix,
|
||||
content=JSONSchemaFormat(
|
||||
json_schema=parameters,
|
||||
style=xml_style,
|
||||
),
|
||||
end=invoke_end,
|
||||
)
|
||||
)
|
||||
assert len(tags) > 0
|
||||
suffix_tag = SequenceFormat(
|
||||
elements=[
|
||||
ConstStringFormat(value=tool_calls_prefix + function_calls_begin),
|
||||
TagsWithSeparatorFormat(
|
||||
tags=tags,
|
||||
separator="\n",
|
||||
at_least_one=True,
|
||||
),
|
||||
ConstStringFormat(value=function_calls_end),
|
||||
]
|
||||
)
|
||||
|
||||
if not reasoning:
|
||||
return StructuralTag(format=suffix_tag)
|
||||
|
||||
prefix_tag = TagFormat(begin="", content=AnyTextFormat(), end=think_tag_end)
|
||||
return StructuralTag(format=SequenceFormat(elements=[prefix_tag, suffix_tag]))
|
||||
|
||||
|
||||
@register_model_structural_tag("qwen_3_5")
|
||||
def get_qwen_3_5_structural_tag(
|
||||
tools: list[ChatCompletionToolsParam],
|
||||
tool_choice: SimplifiedToolChoice,
|
||||
reasoning: bool,
|
||||
) -> StructuralTag:
|
||||
"""Build Qwen XML structural tags.
|
||||
|
||||
This format is used for Qwen3-Coder/Qwen3.5/Qwen3.6 and is compatible with
|
||||
Qwen variants that use the same XML tool-call format.
|
||||
"""
|
||||
tool_call_begin_prefix = "<tool_call>\n<function="
|
||||
tool_call_begin_suffix = ">\n"
|
||||
tool_call_end = "\n</function>\n</tool_call>"
|
||||
tool_call_trigger = "<tool_call>\n<function="
|
||||
think_tag_end = "</think>"
|
||||
think_suffix = "\n\n"
|
||||
think_exclude_tokens = ["<think>", "</think>"]
|
||||
|
||||
if tool_choice == "auto":
|
||||
tags = []
|
||||
for tool in tools:
|
||||
function = tool.function
|
||||
parameters = _get_function_parameters(function)
|
||||
tags.append(
|
||||
TagFormat(
|
||||
begin=f"{tool_call_begin_prefix}{function.name}{tool_call_begin_suffix}",
|
||||
content=JSONSchemaFormat(json_schema=parameters, style="qwen_xml"),
|
||||
end=tool_call_end,
|
||||
)
|
||||
)
|
||||
|
||||
if tags:
|
||||
suffix_tag = TriggeredTagsFormat(
|
||||
triggers=[tool_call_trigger],
|
||||
tags=tags,
|
||||
excludes=think_exclude_tokens,
|
||||
)
|
||||
else:
|
||||
suffix_tag = AnyTextFormat(excludes=think_exclude_tokens)
|
||||
|
||||
elif tool_choice == "forced":
|
||||
if not tools:
|
||||
raise ValueError("Forced tool choice must resolve to exactly one tool.")
|
||||
function = tools[0].function
|
||||
suffix_tag = TagFormat(
|
||||
begin=f"{tool_call_begin_prefix}{function.name}{tool_call_begin_suffix}",
|
||||
return [
|
||||
TagFormat(
|
||||
begin=begin + tool.function.name + arguments_field_prefix,
|
||||
content=JSONSchemaFormat(
|
||||
json_schema=_get_function_parameters(function),
|
||||
style="qwen_xml",
|
||||
json_schema=_get_function_parameters(tool.function)
|
||||
),
|
||||
end=tool_call_end,
|
||||
end=end,
|
||||
)
|
||||
for tool in tools
|
||||
for begin, end in formats
|
||||
]
|
||||
|
||||
elif tool_choice == "required":
|
||||
tags = []
|
||||
for tool in tools:
|
||||
function = tool.function
|
||||
parameters = _get_function_parameters(function)
|
||||
tags.append(
|
||||
TagFormat(
|
||||
begin=f"{tool_call_begin_prefix}{function.name}{tool_call_begin_suffix}",
|
||||
content=JSONSchemaFormat(json_schema=parameters, style="qwen_xml"),
|
||||
end=tool_call_end,
|
||||
)
|
||||
)
|
||||
assert len(tags) > 0
|
||||
|
||||
@register_vllm_structural_tag("hermes")
|
||||
def get_hermes_structural_tag(
|
||||
tools: list[FunctionToolParam],
|
||||
builtin_tools: list[BuiltinToolParam],
|
||||
tool_choice: SimplifiedToolChoice,
|
||||
reasoning: bool,
|
||||
) -> StructuralTag:
|
||||
del builtin_tools, reasoning
|
||||
|
||||
tool_call_trigger = "<tool_call>"
|
||||
|
||||
if tool_choice == "auto":
|
||||
tags = _hermes_tool_tags(tools)
|
||||
suffix_tag = (
|
||||
TriggeredTagsFormat(triggers=[tool_call_trigger], tags=tags)
|
||||
if tags
|
||||
else AnyTextFormat()
|
||||
)
|
||||
elif tool_choice == "forced":
|
||||
suffix_tag = TagsWithSeparatorFormat(
|
||||
tags=tags,
|
||||
tags=_hermes_tool_tags(tools),
|
||||
separator="",
|
||||
at_least_one=True,
|
||||
stop_after_first=True,
|
||||
)
|
||||
else:
|
||||
suffix_tag = TagsWithSeparatorFormat(
|
||||
tags=_hermes_tool_tags(tools),
|
||||
separator="",
|
||||
at_least_one=True,
|
||||
)
|
||||
|
||||
if not reasoning:
|
||||
result = StructuralTag(format=suffix_tag)
|
||||
else:
|
||||
prefix_tag = SequenceFormat(
|
||||
return StructuralTag(format=suffix_tag)
|
||||
|
||||
|
||||
def _minimax_tool_tags(tools: list[FunctionToolParam]) -> list[TagFormat]:
|
||||
return [
|
||||
TagFormat(
|
||||
begin=f'<invoke name="{tool.function.name}">\n',
|
||||
content=JSONSchemaFormat(
|
||||
json_schema=_get_function_parameters(tool.function),
|
||||
style="minimax_xml",
|
||||
),
|
||||
end="</invoke>\n",
|
||||
)
|
||||
for tool in tools
|
||||
]
|
||||
|
||||
|
||||
@register_vllm_structural_tag("minimax")
|
||||
def get_minimax_structural_tag(
|
||||
tools: list[FunctionToolParam],
|
||||
builtin_tools: list[BuiltinToolParam],
|
||||
tool_choice: SimplifiedToolChoice,
|
||||
reasoning: bool,
|
||||
) -> StructuralTag:
|
||||
del builtin_tools, reasoning
|
||||
|
||||
tool_call_begin = "<minimax:tool_call>\n"
|
||||
tool_call_end = "</minimax:tool_call>"
|
||||
tool_call_trigger = "<minimax:tool_call>"
|
||||
|
||||
tags = _minimax_tool_tags(tools)
|
||||
|
||||
if tool_choice == "auto":
|
||||
suffix_tag = (
|
||||
TriggeredTagsFormat(
|
||||
triggers=[tool_call_trigger],
|
||||
tags=[
|
||||
TagFormat(
|
||||
begin=tool_call_begin,
|
||||
content=TagsWithSeparatorFormat(
|
||||
tags=tags,
|
||||
separator="",
|
||||
at_least_one=True,
|
||||
),
|
||||
end=tool_call_end,
|
||||
)
|
||||
],
|
||||
excludes=["<think>", "</think>"],
|
||||
)
|
||||
if tags
|
||||
else AnyTextFormat(excludes=["<think>", "</think>"])
|
||||
)
|
||||
elif tool_choice == "forced":
|
||||
suffix_tag = SequenceFormat(
|
||||
elements=[
|
||||
TagFormat(begin="", content=AnyTextFormat(), end=think_tag_end),
|
||||
ConstStringFormat(value=think_suffix),
|
||||
ConstStringFormat(value="\n" + tool_call_begin),
|
||||
TagsWithSeparatorFormat(
|
||||
tags=tags,
|
||||
separator="",
|
||||
at_least_one=True,
|
||||
stop_after_first=True,
|
||||
),
|
||||
ConstStringFormat(value=tool_call_end),
|
||||
]
|
||||
)
|
||||
else:
|
||||
suffix_tag = SequenceFormat(
|
||||
elements=[
|
||||
ConstStringFormat(value="\n" + tool_call_begin),
|
||||
TagsWithSeparatorFormat(
|
||||
tags=tags,
|
||||
separator="",
|
||||
at_least_one=True,
|
||||
),
|
||||
ConstStringFormat(value=tool_call_end),
|
||||
]
|
||||
)
|
||||
result = StructuralTag(format=SequenceFormat(elements=[prefix_tag, suffix_tag]))
|
||||
|
||||
return result
|
||||
return StructuralTag(format=suffix_tag)
|
||||
|
||||
Reference in New Issue
Block a user