[Bugfix][Tool Parser] Migrate Granite to the streaming Parser Engine (#49648)
Signed-off-by: Nikhil Kulkarni <nikhilkulkarni1755@gmail.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: Chauncey <chaunceyjiang@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
Chauncey
parent
c961121519
commit
15ed1262e7
@@ -82,6 +82,12 @@ class ParserEngineConfig:
|
||||
|
||||
tool_args_json: bool = True
|
||||
|
||||
# The tool region body is a single JSON array of ``{"name", "arguments"}``
|
||||
# objects (one marker → N calls, no closing terminal). The engine splits
|
||||
# the array into one tool call per element; the array's ``]`` ends the
|
||||
# region and any trailing text becomes content. Used by Granite.
|
||||
tool_call_body_array: bool = False
|
||||
|
||||
arg_structural_chars: frozenset[str] | None = None
|
||||
|
||||
# Special tokens exempt from auto-drop but not state-machine terminals.
|
||||
|
||||
@@ -13,6 +13,7 @@ from vllm.parser.deepseek_v41 import DeepSeekV41Parser
|
||||
from vllm.parser.engine.adapters import make_adapters
|
||||
from vllm.parser.gemma4 import Gemma4Parser
|
||||
from vllm.parser.glm47_moe import Glm47MoeParser
|
||||
from vllm.parser.granite import GraniteParser
|
||||
from vllm.parser.inkling import InklingParser
|
||||
from vllm.parser.kimi_k2 import KimiK2Parser
|
||||
from vllm.parser.minimax_m2 import MinimaxM2Parser
|
||||
@@ -46,6 +47,11 @@ from vllm.parser.seed_oss import SeedOssParser
|
||||
Gemma4ParserToolAdapter,
|
||||
) = make_adapters(Gemma4Parser)
|
||||
|
||||
(
|
||||
GraniteParserReasoningAdapter,
|
||||
GraniteParserToolAdapter,
|
||||
) = make_adapters(GraniteParser)
|
||||
|
||||
(
|
||||
NemotronV3ParserReasoningAdapter,
|
||||
NemotronV3ParserToolAdapter,
|
||||
|
||||
@@ -190,6 +190,12 @@ class StreamingParserEngine:
|
||||
self._args_in_string: bool = False
|
||||
self._args_escape_next: bool = False
|
||||
|
||||
def _reset_array_state(self) -> None:
|
||||
# State for ``tool_call_body_array``: whether the opening ``[`` has been
|
||||
# seen, and whether a ``{...}`` element is currently being streamed.
|
||||
self._array_started: bool = False
|
||||
self._array_in_element: bool = False
|
||||
|
||||
def reset(self, initial_state: ParserState | None = None) -> None:
|
||||
"""Reset mutable state for reuse across requests.
|
||||
|
||||
@@ -213,6 +219,7 @@ class StreamingParserEngine:
|
||||
self._message_header_token_count = 0
|
||||
self._in_skipped_tool_span = False
|
||||
self._reset_args_state()
|
||||
self._reset_array_state()
|
||||
|
||||
def feed(
|
||||
self,
|
||||
@@ -306,7 +313,12 @@ class StreamingParserEngine:
|
||||
ParserState.TOOL_NAME,
|
||||
ParserState.TOOL_BETWEEN,
|
||||
):
|
||||
if self.tool_index >= 0:
|
||||
# In array mode a closed element has already emitted its
|
||||
# TOOL_CALL_END; only a truncated (still-open) element needs one.
|
||||
end_open_call = (
|
||||
self._array_in_element if self.config.tool_call_body_array else True
|
||||
)
|
||||
if end_open_call and self.tool_index >= 0:
|
||||
events.append(
|
||||
SemanticEvent(
|
||||
EventType.TOOL_CALL_END,
|
||||
@@ -474,6 +486,8 @@ class StreamingParserEngine:
|
||||
self._message_header_token_count += token_count
|
||||
return []
|
||||
if self.state == ParserState.TOOL_ARGS:
|
||||
if self.config.tool_call_body_array:
|
||||
return self._feed_array_text(text)
|
||||
if self.config.tool_args_json:
|
||||
return self._feed_args_text(text)
|
||||
return [
|
||||
@@ -564,6 +578,8 @@ class StreamingParserEngine:
|
||||
self._args_in_string = False
|
||||
self._args_escape_next = False
|
||||
self._args_safe_end = 0
|
||||
if self.config.tool_call_body_array:
|
||||
self._reset_array_state()
|
||||
|
||||
return events
|
||||
|
||||
@@ -634,3 +650,88 @@ class StreamingParserEngine:
|
||||
tool_index=self.tool_index,
|
||||
)
|
||||
]
|
||||
|
||||
# ── JSON-array tool body (tool_call_body_array) ─────────────────────
|
||||
|
||||
def _feed_array_text(self, text: str) -> list[SemanticEvent]:
|
||||
"""Split a JSON-array tool body into one tool call per element.
|
||||
|
||||
Granite emits ``[{"name":..,"arguments":{..}}, ...]`` after the tool
|
||||
marker. Element interiors are streamed through the string/brace-aware
|
||||
:meth:`_feed_args_char`, so each element behaves exactly like a
|
||||
single-object tool body; the array's ``]`` ends the region and any
|
||||
trailing text becomes content.
|
||||
"""
|
||||
events: list[SemanticEvent] = []
|
||||
for i, ch in enumerate(text):
|
||||
if self.state != ParserState.TOOL_ARGS:
|
||||
# The array closed mid-chunk; the rest of the text is content.
|
||||
events.extend(self._emit_for_state(text[i:]))
|
||||
break
|
||||
events.extend(self._feed_array_char(ch))
|
||||
return events
|
||||
|
||||
def _feed_array_char(self, ch: str) -> list[SemanticEvent]:
|
||||
if self._array_in_element:
|
||||
events = self._feed_args_char(ch)
|
||||
# Element object closed: top-level '}' with all braces balanced.
|
||||
if (
|
||||
ch == "}"
|
||||
and not self._args_in_string
|
||||
and not self._args_escape_next
|
||||
and self._args_brace_depth == 0
|
||||
):
|
||||
events.extend(self._end_array_element())
|
||||
return events
|
||||
|
||||
# Between elements only structural array characters are expected.
|
||||
if ch in " \t\r\n":
|
||||
return []
|
||||
if not self._array_started:
|
||||
if ch == "[":
|
||||
self._array_started = True
|
||||
return []
|
||||
return self._bail_array_to_content(ch)
|
||||
if ch == ",":
|
||||
return []
|
||||
if ch == "{":
|
||||
return self._start_array_element(ch)
|
||||
if ch == "]":
|
||||
self.state = ParserState.CONTENT
|
||||
self._reset_array_state()
|
||||
return []
|
||||
return self._bail_array_to_content(ch)
|
||||
|
||||
def _start_array_element(self, ch: str) -> list[SemanticEvent]:
|
||||
self.tool_index += 1
|
||||
self._reset_args_state()
|
||||
self._array_in_element = True
|
||||
events = [SemanticEvent(EventType.TOOL_CALL_START, tool_index=self.tool_index)]
|
||||
events.extend(self._feed_args_char(ch))
|
||||
return events
|
||||
|
||||
def _end_array_element(self) -> list[SemanticEvent]:
|
||||
self._array_in_element = False
|
||||
events: list[SemanticEvent] = []
|
||||
# Flush the held closing '}' so the slot body is the full element.
|
||||
if self._args_buffer:
|
||||
events.append(
|
||||
SemanticEvent(
|
||||
EventType.ARG_VALUE_CHUNK,
|
||||
value=self._args_buffer,
|
||||
tool_index=self.tool_index,
|
||||
)
|
||||
)
|
||||
self._args_buffer = ""
|
||||
self._args_safe_end = 0
|
||||
events.append(
|
||||
SemanticEvent(EventType.TOOL_CALL_END, tool_index=self.tool_index)
|
||||
)
|
||||
return events
|
||||
|
||||
def _bail_array_to_content(self, ch: str) -> list[SemanticEvent]:
|
||||
# Marker not followed by a JSON array (malformed) — revert to content
|
||||
# so the remaining tokens are emitted as plain text, no tool call.
|
||||
self.state = ParserState.CONTENT
|
||||
self._reset_array_state()
|
||||
return self._emit_for_state(ch)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Granite parser for JSON-array tool calls.
|
||||
|
||||
Granite 3.0/3.1 emit tool calls as a JSON array following a marker::
|
||||
|
||||
<|tool_call|> [{"name": "get_weather", "arguments": {"city": "SF"}}] # 3.0
|
||||
<tool_call> [{"name": "get_weather", "arguments": {"city": "SF"}}] # 3.1
|
||||
|
||||
``<|tool_call|>`` is a single special token; ``<tool_call>`` is plain text.
|
||||
The array may hold several calls, has no closing marker (the ``]`` ends it),
|
||||
and any surrounding prose is content. The engine's ``tool_call_body_array``
|
||||
mode splits the array into one call per element and extracts each name via the
|
||||
name-from-args path; ``_granite_arg_converter`` carves the ``arguments`` object
|
||||
out of each ``{"name":..,"arguments":{..}}`` element. Granite has no reasoning.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from vllm.parser.engine.parser_engine import ParserEngine
|
||||
from vllm.parser.engine.parser_engine_config import (
|
||||
ParserEngineConfig,
|
||||
ParserState,
|
||||
Transition,
|
||||
)
|
||||
from vllm.parser.utils import extract_json_member_object
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.tool_parsers.abstract_tool_parser import Tool
|
||||
|
||||
TOOL_TOKEN = "<|tool_call|>" # granite 3.0 (single special token)
|
||||
TOOL_STRING = "<tool_call>" # granite 3.1 (plain text)
|
||||
|
||||
|
||||
def _granite_arg_converter(raw_args: str, partial: bool) -> str:
|
||||
"""Carve the ``arguments`` object out of a ``{"name":..,"arguments":{..}}``
|
||||
array element (see :func:`extract_json_member_object`)."""
|
||||
span = extract_json_member_object(raw_args, "arguments")
|
||||
if span is None:
|
||||
return "" if partial else "{}"
|
||||
return span
|
||||
|
||||
|
||||
@functools.cache
|
||||
def granite_config() -> ParserEngineConfig:
|
||||
return ParserEngineConfig(
|
||||
name="granite",
|
||||
initial_state=ParserState.CONTENT,
|
||||
terminals={
|
||||
"TOOL_TOKEN": TOOL_TOKEN,
|
||||
"TOOL_STRING": TOOL_STRING,
|
||||
},
|
||||
token_id_terminals={
|
||||
"TOOL_TOKEN": TOOL_TOKEN,
|
||||
},
|
||||
transitions={
|
||||
# The marker only switches into the tool region; the array splitter
|
||||
# emits TOOL_CALL_START per element (empty events here).
|
||||
(ParserState.CONTENT, "TOOL_TOKEN"): Transition(
|
||||
ParserState.TOOL_ARGS,
|
||||
(),
|
||||
),
|
||||
(ParserState.CONTENT, "TOOL_STRING"): Transition(
|
||||
ParserState.TOOL_ARGS,
|
||||
(),
|
||||
),
|
||||
},
|
||||
arg_converter=_granite_arg_converter,
|
||||
tool_call_body_array=True,
|
||||
stream_arg_deltas=True,
|
||||
)
|
||||
|
||||
|
||||
class GraniteParser(ParserEngine):
|
||||
CONFIG_NAME = "granite"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: TokenizerLike,
|
||||
tools: list[Tool] | None = None,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
kwargs.setdefault("parser_engine_config", granite_config())
|
||||
super().__init__(tokenizer, tools, **kwargs)
|
||||
+4
-90
@@ -37,6 +37,7 @@ from vllm.parser.engine.parser_engine_config import (
|
||||
ParserState,
|
||||
Transition,
|
||||
)
|
||||
from vllm.parser.utils import extract_json_member_object
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
@@ -62,84 +63,6 @@ INKLING_SPECIAL_TOKENS = (
|
||||
END_MESSAGE,
|
||||
)
|
||||
|
||||
_WS = " \t\r\n"
|
||||
|
||||
|
||||
def _scan_json_value(raw: str, start: int) -> int | None:
|
||||
"""Return the end index (exclusive) of the JSON object starting at
|
||||
``raw[start]``, or ``None`` when the object is still unterminated."""
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape = False
|
||||
for i in range(start, len(raw)):
|
||||
ch = raw[i]
|
||||
if escape:
|
||||
escape = False
|
||||
continue
|
||||
if in_string:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_string = False
|
||||
continue
|
||||
if ch == '"':
|
||||
in_string = True
|
||||
elif ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return i + 1
|
||||
return None
|
||||
|
||||
|
||||
def _args_value_span(raw: str) -> str | None:
|
||||
"""Extract the raw text span of the top-level ``"args"`` value from a
|
||||
(possibly incomplete) ``{"name":...,"args":{...}}`` wrapper.
|
||||
|
||||
Returns the verbatim substring (prefix-stable across growing input,
|
||||
which the engine's argument-delta diffing relies on), possibly an
|
||||
unterminated object prefix; ``None`` when the value has not started.
|
||||
Raises ``ValueError`` when the value is not a JSON object.
|
||||
"""
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape = False
|
||||
string_start = -1
|
||||
last_string: str | None = None
|
||||
for i, ch in enumerate(raw):
|
||||
if escape:
|
||||
escape = False
|
||||
continue
|
||||
if in_string:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_string = False
|
||||
if depth == 1:
|
||||
last_string = raw[string_start + 1 : i]
|
||||
continue
|
||||
if ch == '"':
|
||||
in_string = True
|
||||
string_start = i
|
||||
elif ch == ":" and depth == 1 and last_string == "args":
|
||||
value_start = i + 1
|
||||
while value_start < len(raw) and raw[value_start] in _WS:
|
||||
value_start += 1
|
||||
if value_start >= len(raw):
|
||||
return None
|
||||
if raw[value_start] != "{":
|
||||
raise ValueError("Inkling tool call args must be a JSON object")
|
||||
value_end = _scan_json_value(raw, value_start)
|
||||
if value_end is None:
|
||||
return raw[value_start:]
|
||||
return raw[value_start:value_end]
|
||||
elif ch in "{[":
|
||||
depth += 1
|
||||
elif ch in "}]":
|
||||
depth -= 1
|
||||
return None
|
||||
|
||||
|
||||
def _inkling_arg_converter(raw_args: str, partial: bool) -> str:
|
||||
"""Carve the ``args`` object out of the tool-call JSON wrapper.
|
||||
@@ -150,19 +73,10 @@ def _inkling_arg_converter(raw_args: str, partial: bool) -> str:
|
||||
converter, ``_compute_arg_delta`` streams the wrapper verbatim into
|
||||
the OpenAI ``arguments`` field (``converter is None -> raw delta``,
|
||||
unconditionally; ``stream_arg_deltas=False`` does not stop it).
|
||||
|
||||
Why a hand-rolled scanner instead of (partial) ``json.loads`` +
|
||||
``json.dumps``: the engine diffs successive converter outputs and
|
||||
requires each to extend the previous one (``startswith``); a
|
||||
violation silently drops argument deltas. Re-serialization changes
|
||||
whitespace and closes unterminated structures differently across
|
||||
ticks, so the only prefix-stable output is a verbatim substring of
|
||||
the input. The scanner is also string/escape-aware so an ``"args"``
|
||||
literal inside the name or a string value cannot mislead it, and it
|
||||
still recovers a partial span when EOS truncates the wrapper (where
|
||||
``json.loads`` would fail).
|
||||
:func:`extract_json_member_object` returns a prefix-stable verbatim
|
||||
substring, which the engine's argument-delta diffing requires.
|
||||
"""
|
||||
span = _args_value_span(raw_args)
|
||||
span = extract_json_member_object(raw_args, "args")
|
||||
if span is None:
|
||||
# No args value yet (streaming) or none at all (treat as empty).
|
||||
return "" if partial else "{}"
|
||||
|
||||
@@ -63,3 +63,88 @@ def count_history_tool_calls(
|
||||
return 0
|
||||
|
||||
return count_response_history_tool_calls(request_input)
|
||||
|
||||
|
||||
_JSON_WS = " \t\r\n"
|
||||
|
||||
|
||||
def scan_json_object_end(raw: str, start: int) -> int | None:
|
||||
"""Return the end index (exclusive) of the JSON object starting at
|
||||
``raw[start]`` (which must be ``{``), or ``None`` when it is still
|
||||
unterminated. String- and escape-aware so braces inside strings do not
|
||||
mislead the depth count."""
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape = False
|
||||
for i in range(start, len(raw)):
|
||||
ch = raw[i]
|
||||
if escape:
|
||||
escape = False
|
||||
continue
|
||||
if in_string:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_string = False
|
||||
continue
|
||||
if ch == '"':
|
||||
in_string = True
|
||||
elif ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return i + 1
|
||||
return None
|
||||
|
||||
|
||||
def extract_json_member_object(raw: str, key: str) -> str | None:
|
||||
"""Extract the raw text span of the top-level object-valued member ``key``
|
||||
from a (possibly incomplete) ``{...}`` JSON wrapper.
|
||||
|
||||
Returns the verbatim substring (prefix-stable as the input grows, which
|
||||
the engine's argument-delta diffing relies on), possibly an unterminated
|
||||
object prefix; ``None`` when the value has not started. Raises
|
||||
``ValueError`` when the member is present but its value is not a JSON
|
||||
object. A verbatim substring (not re-serialized JSON) is required because
|
||||
the engine diffs successive converter outputs and expects each to extend
|
||||
the previous one; the scanner is string/escape-aware so a matching literal
|
||||
inside another value cannot mislead it, and it recovers a partial span when
|
||||
the wrapper is truncated (where ``json.loads`` would fail)."""
|
||||
depth = 0
|
||||
in_string = False
|
||||
escape = False
|
||||
string_start = -1
|
||||
last_string: str | None = None
|
||||
for i, ch in enumerate(raw):
|
||||
if escape:
|
||||
escape = False
|
||||
continue
|
||||
if in_string:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_string = False
|
||||
if depth == 1:
|
||||
last_string = raw[string_start + 1 : i]
|
||||
continue
|
||||
if ch == '"':
|
||||
in_string = True
|
||||
string_start = i
|
||||
elif ch == ":" and depth == 1 and last_string == key:
|
||||
value_start = i + 1
|
||||
while value_start < len(raw) and raw[value_start] in _JSON_WS:
|
||||
value_start += 1
|
||||
if value_start >= len(raw):
|
||||
return None
|
||||
if raw[value_start] != "{":
|
||||
raise ValueError(f"member {key!r} must be a JSON object")
|
||||
value_end = scan_json_object_end(raw, value_start)
|
||||
if value_end is None:
|
||||
return raw[value_start:]
|
||||
return raw[value_start:value_end]
|
||||
elif ch in "{[":
|
||||
depth += 1
|
||||
elif ch in "}]":
|
||||
depth -= 1
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user