[Frontend] Constrain non-strict GLM-4.7 tool calls with a shallow structural tag (#56403)
Signed-off-by: Shijin Zhang <75300765+Dovis01@users.noreply.github.com> Co-authored-by: Flora Feng <4florafeng@gmail.com>
This commit is contained in:
co-authored by
Flora Feng
parent
f700178f90
commit
d1a974c140
@@ -506,6 +506,11 @@ class DelegatingParser(Parser):
|
||||
is_auto = request.tool_choice == "auto"
|
||||
single_call = request.parallel_tool_calls is False
|
||||
strict_level = self.tool_strict_level
|
||||
if (
|
||||
strict_level == ToolStrictLevel.AUTO
|
||||
and tool_parser.default_tool_strict_level is not None
|
||||
):
|
||||
strict_level = tool_parser.default_tool_strict_level
|
||||
if single_call and not (is_auto and structured_outputs is not None):
|
||||
# Limiting the call count needs the call envelope in the grammar.
|
||||
# Auto with structured outputs keeps its format-only grammar, so the
|
||||
|
||||
@@ -59,6 +59,10 @@ class ToolParser:
|
||||
# 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
|
||||
# Strict level applied when the operator leaves ``--tool-strict-level``
|
||||
# at auto. Operator flags override it, and
|
||||
# ``VLLM_ENFORCE_STRICT_TOOL_CALLING=0`` still disables structural tags.
|
||||
default_tool_strict_level: ToolStrictLevel | None = None
|
||||
engine_based_streaming: bool = False
|
||||
|
||||
def __init_subclass__(cls, **kwargs: Any) -> None:
|
||||
|
||||
@@ -4,8 +4,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm.parser.engine.registered_adapters import Glm47MoeParserToolAdapter
|
||||
from vllm.tool_parsers.tool_strict_level import ToolStrictLevel
|
||||
|
||||
|
||||
class Glm47MoeModelToolParser(Glm47MoeParserToolAdapter): # type: ignore[valid-type, misc]
|
||||
supports_required_and_named = False
|
||||
structural_tag_model = "glm_4_7"
|
||||
# Constrain auto tool calls with the shallow tag by default.
|
||||
default_tool_strict_level = ToolStrictLevel.FUNCTION
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
|
||||
import json
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import Any, Literal, TypeAlias
|
||||
|
||||
@@ -71,12 +73,13 @@ XGRAMMAR_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset(
|
||||
"mimo",
|
||||
"qwen_3",
|
||||
"deepseek_v3_2",
|
||||
"glm_4_7",
|
||||
"deepseek_v4",
|
||||
"deepseek_v4_1",
|
||||
}
|
||||
)
|
||||
VLLM_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset({"hermes", "hy_v4", "kimi_k3", "plamo3"})
|
||||
VLLM_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset(
|
||||
{"glm_4_7", "hermes", "hy_v4", "kimi_k3", "plamo3"}
|
||||
)
|
||||
SUPPORTED_STRUCTURAL_TAG_MODELS = (
|
||||
XGRAMMAR_BUILTIN_STRUCTURAL_TAG_MODELS | VLLM_BUILTIN_STRUCTURAL_TAG_MODELS
|
||||
)
|
||||
@@ -903,3 +906,182 @@ def get_hy_v4_structural_tag(
|
||||
# the ``<think>...</think:SUF>`` prefix.
|
||||
prefix_tag = TagFormat(begin="", content=AnyTextFormat(), end=think_end)
|
||||
return StructuralTag(format=SequenceFormat(elements=[prefix_tag, suffix_tag]))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GLM-4.7 tool calls (<tool_call>NAME<arg_key>K</arg_key><arg_value>V</arg_value>)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Assistant output after the reasoning gate (``</think>``):
|
||||
# [<text>]
|
||||
# <tool_call>NAME<arg_key>K1</arg_key><arg_value>V1</arg_value>...</tool_call>
|
||||
# Values are raw JSON scalars: strings verbatim (unquoted), other types as
|
||||
# bare JSON, matching how the chat template serializes tool-call history.
|
||||
|
||||
_GLM_4_7_VALUE_EXCLUDES = [
|
||||
"<think>",
|
||||
"</think>",
|
||||
"<tool_call>",
|
||||
"</tool_call>",
|
||||
"<arg_key>",
|
||||
"</arg_key>",
|
||||
"<arg_value>",
|
||||
"</arg_value>",
|
||||
]
|
||||
|
||||
|
||||
def _glm_4_7_value_format(prop: dict[str, Any]) -> Any:
|
||||
if "enum" in prop:
|
||||
values = [
|
||||
ConstStringFormat(value=v if isinstance(v, str) else json.dumps(v))
|
||||
for v in prop["enum"]
|
||||
]
|
||||
return values[0] if len(values) == 1 else OrFormat(elements=values)
|
||||
prop_type = prop.get("type")
|
||||
if isinstance(prop_type, list):
|
||||
formats = [
|
||||
_glm_4_7_value_format({"type": t}) for t in prop_type if t != "string"
|
||||
]
|
||||
if "string" in prop_type:
|
||||
formats.append(AnyTextFormat(excludes=_GLM_4_7_VALUE_EXCLUDES))
|
||||
return formats[0] if len(formats) == 1 else OrFormat(elements=formats)
|
||||
if prop_type in (None, "string"):
|
||||
return AnyTextFormat(excludes=_GLM_4_7_VALUE_EXCLUDES)
|
||||
return JSONSchemaFormat(json_schema={"type": prop_type})
|
||||
|
||||
|
||||
def _glm_4_7_plain_properties(params: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""Return ``properties`` when the schema is a plain object schema."""
|
||||
properties = params.get("properties")
|
||||
if (
|
||||
not isinstance(properties, dict)
|
||||
or not properties
|
||||
or params.get("additionalProperties") is True
|
||||
or any(
|
||||
key in params
|
||||
for key in ("$ref", "allOf", "anyOf", "oneOf", "patternProperties")
|
||||
)
|
||||
):
|
||||
return None
|
||||
return properties
|
||||
|
||||
|
||||
def _glm_4_7_tool_tag(tool: FunctionToolParam) -> TagFormat:
|
||||
"""Shallow tag for a non-strict tool: keys and basic value types pinned."""
|
||||
properties = _glm_4_7_plain_properties(tool.function.parameters or {})
|
||||
if properties is None:
|
||||
return TagFormat(
|
||||
begin=f"<tool_call>{tool.function.name}",
|
||||
content=JSONSchemaFormat(
|
||||
json_schema=True, style="glm_xml", any_order=False
|
||||
),
|
||||
end="</tool_call>",
|
||||
)
|
||||
pairs: list[Any] = [
|
||||
SequenceFormat(
|
||||
elements=[
|
||||
ConstStringFormat(value=f"<arg_key>{key}</arg_key><arg_value>"),
|
||||
_glm_4_7_value_format(prop),
|
||||
ConstStringFormat(value="</arg_value>"),
|
||||
]
|
||||
)
|
||||
for key, prop in properties.items()
|
||||
]
|
||||
content: Any = (
|
||||
StarFormat(content=pairs[0] if len(pairs) == 1 else OrFormat(elements=pairs))
|
||||
if pairs
|
||||
else ConstStringFormat(value="")
|
||||
)
|
||||
return TagFormat(
|
||||
begin=f"<tool_call>{tool.function.name}",
|
||||
content=content,
|
||||
end="</tool_call>",
|
||||
)
|
||||
|
||||
|
||||
def _glm_4_7_strict_tool_tag(tool: FunctionToolParam) -> TagFormat:
|
||||
"""Schema-pinned tag matching the xgrammar builtin's strict content."""
|
||||
return TagFormat(
|
||||
begin=f"<tool_call>{tool.function.name}",
|
||||
content=JSONSchemaFormat(
|
||||
json_schema=tool.function.parameters
|
||||
if tool.function.parameters is not None
|
||||
else True,
|
||||
style="glm_xml",
|
||||
any_order=False,
|
||||
),
|
||||
end="</tool_call>",
|
||||
)
|
||||
|
||||
|
||||
@register_vllm_structural_tag("glm_4_7")
|
||||
def get_glm_4_7_structural_tag(
|
||||
function_tools: list[FunctionToolParam],
|
||||
builtin_tools: list[BuiltinToolParam],
|
||||
tool_choice: Any,
|
||||
reasoning: bool,
|
||||
token_suffix: str = "",
|
||||
) -> StructuralTag:
|
||||
"""Build the GLM-4.7 structural tag, dispatching per tool on strictness.
|
||||
|
||||
Args:
|
||||
function_tools: Normalized function tools with ``strict`` pinned by
|
||||
``resolve_tool_strictness``.
|
||||
builtin_tools: Unused; GLM-4.7 has no builtin tools.
|
||||
tool_choice: Simplified tool choice (``auto`` / ``required`` /
|
||||
``forced``).
|
||||
reasoning: Whether the grammar also covers the reasoning phase.
|
||||
token_suffix: Unused; GLM-4.7 structural tokens are fixed.
|
||||
|
||||
"""
|
||||
del builtin_tools, token_suffix
|
||||
|
||||
if function_tools and all(tool.function.strict for tool in function_tools):
|
||||
# Strict-only requests stay byte-identical to the xgrammar builtin.
|
||||
dumped_choice: Any = (
|
||||
{"type": "function", "function": {"name": function_tools[0].function.name}}
|
||||
if tool_choice == "forced"
|
||||
else tool_choice
|
||||
)
|
||||
dumped_tools = []
|
||||
for tool in function_tools:
|
||||
function: dict[str, Any] = {"name": tool.function.name, "strict": True}
|
||||
if tool.function.description is not None:
|
||||
function["description"] = tool.function.description
|
||||
if tool.function.parameters is not None:
|
||||
function["parameters"] = tool.function.parameters
|
||||
dumped_tools.append({"type": "function", "function": function})
|
||||
return get_xgrammar_model_structural_tag(
|
||||
model="glm_4_7",
|
||||
tools=dumped_tools,
|
||||
tool_choice=dumped_choice,
|
||||
reasoning=reasoning,
|
||||
)
|
||||
|
||||
tags = [
|
||||
_glm_4_7_strict_tool_tag(tool)
|
||||
if tool.function.strict
|
||||
else _glm_4_7_tool_tag(tool)
|
||||
for tool in function_tools
|
||||
]
|
||||
if tool_choice == "auto":
|
||||
# Keep the trigger itself out of the excludes so tag dispatch works.
|
||||
suffix_tag: Any = TriggeredTagsFormat(
|
||||
triggers=["<tool_call>"],
|
||||
tags=tags,
|
||||
excludes=[e for e in _GLM_4_7_VALUE_EXCLUDES if e != "<tool_call>"],
|
||||
)
|
||||
else:
|
||||
suffix_tag = TagsWithSeparatorFormat(
|
||||
tags=tags,
|
||||
separator="",
|
||||
at_least_one=True,
|
||||
stop_after_first=tool_choice == "forced",
|
||||
)
|
||||
if reasoning:
|
||||
prefix_tag = TagFormat(
|
||||
begin="",
|
||||
content=AnyTextFormat(excludes=_GLM_4_7_VALUE_EXCLUDES),
|
||||
end="</think>",
|
||||
)
|
||||
return StructuralTag(format=SequenceFormat(elements=[prefix_tag, suffix_tag]))
|
||||
return StructuralTag(format=suffix_tag)
|
||||
|
||||
Reference in New Issue
Block a user