Add pydocstyle to the ruff rules (#52136)

Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Signed-off-by: Harry Mellor <hej.mellor@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Harry Mellor
2026-09-16 16:44:29 +00:00
committed by GitHub
co-authored by Claude Opus 5
parent 804e5377aa
commit 8c1557a79c
2002 changed files with 15024 additions and 14269 deletions
+8 -14
View File
@@ -40,8 +40,7 @@ logger = init_logger(__name__)
class ToolParser:
"""
Abstract ToolParser class that should not be used directly. Provided
"""Abstract ToolParser class that should not be used directly. Provided
properties and methods should be used in
derived classes.
"""
@@ -186,8 +185,7 @@ class ToolParser:
def extract_tool_calls(
self, model_output: str, request: ChatCompletionRequest
) -> ExtractedToolCallInformation:
"""
Static method that should be implemented for extracting tool calls from
"""Static method that should be implemented for extracting tool calls from
a complete model-generated string.
Used for non-streaming responses where we have the entire model response
available before sending to the client.
@@ -207,8 +205,7 @@ class ToolParser:
delta_token_ids: Sequence[int],
request: ChatCompletionRequest,
) -> DeltaMessage | None:
"""
Instance method that should be implemented for extracting tool calls
"""Instance method that should be implemented for extracting tool calls
from an incomplete response; for use when handling tool calls and
streaming. Has to be an instance method because it requires state -
the current tokens/diffs, but also the information about what has
@@ -220,8 +217,7 @@ class ToolParser:
class ToolParserManager:
"""
Central registry for ToolParser implementations.
"""Central registry for ToolParser implementations.
Supports two modes:
- Eager (immediate) registration via `register_module`
@@ -233,8 +229,7 @@ class ToolParserManager:
@classmethod
def get_tool_parser(cls, name: str) -> type[ToolParser]:
"""
Retrieve a registered or lazily registered ToolParser class.
"""Retrieve a registered or lazily registered ToolParser class.
If the parser is lazily registered,
it will be imported and cached on first access.
@@ -301,8 +296,7 @@ class ToolParserManager:
@classmethod
def register_lazy_module(cls, name: str, module_path: str, class_name: str) -> None:
"""
Register a lazy module mapping.
"""Register a lazy module mapping.
Example:
ToolParserManager.register_lazy_module(
@@ -310,6 +304,7 @@ class ToolParserManager:
module_path="vllm.tool_parsers.kimi_k2_parser",
class_name="KimiK2ToolParser",
)
"""
cls.lazy_parsers[name] = (module_path, class_name)
@@ -320,8 +315,7 @@ class ToolParserManager:
force: bool = True,
module: type[ToolParser] | None = None,
) -> type[ToolParser] | Callable[[type[ToolParser]], type[ToolParser]]:
"""
Register module immediately or lazily (as a decorator).
"""Register module immediately or lazily (as a decorator).
Usage:
@ToolParserManager.register_module("kimi_k2")
+22 -24
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Tool call parser for Apertus models.
"""Tool call parser for Apertus models.
Extracts tool calls from the format:
<|tools_prefix|>[{"function_name": {"arg1": "value1", ...}}, ...]<|tools_suffix|>
@@ -45,8 +44,7 @@ TOOL_CALLS_SUFFIX = "<|tools_suffix|>"
class ApertusToolParser(ToolParser):
"""
Tool call parser for Apertus models.
"""Tool call parser for Apertus models.
Handles the extraction of tool calls from text in both non-streaming
(complete string) and streaming (chunked token) environments.
@@ -68,11 +66,11 @@ class ApertusToolParser(ToolParser):
"get_weather"
>>> info.tool_calls[0].function.arguments
'{"city": "Paris"}'
"""
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
"""
Initializes the ApertusToolParser.
"""Initializes the ApertusToolParser.
Args:
tokenizer: The model's tokenizer.
@@ -82,6 +80,7 @@ class ApertusToolParser(ToolParser):
Raises:
ValueError: If the `model_tokenizer`
is not successfully passed to the base class.
"""
super().__init__(tokenizer, tools)
@@ -101,8 +100,7 @@ class ApertusToolParser(ToolParser):
self._reset_streaming_state()
def _reset_streaming_state(self) -> None:
"""
Resets all streaming state variables for a new completion request.
"""Resets all streaming state variables for a new completion request.
This clears the delta text buffer and resets the pointers used to
track the currently streaming tool index and arguments. Called implicitly
@@ -116,8 +114,7 @@ class ApertusToolParser(ToolParser):
def adjust_request(
self, request: ChatCompletionRequest | ResponsesRequest
) -> ChatCompletionRequest | ResponsesRequest:
"""
Adjusts the generation request to ensure special tool tokens are not skipped.
"""Adjusts the generation request to ensure special tool tokens are not skipped.
Forces `skip_special_tokens=False` if tools are actively being evaluated,
ensuring the tools special tokens are surfaced to the engine for parsing.
@@ -127,6 +124,7 @@ class ApertusToolParser(ToolParser):
Returns:
The potentially modified chat completion request.
"""
request = super().adjust_request(request)
if request.tools and request.tool_choice != "none":
@@ -134,8 +132,7 @@ class ApertusToolParser(ToolParser):
return request
def _buffer_delta_text(self, delta_text: str) -> str:
"""
Buffers incoming delta chunks to prevent
"""Buffers incoming delta chunks to prevent
fragmentation of multi-token special tags.
If a chunk ends with a partial match of
@@ -155,6 +152,7 @@ class ApertusToolParser(ToolParser):
"Let me check " # "<|tool" is buffered internally
>>> parser._buffer_delta_text("s_prefix|>" \
"<|tools_prefix|>" # Buffer released on completion
"""
self.buffered_delta_text += delta_text
text = self.buffered_delta_text
@@ -178,8 +176,7 @@ class ApertusToolParser(ToolParser):
model_output: str,
request: ChatCompletionRequest,
) -> ExtractedToolCallInformation:
"""
Extracts tool calls from a completely generated model response (Non-Streaming).
"""Extract tool calls from a complete model response (non-streaming).
Args:
model_output: The full completion string generated by the model.
@@ -200,6 +197,7 @@ class ApertusToolParser(ToolParser):
'Let me see.'
>>> info.tool_calls[0].function.name
'get_weather'
"""
match = self.tool_call_regex.search(model_output)
if not match:
@@ -280,8 +278,7 @@ class ApertusToolParser(ToolParser):
delta_token_ids: Sequence[int],
request: ChatCompletionRequest,
) -> DeltaMessage | None:
"""
Handles streaming chunks
"""Handles streaming chunks.
Args:
previous_text: The complete model text generated prior to this chunk.
@@ -305,6 +302,7 @@ class ApertusToolParser(ToolParser):
... )
>>> msg.tool_calls[0].function.arguments
'ation": "Paris"}'
"""
delta_text = self._buffer_delta_text(delta_text)
if not delta_text:
@@ -323,8 +321,7 @@ class ApertusToolParser(ToolParser):
def _extract_streaming(
self, current_text: str, delta_text: str
) -> DeltaMessage | None:
"""
Core streaming logic.
"""Core streaming logic.
Separates visible chat text from JSON blocks and computes diffs.
Args:
@@ -333,6 +330,7 @@ class ApertusToolParser(ToolParser):
Returns:
A `DeltaMessage` containing the `content` delta and/or `tool_calls` delta.
"""
prefix_idx = current_text.rfind(TOOL_CALLS_PREFIX)
suffix_idx = current_text.rfind(TOOL_CALLS_SUFFIX)
@@ -404,8 +402,7 @@ class ApertusToolParser(ToolParser):
def _parse_and_diff_json(
self, json_str: str, is_final: bool
) -> list[DeltaToolCall]:
"""
Parses an isolated, potentially incomplete streaming JSON array and returns
"""Parses an isolated, potentially incomplete streaming JSON array and returns
newly accumulated tool call diffs.
Args:
@@ -417,6 +414,7 @@ class ApertusToolParser(ToolParser):
A list of `DeltaToolCall`
items representing string diffs in function arguments
to stream back to the client.
"""
try:
parsed, _ = partial_json_loads(json_str, Allow.ALL)
@@ -460,8 +458,7 @@ class ApertusToolParser(ToolParser):
def _emit_tool_name(
self, parsed: list, index: int, tool_calls: list[DeltaToolCall]
) -> None:
"""
Extracts and emits the function name mapped to a new tool call ID.
"""Extracts and emits the function name mapped to a new tool call ID.
Args:
parsed: The partially parsed JSON list containing tool dictionaries.
@@ -472,6 +469,7 @@ class ApertusToolParser(ToolParser):
Appends `DeltaToolCall(index=0,
function=DeltaFunctionCall(name="get_weather", ...))`
to the `tool_calls` list and marks the name as sent.
"""
obj = parsed[index]
if isinstance(obj, dict) and obj:
@@ -491,8 +489,7 @@ class ApertusToolParser(ToolParser):
def _get_tool_diff(
self, parsed: list, index: int, is_final: bool
) -> DeltaToolCall | None:
"""
Calculates the exact string difference to safely append new tool parameters.
"""Calculates the exact string difference to safely append new tool parameters.
This ensures characters like `{`, `}`, and `"` don't jump around unevenly
in the UI frontend while streaming incomplete JSON arguments.
@@ -513,6 +510,7 @@ class ApertusToolParser(ToolParser):
>>> # Returns diff (closing bracket suppressed until final):
>>> parser._get_tool_diff(parsed, index=0, is_final=False)
DeltaToolCall(index=0, function=DeltaFunctionCall(arguments='s'))
"""
obj = parsed[index]
if not isinstance(obj, dict) or not obj:
+1 -2
View File
@@ -29,8 +29,7 @@ logger = init_logger(__name__)
class Ernie45ToolParser(ToolParser):
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
"""
Ernie thinking model format:
"""Ernie thinking model format:
abc\n</think>\n\n\n<tool_call>\ndef\n</tool_call>\n
"""
super().__init__(tokenizer, tools)
@@ -27,8 +27,7 @@ logger = init_logger(__name__)
class FunctionGemmaToolParser(ToolParser):
"""
Tool parser for Google's FunctionGemma model (google/functiongemma-270m-it).
"""Tool parser for Google's FunctionGemma model (google/functiongemma-270m-it).
Handles the FunctionGemma function call format:
<start_function_call>call:func_name{param:<escape>value<escape>}<end_function_call>
+3
View File
@@ -52,6 +52,7 @@ def _parse_tool_arguments(args_str: str) -> dict[str, str]:
Returns:
Dictionary of argument name → string value.
"""
if not args_str or not args_str.strip():
return {}
@@ -95,6 +96,7 @@ def parse_tool_calls(text: str, *, strict: bool = False) -> list[dict]:
>>> tool_calls = parse_tool_calls(output)
>>> for tc in tool_calls:
... print(f"Call: {tc['name']}({tc['arguments']})")
"""
results = []
@@ -150,6 +152,7 @@ def has_tool_response_tag(text: str) -> bool:
>>> if not has_tool_response_tag(model_output):
... # Model used <eos> instead — inject <|tool_response> manually
... next_prompt = "<|tool_response>" + tool_result
"""
stripped = text.rstrip()
return stripped.endswith(_TOOL_RESPONSE_START_TAG)
+1 -2
View File
@@ -15,8 +15,7 @@ if TYPE_CHECKING:
class GptOssToolParser(ToolParser):
"""
Stub tool parser for gpt-oss/harmony models.
"""Stub tool parser for gpt-oss/harmony models.
All output parsing is handled by HarmonyParser. This stub exists as a
capability declaration via HarmonyParser.tool_parser_cls.
@@ -38,8 +38,7 @@ logger = init_logger(__name__)
class Granite20bFCToolParser(ToolParser):
"""
Tool call parser for the granite-20b-functioncalling model intended
"""Tool call parser for the granite-20b-functioncalling model intended
for use with the examples/tool_chat_template_granite20b_fc.jinja
template.
+1 -2
View File
@@ -36,8 +36,7 @@ logger = init_logger(__name__)
class GraniteToolParser(ToolParser):
"""
Tool call parser for the granite 3.0 models. Intended
"""Tool call parser for the granite 3.0 models. Intended
for use with the examples/tool_chat_template_granite.jinja
template.
+2 -1
View File
@@ -219,7 +219,8 @@ class Hermes2ProToolParser(ToolParser):
Returns a ``DeltaMessage`` containing either plain content (for
text preceding any tool call) or one or more ``DeltaToolCall``
entries, or ``None`` if there is nothing new to send yet."""
entries, or ``None`` if there is nothing new to send yet.
"""
try:
# Extract any content before tool calls.
content = self._extract_content(current_text)
@@ -100,9 +100,7 @@ class HunyuanA13BToolParser(ToolParser):
def extract_tool_calls(
self, model_output: str, request: ChatCompletionRequest
) -> ExtractedToolCallInformation:
"""
Extract tool calls from a complete model output.
"""
"""Extract tool calls from a complete model output."""
try:
# Preprocess the model output
content, potential_tool_calls = self.preprocess_model_output(model_output)
@@ -177,10 +175,7 @@ class HunyuanA13BToolParser(ToolParser):
delta_token_ids: Sequence[int],
request: ChatCompletionRequest,
) -> DeltaMessage | None:
"""
Extract tool calls for streaming mode.
"""
"""Extract tool calls for streaming mode."""
start_idx = consume_space(0, current_text)
if current_text[start_idx:].startswith(self.bot_string):
start_idx = consume_space(start_idx + len(self.bot_string), current_text)
+1
View File
@@ -181,6 +181,7 @@ class HYV3ToolParser(ToolParser):
"-3" → int(-3)
Return None on failure.
"""
try:
if "." in value or "e" in value or "E" in value:
+4 -1
View File
@@ -101,8 +101,8 @@ def detect_token_suffix(tokenizer: TokenizerLike) -> str:
RuntimeError: The tokenizer declares the structural tokens through
``model_specific_special_tokens``, which transformers 5 no longer
round-trips.
"""
"""
import transformers
if int(transformers.__version__.split(".")[0]) >= 5:
@@ -611,6 +611,7 @@ class HYV4ToolExtractor:
Returns:
A streaming delta carrying content and/or the tool calls drained
from the buffer, or None when nothing can be emitted yet.
"""
content_delta: str | None = None
tool_calls: list[StreamToolCall] = []
@@ -1011,6 +1012,7 @@ class HYV4ToolParser(ToolParser):
Returns:
The structural tag, or None when structural tagging does not apply.
"""
if not envs.VLLM_ENFORCE_STRICT_TOOL_CALLING:
return None
@@ -1070,6 +1072,7 @@ class HYV4ToolParser(ToolParser):
Returns:
True when the streaming parser must use the string-marker path.
"""
structured_outputs = getattr(request, "structured_outputs", None)
return (
+3 -3
View File
@@ -42,8 +42,7 @@ TOOL_CALL_END = "<|tool_call_end|>"
class Lfm2ToolParser(ToolParser):
"""
Tool call parser for LiquidAI LFM2/LFM2.5 models that produce pythonic
"""Tool call parser for LiquidAI LFM2/LFM2.5 models that produce pythonic
tool calls wrapped in <|tool_call_start|> and <|tool_call_end|> tokens.
Example model output:
@@ -115,7 +114,8 @@ class Lfm2ToolParser(ToolParser):
"""Drop any orphan <|tool_call_end|> (and the preceding text) from
trailing content. LFM2 occasionally echoes the call body after the
first end token and caps it with a second end token; everything
through the last such orphan is model garbage, not user content."""
through the last such orphan is model garbage, not user content.
"""
last_orphan = raw_after.rfind(TOOL_CALL_END)
if last_orphan != -1:
return raw_after[last_orphan + len(TOOL_CALL_END) :]
@@ -31,8 +31,7 @@ logger = init_logger(__name__)
class Llama4PythonicToolParser(ToolParser):
"""
Toolcall parser for Llama4 that produce tool calls in a pythonic style
"""Toolcall parser for Llama4 that produce tool calls in a pythonic style
Use --enable-auto-tool-choice --tool-call-parser llama4_pythonic
"""
@@ -67,10 +66,7 @@ class Llama4PythonicToolParser(ToolParser):
def extract_tool_calls(
self, model_output: str, request: ChatCompletionRequest
) -> ExtractedToolCallInformation:
"""
Extract the tool calls from a complete model response.
"""
"""Extract the tool calls from a complete model response."""
# remove <|python_start|> and <|python_end|>
# as Llama 4 model sometime will output those tokens
if model_output.startswith("<|python_start|>"):
+2 -4
View File
@@ -37,8 +37,7 @@ logger = init_logger(__name__)
class Llama3JsonToolParser(ToolParser):
"""
Tool call parser for Llama 3.x and 4 models intended for use with the
"""Tool call parser for Llama 3.x and 4 models intended for use with the
examples/tool_chat_template_llama.jinja template.
Used when --enable-auto-tool-choice --tool-call-parser llama3_json or
@@ -77,8 +76,7 @@ class Llama3JsonToolParser(ToolParser):
def extract_tool_calls(
self, model_output: str, request: ChatCompletionRequest
) -> ExtractedToolCallInformation:
"""
Extract the tool calls from a complete model response.
"""Extract the tool calls from a complete model response.
Only extracts JSON content and ignores any surrounding plain text.
Supports both single JSON and multiple JSONs separated by semicolons.
"""
+2 -5
View File
@@ -31,8 +31,7 @@ logger = init_logger(__name__)
class Olmo3PythonicToolParser(ToolParser):
"""
Tool call parser for Olmo 3 models that produce tool calls as
"""Tool call parser for Olmo 3 models that produce tool calls as
newline-separated pythonic strings.
Used when --enable-auto-tool-choice --tool-call-parser pythonic are all set
Code copied from pythonic_tool_parser.py and updated to handle
@@ -71,9 +70,7 @@ class Olmo3PythonicToolParser(ToolParser):
def extract_tool_calls(
self, model_output: str, request: ChatCompletionRequest
) -> ExtractedToolCallInformation:
"""
Extract the tool calls from a complete model response.
"""
"""Extract the tool calls from a complete model response."""
original_model_output = model_output
# Remove xml tags.
match = re.search(
+2 -5
View File
@@ -28,8 +28,7 @@ logger = init_logger(__name__)
class Phi4MiniJsonToolParser(ToolParser):
"""
Tool call parser for phi-4-mini models intended for use with the
"""Tool call parser for phi-4-mini models intended for use with the
examples/tool_chat_template_llama.jinja template.
Used when --enable-auto-tool-choice --tool-call-parser phi4_mini_json
@@ -55,9 +54,7 @@ class Phi4MiniJsonToolParser(ToolParser):
def extract_tool_calls(
self, model_output: str, request: ChatCompletionRequest
) -> ExtractedToolCallInformation:
"""
Extract the tool calls from a complete model response.
"""
"""Extract the tool calls from a complete model response."""
logger.debug("Model output: %s", model_output)
pattern = r"functools\[(.*?)\]"
+1 -2
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
GLM-4 Tool Call Parser with incremental string streaming support.
"""GLM-4 Tool Call Parser with incremental string streaming support.
This parser fixes the streaming issue reported in Issue #32829 where long string
parameters (e.g., file content with 4000+ characters of code) are buffered until
+2 -5
View File
@@ -31,8 +31,7 @@ logger = init_logger(__name__)
class PythonicToolParser(ToolParser):
"""
Tool call parser for models that produce tool calls in a pythonic style,
"""Tool call parser for models that produce tool calls in a pythonic style,
such as Llama 3.2 and Llama 4 models.
Used when --enable-auto-tool-choice --tool-call-parser pythonic are all set
@@ -69,9 +68,7 @@ class PythonicToolParser(ToolParser):
def extract_tool_calls(
self, model_output: str, request: ChatCompletionRequest
) -> ExtractedToolCallInformation:
"""
Extract the tool calls from a complete model response.
"""
"""Extract the tool calls from a complete model response."""
is_tool_call_pattern = False
try:
is_tool_call_pattern = (
+1 -2
View File
@@ -32,8 +32,7 @@ logger = init_logger(__name__)
class Step3ToolParser(ToolParser):
"""
Tool parser for a model that uses a specific XML-like format for tool calls.
"""Tool parser for a model that uses a specific XML-like format for tool calls.
This version uses a robust, stateful, cursor-based streaming parser and
consolidates tool arguments into a single message.
"""
+33 -42
View File
@@ -28,8 +28,7 @@ logger = init_logger(__name__)
class StreamingXMLToolCallParser:
"""
Simplified streaming XML tool call parser
"""Simplified streaming XML tool call parser
Supports streaming input, parsing, and output
"""
@@ -46,8 +45,7 @@ class StreamingXMLToolCallParser:
self.parameter_end_token: str = "</parameter>"
def reset_streaming_state(self):
"""Reset streaming parsing state"""
"""Reset streaming parsing state."""
self.deltas = []
# state for streaming
self.tool_call_index = 0
@@ -80,8 +78,7 @@ class StreamingXMLToolCallParser:
self.setup_parser()
def parse_single_streaming_chunks(self, xml_chunk: str) -> DeltaMessage:
"""
Parse single streaming XML chunk and return Delta response
"""Parse single streaming XML chunk and return Delta response
This is the actual streaming interface that receives chunks
one by one and maintains internal state
@@ -90,6 +87,7 @@ class StreamingXMLToolCallParser:
Returns:
DeltaMessage: Contains delta information generated by this chunk,
returns empty response if no complete elements
"""
# Record delta count before processing
initial_delta_count = len(self.deltas)
@@ -218,8 +216,7 @@ class StreamingXMLToolCallParser:
return DeltaMessage(content=None)
def _escape_xml_special_chars(self, text: str) -> str:
"""
Escape XML special characters
"""Escape XML special characters
Args:
text: Original text
Returns:
@@ -239,11 +236,11 @@ class StreamingXMLToolCallParser:
return text
def _process_complete_xml_elements(self) -> bool:
"""
Process complete XML elements in buffer
"""Process complete XML elements in buffer.
Returns:
bool: Whether complete elements were found and processed
"""
found_any = False
@@ -320,8 +317,7 @@ class StreamingXMLToolCallParser:
return found_any
def _fix_incomplete_tag_in_chunk(self, chunk: str) -> str:
"""
Fallback: fix incomplete <parameter=xxx or <function=xxx tags
"""Fallback: fix incomplete <parameter=xxx or <function=xxx tags
(missing >)
Examples: <parameter=-C: -> <parameter=-C>, <parameter=parameter=-n:
-> <parameter=-n>
@@ -386,8 +382,7 @@ class StreamingXMLToolCallParser:
return chunk
def _fix_missing_equals_in_function_tag(self, chunk: str) -> str:
"""
Fix missing = in function tags: <function xxx> or <functionxxx>
"""Fix missing = in function tags: <function xxx> or <functionxxx>
Examples:
<function execute_bash> -> <function=execute_bash>
<functionexecute_bash> -> <function=execute_bash>
@@ -425,7 +420,7 @@ class StreamingXMLToolCallParser:
return chunk
def _validate_function_name(self, func_name: str) -> bool:
"""Check if function name exists in tool definitions"""
"""Check if function name exists in tool definitions."""
if not self.tools:
return False
@@ -442,7 +437,7 @@ class StreamingXMLToolCallParser:
return False
def _validate_parameter_name(self, param_name: str) -> bool:
"""Check if parameter exists in current function's tool definition"""
"""Check if parameter exists in current function's tool definition."""
if not self.tools or not self.current_function_name:
return True
@@ -465,16 +460,15 @@ class StreamingXMLToolCallParser:
return True
def _should_skip_element(self, element: str) -> bool:
"""
Determine whether an element should be skipped
"""Determine whether an element should be skipped.
Args:
element: Element to evaluate
Returns:
bool: True means should skip, False means should process
"""
"""
# If it's a tool_call XML tag, don't skip
if (
element.startswith(self.tool_call_start_token)
@@ -501,8 +495,7 @@ class StreamingXMLToolCallParser:
return not element
def _find_next_complete_element(self, start_pos: int) -> tuple[str | None, int]:
"""
Find next complete XML element from specified position
"""Find next complete XML element from specified position.
Args:
start_pos: Position to start searching
@@ -510,6 +503,7 @@ class StreamingXMLToolCallParser:
Returns:
(Complete element string, element end position),
returns (None, start_pos) if no complete element found
"""
buffer = self.streaming_buffer[start_pos:]
@@ -588,8 +582,7 @@ class StreamingXMLToolCallParser:
return remaining, start_pos + len(remaining)
def _merge_new_deltas_to_single_response(self, initial_count: int) -> DeltaMessage:
"""
Merge newly generated deltas from this processing
"""Merge newly generated deltas from this processing
into a single DeltaMessage
Args:
@@ -597,6 +590,7 @@ class StreamingXMLToolCallParser:
Returns:
Merged DeltaMessage containing all newly generated delta information
"""
if len(self.deltas) <= initial_count:
return DeltaMessage(content=None)
@@ -652,8 +646,7 @@ class StreamingXMLToolCallParser:
)
def _preprocess_xml_chunk(self, chunk: str) -> str:
"""
Preprocess XML chunk, handle non-standard formats,
"""Preprocess XML chunk, handle non-standard formats,
and escape special characters
Args:
@@ -661,8 +654,8 @@ class StreamingXMLToolCallParser:
Returns:
Processed XML chunk
"""
"""
# Check if this is a tool_call related element
is_tool_call = False
if chunk.startswith(self.tool_call_start_token) or chunk.startswith(
@@ -785,7 +778,7 @@ class StreamingXMLToolCallParser:
return processed
def _emit_delta(self, delta: DeltaMessage):
"""Emit Delta response (streaming output)"""
"""Emit Delta response (streaming output)."""
self.deltas.append(delta)
def _auto_close_open_parameter_if_needed(self, incoming_tag: str | None = None):
@@ -814,8 +807,7 @@ class StreamingXMLToolCallParser:
self._end_element("tool_call")
def _start_element(self, name: str, attrs: dict[str, str]):
"""Handle XML start element events"""
"""Handle XML start element events."""
if name == "root":
return
@@ -904,7 +896,7 @@ class StreamingXMLToolCallParser:
self.current_param_is_first = False
def _char_data(self, data: str):
"""Handle XML character data events"""
"""Handle XML character data events."""
if data and self.current_param_name:
# If preprocessing stage determines deferred parsing is needed,
# only cache character data, no streaming output
@@ -979,8 +971,7 @@ class StreamingXMLToolCallParser:
self._emit_delta(delta)
def _end_element(self, name: str):
"""Handle XML end element events"""
"""Handle XML end element events."""
if name == "root":
return
@@ -1154,18 +1145,18 @@ class StreamingXMLToolCallParser:
self._reset_xml_parser_after_tool_call()
def setup_parser(self):
"""Set up XML parser event handlers"""
"""Set up XML parser event handlers."""
self.parser.buffer_text = True
self.parser.StartElementHandler = self._start_element
self.parser.EndElementHandler = self._end_element
self.parser.CharacterDataHandler = self._char_data
def set_tools(self, tools: list[Tool] | None):
"""Set tool configuration information"""
"""Set tool configuration information."""
self.tools = tools
def _extract_function_name(self, name: str, attrs: dict[str, str]) -> str | None:
"""Extract function name from various formats"""
"""Extract function name from various formats."""
if attrs and "name" in attrs:
return attrs["name"]
@@ -1177,7 +1168,7 @@ class StreamingXMLToolCallParser:
return None
def _extract_parameter_name(self, name: str, attrs: dict[str, str]) -> str | None:
"""Extract parameter name from various formats"""
"""Extract parameter name from various formats."""
if attrs and "name" in attrs:
return attrs["name"]
@@ -1195,6 +1186,7 @@ class StreamingXMLToolCallParser:
Returns:
Parameter type
"""
if not self.tools or not self.current_function_name:
return "string"
@@ -1235,6 +1227,7 @@ class StreamingXMLToolCallParser:
Returns:
Repaired parameter type
"""
if (
param_type in ["string", "str", "text", "varchar", "char", "enum"]
@@ -1264,6 +1257,7 @@ class StreamingXMLToolCallParser:
Returns:
Converted value
"""
if param_value.lower() == "null":
return None
@@ -1315,6 +1309,7 @@ class StreamingXMLToolCallParser:
Returns:
Converted string for streaming output
"""
# Check if value is empty, but exclude numeric 0
if converted_value is None or converted_value == "":
@@ -1331,11 +1326,9 @@ class StreamingXMLToolCallParser:
return converted_value
def _reset_xml_parser_after_tool_call(self):
"""
Each tool_call is treated as a separate XML document,
"""Each tool_call is treated as a separate XML document,
so we need to reset the parser after each tool_call.
"""
# recreate XML parser
self.parser = ParserCreate()
self.setup_parser()
@@ -1513,7 +1506,5 @@ class Step3p5ToolParser(ToolParser):
return result
def parser_should_check_for_unstreamed_tool_arg_tokens(self) -> bool:
"""
Skip the remaining_call calculation in serving_chat
"""
"""Skip the remaining_call calculation in serving_chat."""
return False
+1 -3
View File
@@ -113,7 +113,6 @@ def get_model_structural_tag(
token_suffix: str = "",
) -> StructuralTag | None:
"""Build a structural tag with xgrammar's builtin model templates."""
if not tools or tool_choice == "none":
return None
@@ -158,7 +157,6 @@ def _dump_tool_for_xgrammar(
tool: ChatCompletionToolsParam | ResponsesTool,
) -> dict[str, Any]:
"""Convert tool objects to xgrammar's Chat Completions tool protocol."""
if isinstance(tool, FunctionTool):
function: dict[str, Any] = {"name": tool.name}
if tool.description is not None:
@@ -178,7 +176,6 @@ def _dump_tool_choice_for_xgrammar(
tool_choice: ToolChoice,
) -> dict[str, Any] | str | None:
"""Convert tool_choice objects to xgrammar's expected protocol."""
if tool_choice is None:
return None
@@ -783,6 +780,7 @@ def get_hy_v4_structural_tag(
leading colon (e.g. ``":6124c78e"``), or ``""`` when the checkpoint
uses unsuffixed tokens. The HYV4 tool parser reads it off the
tokenizer vocab and passes it to ``get_model_structural_tag``.
"""
del builtin_tools
+11 -7
View File
@@ -56,8 +56,7 @@ def partial_tag_overlap(text: str, tag: str) -> int:
def find_common_prefix(s1: str, s2: str) -> str:
"""
Finds a common prefix that is shared between two strings, if there is one.
"""Finds a common prefix that is shared between two strings, if there is one.
Order of arguments is NOT important.
This function is provided as a UTILITY for extracting information from JSON
@@ -79,8 +78,7 @@ def find_common_prefix(s1: str, s2: str) -> str:
def find_common_suffix(s1: str, s2: str) -> str:
"""
Finds a common suffix shared between two strings, if there is one. Order of
"""Finds a common suffix shared between two strings, if there is one. Order of
arguments is NOT important.
Stops when the suffix ends OR it hits an alphanumeric character
@@ -97,8 +95,7 @@ def find_common_suffix(s1: str, s2: str) -> str:
def extract_intermediate_diff(curr: str, old: str) -> str:
"""
Given two strings, extract the difference in the middle between two strings
"""Given two strings, extract the difference in the middle between two strings
that are known to have a common prefix and/or suffix.
This function is provided as a UTILITY for extracting information from JSON
@@ -429,7 +426,8 @@ def get_json_schema_from_tools(
class UnexpectedAstError(Exception):
"""Raised when the AST structure does not match the expected
pythonic tool call format."""
pythonic tool call format.
"""
pass
@@ -450,6 +448,7 @@ def get_parameter_value(val: ast.expr) -> Any:
Raises:
UnexpectedAstError: If the AST node is not a supported literal type.
"""
if isinstance(val, ast.Constant):
if val.value is None or isinstance(val.value, (str, int, float)):
@@ -528,6 +527,7 @@ def _ast_callable_dotted_name(node: ast.expr) -> str:
Raises:
UnexpectedAstError: If the chain does not bottom out in an
``ast.Name`` (e.g. subscript or call expression as receiver).
"""
parts: list[str] = []
current: ast.expr = node
@@ -550,6 +550,7 @@ def handle_single_tool(call: ast.Call) -> ToolCall:
Raises:
UnexpectedAstError: If the call target is neither a simple name
nor a chain of attribute accesses bottoming out in a name.
"""
if not isinstance(call.func, (ast.Name, ast.Attribute)):
logger.warning(
@@ -921,6 +922,7 @@ def make_valid_python(text: str) -> tuple[str, str] | None:
Raises:
UnexpectedAstError: If mismatched brackets or parentheses
are detected.
"""
bracket_stack: list[str] = []
for index, char in enumerate(text):
@@ -1088,6 +1090,7 @@ def coerce_to_schema_type(value: str, schema_type: str | list[str]) -> Any:
value: The raw string value from the model output.
schema_type: One or more JSON Schema type strings
(e.g. ``"string"`` or ``["string", "null"]``).
"""
if isinstance(schema_type, str):
schema_type = [schema_type]
@@ -1176,6 +1179,7 @@ def compute_tool_delta(
Returns:
A DeltaToolCall with only the new argument characters, or None
if there is no difference from what was previously sent.
"""
new_call_args = new_call.function.arguments
if withheld_suffix: