feat(parsing): per-attempt ParsedToolCall with status + token spans (#22)

This commit is contained in:
hallerite
2026-05-13 13:32:22 +02:00
committed by GitHub
parent 073389004f
commit 3ebfe7b67e
12 changed files with 992 additions and 358 deletions
+4
View File
@@ -15,6 +15,7 @@ from renderers.base import (
MultiModalData,
MultimodalRenderer,
ParsedResponse,
ParsedToolCall,
PlaceholderRange,
RenderedConversation,
RenderedTokens,
@@ -24,6 +25,7 @@ from renderers.base import (
ThinkingPart,
ToolCall,
ToolCallFunction,
ToolCallParseStatus,
ToolSpec,
VideoPart,
build_training_sample,
@@ -66,6 +68,7 @@ __all__ = [
"MultimodalRenderer",
"Nemotron3Renderer",
"ParsedResponse",
"ParsedToolCall",
"PlaceholderRange",
"Qwen3Renderer",
"Qwen3VLRenderer",
@@ -79,6 +82,7 @@ __all__ = [
"ThinkingPart",
"ToolCall",
"ToolCallFunction",
"ToolCallParseStatus",
"ToolSpec",
"VideoPart",
"__version__",
+64 -2
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import enum
import logging
import queue
import threading
@@ -160,13 +161,74 @@ class RenderedTokens:
multi_modal_data: "MultiModalData | None" = None
class ToolCallParseStatus(str, enum.Enum):
"""Per-attempt outcome of parsing a single ``<tool_call>`` block.
The renderer parser's job is JSON-syntax → ``dict`` (the parser-level
contract). Schema validation — required fields, argument types, tool
name lookup — is the *tool*'s job and is intentionally not done here.
See ``ParsedToolCall.status`` for what each value means.
Diverges from vLLM/SGLang on purpose. Both engines collapse parse
failures into either a single ``tools_called: bool`` (vLLM) or silent
drops (SGLang), with no way to express "the model emitted three
parallel tool calls and the second was malformed." Renderers expose
that information because verifier / RL-loss code needs it for
schema-adherence rubrics and selective token masking — use cases the
inference engines don't serve.
"""
OK = "ok"
INVALID_JSON = "invalid_json" # body wasn't valid JSON
UNCLOSED_BLOCK = "unclosed_block" # opening delim hit EOS / stop
MISSING_NAME = "missing_name" # parsed structurally, but no function name
MALFORMED_STRUCTURE = "malformed_structure" # format-specific shape error
@dataclass
class ParsedToolCall:
"""A single ``<tool_call>`` block as the renderer parsed it.
One record per *attempt* — successful and malformed calls both land
here, distinguished by ``status``. Ordering is preserved across the
response, so ``[OK, INVALID_JSON, OK]`` is a faithful record of "the
model emitted three parallel calls; the second was broken."
``token_span`` is a half-open ``[start, end)`` slice into the
completion's stripped token id stream (i.e. ``token_ids`` after
``_strip_stop_tokens``); some text-based parsers can't cheaply
recover token offsets and leave it ``None``. Useful for trainer-side
selective loss masking: zero the mask over the spans of non-OK
entries to avoid reinforcing malformed structures.
``raw`` is the decoded text of the block as the model emitted it
(before any JSON normalization). Always populated — for failed
attempts it's the only way to see what actually went wrong.
"""
raw: str
name: str | None = None
arguments: dict[str, Any] | str | None = None
token_span: tuple[int, int] | None = None
status: ToolCallParseStatus = ToolCallParseStatus.OK
id: str | None = None # native tool-call id when the format carries one (Kimi K2)
@dataclass
class ParsedResponse:
"""Result of parsing completion tokens back into a structured message."""
"""Result of parsing completion tokens back into a structured message.
``tool_calls`` is a list of every parse attempt — successful and
malformed alike. Filter with ``[tc for tc in r.tool_calls if
tc.status == ToolCallParseStatus.OK]`` to get only the calls that
came out clean. Empty list = the model didn't emit any tool calls
(different from "tried and failed entirely", which produces a list
with non-OK entries).
"""
content: str
reasoning_content: str | None = None
tool_calls: list[dict[str, Any]] | None = None
tool_calls: list[ParsedToolCall] = field(default_factory=list)
@dataclass
+18 -5
View File
@@ -19,7 +19,14 @@ from typing import Any, cast
import numpy as np
from openai import AsyncOpenAI, BadRequestError
from renderers.base import Message, MultiModalData, Renderer, RendererPool, ToolSpec
from renderers.base import (
Message,
MultiModalData,
Renderer,
RendererPool,
ToolCallParseStatus,
ToolSpec,
)
_request_logger = logging.getLogger("renderers.client")
@@ -162,11 +169,17 @@ async def generate(
# /inference/v1/generate returns finish_reason in {"stop","length",...} —
# never "tool_calls" (a chat-completions concept). Promote stop→tool_calls
# when we extracted tool calls client-side, so OpenAI-compatible agent
# loops continue past the tool turn instead of treating the response as
# final.
# when we extracted at least one well-formed tool call client-side, so
# OpenAI-compatible agent loops continue past the tool turn instead of
# treating the response as final. Malformed attempts (INVALID_JSON,
# UNCLOSED_BLOCK, ...) don't qualify — those still surface on
# ``parsed.tool_calls`` so verifiers can inspect them, but they don't
# trigger the tool-loop continuation.
finish_reason = choice.get("finish_reason")
if parsed.tool_calls and finish_reason == "stop":
ok_tool_calls = [
tc for tc in parsed.tool_calls if tc.status == ToolCallParseStatus.OK
]
if ok_tool_calls and finish_reason == "stop":
finish_reason = "tool_calls"
return {
+1 -1
View File
@@ -174,7 +174,7 @@ class DefaultRenderer:
content_ids, tool_calls = self._tool_parser.extract(list(token_ids))
else:
content_ids = list(token_ids)
tool_calls = None
tool_calls = []
# 2. Decode (keep special tokens so a downstream reasoning parser can
# still see things like <think>/</think> when they're tokens).
+115 -42
View File
@@ -31,13 +31,16 @@ from renderers.base import (
Message,
MultiModalData,
ParsedResponse,
ParsedToolCall,
PlaceholderRange,
RenderedTokens,
ToolCallParseStatus,
ToolSpec,
reject_assistant_in_extension,
should_preserve_past_thinking,
trim_to_turn_close,
)
from renderers.parsing import parse_kimi_k2_section
from renderers.qwen3_vl import (
_image_hash,
_is_image_part,
@@ -420,12 +423,27 @@ def _parse_kimi_k2_response(
stop_ids: set[int],
think_open_ids: list[int],
think_close_ids: list[int],
tool_calls_section_begin_id: int | None,
tool_calls_section_end_id: int | None,
tool_call_begin_id: int | None,
tool_call_argument_begin_id: int | None,
tool_call_end_id: int | None,
) -> ParsedResponse:
"""Parse Kimi K2/K2.5 completion tokens.
Strips the stop token, decodes to text, then extracts:
- reasoning from ``<think>...</think>`` blocks
- tool calls from ``<|tool_calls_section_begin|>...<|tool_calls_section_end|>``
Primary path: walk token IDs via :func:`parse_kimi_k2_section`. That gives
every ``ParsedToolCall`` a ``token_span`` pointing back into the
(stop-stripped) input — what the trainer needs for selective loss masking.
Fallback path: regex on decoded text. Only used when none of the section
delimiters appear as special tokens, which in practice means the model
emitted the literal ``<|tool_call_section_begin|>`` string (the singular
variant is *not* in the K2.5 special-token vocab — confirmed by tokenizer
probe). Spans stay ``None`` here since text positions don't cheaply map
back to token offsets across BPE.
``<think>...</think>`` is always text-extracted from the content slice
(K2.5 emits them as plain text, not special tokens).
"""
# Strip stop token
ids = list(token_ids)
@@ -434,13 +452,79 @@ def _parse_kimi_k2_response(
ids = ids[:i]
break
# Decode all tokens (including any special tokens that are text-like)
text = tokenizer.decode(ids, skip_special_tokens=False) if ids else ""
# Token-ID path — produces spans. Only run if every relevant special
# token resolved at init (i.e. is in the tokenizer's vocab).
tool_calls: list[ParsedToolCall] = []
have_special_tokens = (
tool_calls_section_begin_id is not None
and tool_calls_section_end_id is not None
and tool_call_begin_id is not None
and tool_call_argument_begin_id is not None
and tool_call_end_id is not None
)
if have_special_tokens:
content_ids, tool_calls = parse_kimi_k2_section(
tokenizer,
ids,
tool_calls_section_begin_ids={tool_calls_section_begin_id},
tool_calls_section_end_ids={tool_calls_section_end_id},
tool_call_begin_id=tool_call_begin_id,
tool_call_argument_begin_id=tool_call_argument_begin_id,
tool_call_end_id=tool_call_end_id,
)
text = (
tokenizer.decode(content_ids, skip_special_tokens=False)
if content_ids
else ""
)
else:
text = tokenizer.decode(ids, skip_special_tokens=False) if ids else ""
# Extract reasoning from <think>...</think>. Partition on <think> first so
# any tokens BEFORE the open tag (e.g. the assistant role tag, when the
# caller slices the completion to include the prompt's gen-prompt-equivalent)
# don't leak into reasoning_content.
# Fallback path: model emitted literal-text section delimiters (singular
# variant) rather than special tokens. Spans unavailable here.
if not tool_calls:
tc_match = _TOOL_CALLS_SECTION_RE.search(text)
if tc_match:
text = text[: tc_match.start()]
tool_section = (
tc_match.group(1)
if tc_match.group(1) is not None
else tc_match.group(2)
)
for m in _TOOL_CALL_RE.finditer(tool_section):
tool_id = m.group(1).strip()
args_str = m.group(2).strip()
name_part = tool_id.split(":", 1)[0]
func_name = (
name_part.split(".", 1)[1] if "." in name_part else name_part
)
arguments: dict[str, Any] | str
invalid_json = False
try:
arguments = json.loads(args_str)
except json.JSONDecodeError:
arguments = args_str
invalid_json = True
if not func_name:
status = ToolCallParseStatus.MISSING_NAME
elif invalid_json:
status = ToolCallParseStatus.INVALID_JSON
else:
status = ToolCallParseStatus.OK
tool_calls.append(
ParsedToolCall(
raw=m.group(0),
name=func_name or None,
arguments=arguments,
status=status,
id=tool_id or None,
)
)
# Extract reasoning from <think>...</think> in the content text. Partition
# on <think> first so any tokens BEFORE the open tag (e.g. the assistant
# role tag, when the caller slices the completion to include the prompt's
# gen-prompt-equivalent) don't leak into reasoning_content.
reasoning: str | None = None
if "<think>" in text:
_, _, after_open = text.partition("<think>")
@@ -449,11 +533,12 @@ def _parse_kimi_k2_response(
reasoning = reasoning_raw.strip("\n") or None
text = text.strip("\n")
else:
# Truncated reasoning (no closing tag)
# Truncated reasoning (no closing tag) — discard any partial
# tool-call attempts since the model never finished thinking.
return ParsedResponse(
content="",
reasoning_content=after_open.strip() or None,
tool_calls=None,
tool_calls=[],
)
elif "</think>" in text:
# Sampler stripped the prefilled <think> open tag — see
@@ -463,35 +548,6 @@ def _parse_kimi_k2_response(
reasoning = before.strip("\n") or None
text = after.strip("\n")
# Extract tool calls section
tool_calls: list[dict[str, Any]] | None = None
tc_match = _TOOL_CALLS_SECTION_RE.search(text)
if tc_match:
text = text[: tc_match.start()]
tool_section = (
tc_match.group(1) if tc_match.group(1) is not None else tc_match.group(2)
)
parsed_calls = []
for m in _TOOL_CALL_RE.finditer(tool_section):
tool_id = m.group(1).strip()
args_str = m.group(2).strip()
# Extract function name from "functions.name:index" format
name_part = tool_id.split(":", 1)[0]
func_name = name_part.split(".", 1)[1] if "." in name_part else name_part
try:
arguments = json.loads(args_str)
except json.JSONDecodeError:
arguments = args_str # preserve raw string if invalid JSON
parsed_calls.append(
{
"type": "function",
"id": tool_id,
"function": {"name": func_name, "arguments": arguments},
}
)
if parsed_calls:
tool_calls = parsed_calls
return ParsedResponse(
content=text.strip(),
reasoning_content=reasoning.strip() if reasoning else None,
@@ -853,17 +909,34 @@ class KimiK25Renderer:
if self._endoftext is not None:
stop_ids.add(self._endoftext)
# Restore the synthetic <think> prefill if it was stripped by the sampler
# Restore the synthetic <think> prefill if it was stripped by the
# sampler. ``parse`` then walks ``normalized``, so any token_span we
# emit is in the *normalized* frame. We track the prepend offset and
# shift spans back so they refer to the caller's ``token_ids``.
normalized = self._normalize_response_tokens(list(token_ids))
prepend_offset = len(normalized) - len(token_ids)
return _parse_kimi_k2_response(
parsed = _parse_kimi_k2_response(
self._tokenizer,
normalized,
stop_ids=stop_ids,
think_open_ids=self._think_open_ids,
think_close_ids=self._think_close_ids,
tool_calls_section_begin_id=self._tool_calls_section_begin,
tool_calls_section_end_id=self._tool_calls_section_end,
tool_call_begin_id=self._tool_call_begin,
tool_call_argument_begin_id=self._tool_call_argument_begin,
tool_call_end_id=self._tool_call_end,
)
if prepend_offset:
for tc in parsed.tool_calls:
if tc.token_span is not None:
start, end = tc.token_span
tc.token_span = (start - prepend_offset, end - prepend_offset)
return parsed
def get_stop_token_ids(self) -> list[int]:
stop = [self._im_end]
if self._endoftext is not None:
+168 -52
View File
@@ -19,6 +19,8 @@ import json
import re
from typing import Protocol, runtime_checkable
from renderers.base import ParsedToolCall, ToolCallParseStatus
# ── Shared helpers ───────────────────────────────────────────────────
@@ -54,15 +56,17 @@ def _token_id(tokenizer, token: str) -> int | None:
class ToolParser(Protocol):
"""Extracts tool calls from completion token ids.
``extract`` returns a tuple ``(content_ids, tool_calls)`` where
``content_ids`` is the remaining content token ids with the tool-call
section removed, and ``tool_calls`` is a list of
``{"function": {"name": str, "arguments": dict | str}}`` dicts or
``None`` when no tool call was found.
``extract`` returns ``(content_ids, tool_calls)`` where ``content_ids``
is the remaining content token ids with the tool-call section removed,
and ``tool_calls`` is a list of :class:`ParsedToolCall` records — one
per attempted block. Empty list = the model emitted no tool calls;
callers filter by ``status == OK`` for the clean subset.
"""
def __init__(self, tokenizer): ...
def extract(self, token_ids: list[int]) -> tuple[list[int], list[dict] | None]: ...
def extract(
self, token_ids: list[int]
) -> tuple[list[int], list[ParsedToolCall]]: ...
@runtime_checkable
@@ -87,14 +91,14 @@ class Qwen3ToolParser:
self._tc_id = _token_id(tokenizer, "<tool_call>")
self._tc_end_id = _token_id(tokenizer, "</tool_call>")
def extract(self, ids: list[int]) -> tuple[list[int], list[dict] | None]:
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
if self._tc_id is None:
return ids, None
return ids, []
tc_start = _find(ids, self._tc_id)
if tc_start == -1:
return ids, None
return ids, []
content_ids = ids[:tc_start]
tool_calls: list[dict] = []
tool_calls: list[ParsedToolCall] = []
i = tc_start
while i < len(ids):
if ids[i] == self._tc_id:
@@ -103,25 +107,52 @@ class Qwen3ToolParser:
if self._tc_end_id is not None
else -1
)
unclosed = end == -1
if end == -1:
end = len(ids)
tc_text = _decode(self._tokenizer, ids[i + 1 : end]).strip()
span = (i, end + (0 if unclosed else 1))
if unclosed:
tool_calls.append(
ParsedToolCall(
raw=tc_text,
token_span=span,
status=ToolCallParseStatus.UNCLOSED_BLOCK,
)
)
break
try:
parsed = json.loads(tc_text)
tool_calls.append(
{
"function": {
"name": parsed.get("name", ""),
"arguments": parsed.get("arguments", {}),
}
}
)
except json.JSONDecodeError:
pass
tool_calls.append(
ParsedToolCall(
raw=tc_text,
token_span=span,
status=ToolCallParseStatus.INVALID_JSON,
)
)
else:
name = parsed.get("name", "") if isinstance(parsed, dict) else ""
arguments = (
parsed.get("arguments", {}) if isinstance(parsed, dict) else {}
)
tool_calls.append(
ParsedToolCall(
raw=tc_text,
name=name or None,
arguments=arguments,
token_span=span,
status=(
ToolCallParseStatus.MISSING_NAME
if not name
else ToolCallParseStatus.OK
),
)
)
i = end + 1
else:
i += 1
return content_ids, (tool_calls or None)
return content_ids, tool_calls
class Qwen35ToolParser:
@@ -132,13 +163,13 @@ class Qwen35ToolParser:
self._tc_id = _token_id(tokenizer, "<tool_call>")
self._tc_end_id = _token_id(tokenizer, "</tool_call>")
def extract(self, ids: list[int]) -> tuple[list[int], list[dict] | None]:
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
if self._tc_id is None:
return ids, None
return ids, []
tc_start = _find(ids, self._tc_id)
if tc_start == -1:
return ids, None
tool_calls: list[dict] = []
return ids, []
tool_calls: list[ParsedToolCall] = []
i = tc_start
while i < len(ids):
if ids[i] == self._tc_id:
@@ -148,30 +179,60 @@ class Qwen35ToolParser:
else -1
)
if end == -1:
raw = _decode(self._tokenizer, ids[i + 1 :])
tool_calls.append(
ParsedToolCall(
raw=raw,
token_span=(i, len(ids)),
status=ToolCallParseStatus.UNCLOSED_BLOCK,
)
)
break
block_text = _decode(self._tokenizer, ids[i + 1 : end])
span = (i, end + 1)
name_match = re.search(r"<function=([^>]+)>", block_text)
if name_match:
name = name_match.group(1)
arguments: dict = {}
for pm in re.finditer(
r"<parameter=([^>]+)>\n?(.*?)\n?</parameter>",
block_text,
re.DOTALL,
):
arg_name = pm.group(1)
arg_value = pm.group(2).strip()
try:
arguments[arg_name] = json.loads(arg_value)
except (json.JSONDecodeError, ValueError):
arguments[arg_name] = arg_value
if not name_match:
tool_calls.append(
{"function": {"name": name, "arguments": arguments}}
ParsedToolCall(
raw=block_text,
token_span=span,
status=ToolCallParseStatus.MALFORMED_STRUCTURE,
)
)
i = end + 1
continue
name = name_match.group(1)
arguments: dict = {}
any_json_fallback = False
for pm in re.finditer(
r"<parameter=([^>]+)>\n?(.*?)\n?</parameter>",
block_text,
re.DOTALL,
):
arg_name = pm.group(1)
arg_value = pm.group(2).strip()
try:
arguments[arg_name] = json.loads(arg_value)
except (json.JSONDecodeError, ValueError):
arguments[arg_name] = arg_value
any_json_fallback = True
tool_calls.append(
ParsedToolCall(
raw=block_text,
name=name,
arguments=arguments,
token_span=span,
status=(
ToolCallParseStatus.INVALID_JSON
if any_json_fallback
else ToolCallParseStatus.OK
),
)
)
i = end + 1
else:
i += 1
return ids[:tc_start], (tool_calls or None)
return ids[:tc_start], tool_calls
class GlmToolParser:
@@ -186,13 +247,13 @@ class GlmToolParser:
self._av_id = _token_id(tokenizer, "<arg_value>")
self._ave_id = _token_id(tokenizer, "</arg_value>")
def extract(self, ids: list[int]) -> tuple[list[int], list[dict] | None]:
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
if self._tc_id is None:
return ids, None
return ids, []
tc_start = _find(ids, self._tc_id)
if tc_start == -1:
return ids, None
tool_calls: list[dict] = []
return ids, []
tool_calls: list[ParsedToolCall] = []
i = tc_start
while i < len(ids):
if ids[i] == self._tc_id:
@@ -202,9 +263,21 @@ class GlmToolParser:
else -1
)
if end == -1:
raw = _decode(self._tokenizer, ids[i + 1 :])
tool_calls.append(
ParsedToolCall(
raw=raw,
token_span=(i, len(ids)),
status=ToolCallParseStatus.UNCLOSED_BLOCK,
)
)
break
block = ids[i + 1 : end]
block_text = _decode(self._tokenizer, block)
span = (i, end + 1)
first_ak = _find(block, self._ak_id) if self._ak_id is not None else -1
any_json_fallback = False
structure_broke = False
if first_ak == -1:
name = _decode(self._tokenizer, block).strip()
arguments: dict = {}
@@ -220,6 +293,7 @@ class GlmToolParser:
else -1
)
if ake == -1:
structure_broke = True
break
key = _decode(self._tokenizer, block[j + 1 : ake]).strip()
av = (
@@ -228,6 +302,7 @@ class GlmToolParser:
else -1
)
if av == -1:
structure_broke = True
break
ave = (
_find(block, self._ave_id, av + 1)
@@ -235,6 +310,7 @@ class GlmToolParser:
else -1
)
if ave == -1:
structure_broke = True
break
val_text = _decode(
self._tokenizer, block[av + 1 : ave]
@@ -243,14 +319,31 @@ class GlmToolParser:
arguments[key] = json.loads(val_text)
except (json.JSONDecodeError, ValueError):
arguments[key] = val_text
any_json_fallback = True
j = ave + 1
else:
j += 1
tool_calls.append({"function": {"name": name, "arguments": arguments}})
if not name:
status = ToolCallParseStatus.MISSING_NAME
elif structure_broke:
status = ToolCallParseStatus.MALFORMED_STRUCTURE
elif any_json_fallback:
status = ToolCallParseStatus.INVALID_JSON
else:
status = ToolCallParseStatus.OK
tool_calls.append(
ParsedToolCall(
raw=block_text,
name=name or None,
arguments=arguments,
token_span=span,
status=status,
)
)
i = end + 1
else:
i += 1
return ids[:tc_start], (tool_calls or None)
return ids[:tc_start], tool_calls
class DeepSeekV3ToolParser:
@@ -264,12 +357,12 @@ class DeepSeekV3ToolParser:
self._tc_end = _token_id(tokenizer, "<|tool▁call▁end|>")
self._sep = _token_id(tokenizer, "<|tool▁sep|>")
def extract(self, ids: list[int]) -> tuple[list[int], list[dict] | None]:
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
if self._tcs_begin is None:
return ids, None
return ids, []
section_start = _find(ids, self._tcs_begin)
if section_start == -1:
return ids, None
return ids, []
content_ids = ids[:section_start]
section_end = (
_find(ids, self._tcs_end, section_start + 1)
@@ -278,9 +371,10 @@ class DeepSeekV3ToolParser:
)
if section_end == -1:
section_end = len(ids)
inner_offset = section_start + 1
section_ids = ids[section_start + 1 : section_end]
tool_calls: list[dict] = []
tool_calls: list[ParsedToolCall] = []
i = 0
while i < len(section_ids):
if self._tc_begin is None or section_ids[i] != self._tc_begin:
@@ -291,23 +385,45 @@ class DeepSeekV3ToolParser:
if self._tc_end is not None
else -1
)
unclosed = end == -1
if end == -1:
end = len(section_ids)
block_text = _decode(self._tokenizer, section_ids[i + 1 : end])
span = (inner_offset + i, inner_offset + end + (0 if unclosed else 1))
# Format: "function<|tool▁sep|>{name}\n```json\n{args}\n```"
name_match = re.search(r"^\s*\w+.*?([A-Za-z0-9_]+)\s*\n", block_text)
name = name_match.group(1) if name_match else ""
args: dict | str = {}
invalid_json = False
json_match = re.search(r"```json\s*(.*?)\s*```", block_text, re.DOTALL)
if json_match:
try:
args = json.loads(json_match.group(1))
except (json.JSONDecodeError, ValueError):
args = json_match.group(1)
tool_calls.append({"function": {"name": name, "arguments": args}})
invalid_json = True
if unclosed:
status = ToolCallParseStatus.UNCLOSED_BLOCK
elif not name:
status = ToolCallParseStatus.MISSING_NAME
elif invalid_json:
status = ToolCallParseStatus.INVALID_JSON
else:
status = ToolCallParseStatus.OK
tool_calls.append(
ParsedToolCall(
raw=block_text,
name=name or None,
arguments=args,
token_span=span,
status=status,
)
)
i = end + 1
if unclosed:
break
return content_ids, (tool_calls or None)
return content_ids, tool_calls
# ── Reasoning parsers ────────────────────────────────────────────────
+427 -179
View File
File diff suppressed because it is too large Load Diff
+65 -27
View File
@@ -3,7 +3,12 @@ import base64
import numpy as np
from renderers.base import ParsedResponse, RenderedTokens
from renderers.base import (
ParsedResponse,
ParsedToolCall,
RenderedTokens,
ToolCallParseStatus,
)
from renderers.client import generate
@@ -30,12 +35,12 @@ class _FakeRenderer:
content="done",
reasoning_content="think",
tool_calls=[
{
"function": {
"name": "echo",
"arguments": {"text": "hello"},
}
}
ParsedToolCall(
raw='{"name": "echo", "arguments": {"text": "hello"}}',
name="echo",
arguments={"text": "hello"},
status=ToolCallParseStatus.OK,
)
],
)
@@ -111,26 +116,59 @@ def test_generate_builds_request_body_and_parses_response():
},
}
# finish_reason promoted from "stop" → "tool_calls" because the renderer
# extracted tool calls client-side.
assert result == {
"request_id": "gen-test",
"prompt_ids": [1, 2, 3],
"completion_ids": [7, 8],
"completion_logprobs": [-0.1, -0.2],
"content": "done",
"reasoning_content": "think",
"tool_calls": [
{
"function": {
"name": "echo",
"arguments": {"text": "hello"},
}
}
],
"finish_reason": "tool_calls",
"routed_experts": [[[1]], [[2]]],
"multi_modal_data": None,
}
# extracted at least one well-formed tool call client-side.
assert result["finish_reason"] == "tool_calls"
assert result["content"] == "done"
assert result["reasoning_content"] == "think"
assert result["prompt_ids"] == [1, 2, 3]
assert result["completion_ids"] == [7, 8]
assert result["completion_logprobs"] == [-0.1, -0.2]
assert result["routed_experts"] == [[[1]], [[2]]]
assert result["multi_modal_data"] is None
assert result["request_id"] == "gen-test"
assert len(result["tool_calls"]) == 1
tc = result["tool_calls"][0]
assert tc.name == "echo"
assert tc.arguments == {"text": "hello"}
assert tc.status == ToolCallParseStatus.OK
class _MalformedToolRenderer(_FakeRenderer):
"""Returns only a malformed tool-call attempt — finish_reason must stay "stop"."""
def parse_response(self, completion_ids: list[int]) -> ParsedResponse:
return ParsedResponse(
content="",
reasoning_content=None,
tool_calls=[
ParsedToolCall(
raw='{"name": "echo", broken',
status=ToolCallParseStatus.INVALID_JSON,
)
],
)
def test_generate_does_not_promote_finish_reason_for_malformed_tool_calls():
"""A malformed tool-call attempt must NOT promote finish_reason to
"tool_calls" — only well-formed (status=OK) calls qualify. The
malformed attempt is still preserved in ``tool_calls`` for verifier
inspection, but the agent loop should not treat the turn as a
successful tool invocation.
"""
client = _FakeClient()
result = asyncio.run(
generate(
client=client,
renderer=_MalformedToolRenderer(),
messages=[{"role": "user", "content": "hi"}],
model="test-model",
tools=[{"type": "function", "function": {"name": "echo"}}],
)
)
assert result["finish_reason"] == "stop"
assert len(result["tool_calls"]) == 1
assert result["tool_calls"][0].status == ToolCallParseStatus.INVALID_JSON
class _NoRenderRenderer(_FakeRenderer):
+62 -20
View File
@@ -7,7 +7,7 @@ Runs against every (model, renderer) pair.
from functools import lru_cache
from renderers import create_renderer
from renderers.base import load_tokenizer
from renderers.base import ToolCallParseStatus, load_tokenizer
@lru_cache
@@ -62,18 +62,26 @@ def test_qwen3_vl_parse_json_tool_call():
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
assert parsed.content == "Need a tool."
assert parsed.tool_calls == [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
]
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "get_weather"
assert tc.arguments == {"city": "Paris"}
def test_qwen3_vl_malformed_tool_call_falls_back_to_content():
"""When <tool_call>...</tool_call> contains malformed JSON, match
vLLM's hermes_tool_parser behavior: preserve the raw tokens as
content rather than returning empty content + empty tool_calls.
Without this, the orchestrator raises EmptyModelResponseError and
wastes inference compute on retries — diverging from main's
behavior on hermes tool envs (Qwen3, etc.).
def test_qwen3_vl_malformed_tool_call_surfaces_as_invalid_json():
"""A malformed ``<tool_call>`` block lands as a non-OK ``ParsedToolCall``
rather than getting silently merged back into ``content``.
Before the per-call status redesign, the parser mirrored vLLM's
hermes parser and stuffed the raw block into ``content`` to avoid
downstream ``EmptyModelResponseError``. That hid the malformed signal
from verifiers — they couldn't tell "model wrote prose" from "model
tried a tool call and produced broken JSON." Now the failed attempt
is preserved with ``status=INVALID_JSON`` and ``raw`` text, which
also satisfies the EmptyModelResponseError prevention contract: the
response is non-empty (it has a tool-call attempt) without lying
about what kind of output the model produced.
"""
tokenizer, renderer = _qwen3_vl()
# Note the trailing comma — malformed JSON
@@ -83,13 +91,47 @@ def test_qwen3_vl_malformed_tool_call_falls_back_to_content():
)
parsed = renderer.parse_response(tokenizer.encode(text, add_special_tokens=False))
# Parser must not collapse response: either content has the raw
# tokens OR there's at least a tool_call attempt. Concretely, we
# want content to be non-empty so the caller doesn't raise
# EmptyModelResponseError.
assert parsed.tool_calls is None, "Malformed JSON should not parse as a tool call"
assert parsed.content, (
"Malformed tool_call should fall back to raw content, not empty "
"(else caller raises EmptyModelResponseError)"
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.INVALID_JSON
assert "get_weather" in tc.raw
assert tc.token_span is not None
@lru_cache
def _kimi_k25():
tokenizer = load_tokenizer("moonshotai/Kimi-K2.5")
renderer = create_renderer(tokenizer, renderer="auto")
return tokenizer, renderer
def test_kimi_k25_tool_call_carries_token_span():
"""K2.5 was the lone parser without token spans before — its inline
text-walking implementation couldn't cheaply map regex hits back to
token offsets. We now walk token IDs via ``parse_kimi_k2_section`` for
the special-token path; spans must round-trip and point at a sensible
range within the original input token_ids.
"""
tokenizer, renderer = _kimi_k25()
# K2.5 tool-call wire shape: section + per-call special tokens.
text = (
"<|tool_calls_section_begin|>"
"<|tool_call_begin|>functions.get_weather:0"
"<|tool_call_argument_begin|>"
'{"city": "Tokyo"}'
"<|tool_call_end|>"
"<|tool_calls_section_end|>"
)
token_ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(token_ids)
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "get_weather"
assert tc.arguments == {"city": "Tokyo"}
assert tc.token_span is not None
start, end = tc.token_span
assert 0 <= start < end <= len(token_ids), (
f"span {tc.token_span} out of range for {len(token_ids)} input tokens"
)
assert "get_weather" in parsed.content
+13 -7
View File
@@ -4,7 +4,7 @@ These test that parse_response never crashes and returns sensible results
even with adversarial or truncated model output.
"""
from renderers.base import ParsedResponse
from renderers.base import ParsedResponse, ParsedToolCall
# ── Truncation ───────────────────────────────────────────────────────
@@ -78,7 +78,7 @@ def test_content_only_no_thinking(model_name, tokenizer, renderer):
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert "Hello" in parsed.content
assert parsed.tool_calls is None
assert parsed.tool_calls == []
# ── Tool call edge cases ─────────────────────────────────────────────
@@ -128,11 +128,17 @@ def test_reasoning_is_string_or_none(model_name, tokenizer, renderer):
assert parsed.reasoning_content is None or isinstance(parsed.reasoning_content, str)
def test_tool_calls_is_list_or_none(model_name, tokenizer, renderer):
"""tool_calls must be list or None, never empty list."""
def test_tool_calls_is_list_of_parsed_tool_call(model_name, tokenizer, renderer):
"""tool_calls is always a (possibly empty) list of ParsedToolCall — never None.
Empty list = "model did not emit any tool calls". A list with non-OK
entries = "model tried and the parser caught the failure"; those are
deliberately preserved so verifier / RL-loss code can see them. This
replaces the older list-or-None convention.
"""
text = "Hello!"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert parsed.tool_calls is None or (
isinstance(parsed.tool_calls, list) and len(parsed.tool_calls) > 0
)
assert isinstance(parsed.tool_calls, list)
for tc in parsed.tool_calls:
assert isinstance(tc, ParsedToolCall)
+46 -8
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import pytest
from renderers.base import load_tokenizer
from renderers.base import ToolCallParseStatus, load_tokenizer
from renderers.parsers import (
REASONING_PARSERS,
TOOL_PARSERS,
@@ -40,9 +40,12 @@ def test_qwen3_tool_parser_roundtrip():
completion_text = 'hello\n<tool_call>\n{"name": "search", "arguments": {"q": "rain"}}\n</tool_call>'
token_ids = tok.encode(completion_text, add_special_tokens=False)
content_ids, tool_calls = parser.extract(list(token_ids))
assert tool_calls is not None
assert tool_calls[0]["function"]["name"] == "search"
assert tool_calls[0]["function"]["arguments"] == {"q": "rain"}
assert len(tool_calls) == 1
tc = tool_calls[0]
assert tc.status == ToolCallParseStatus.OK
assert tc.name == "search"
assert tc.arguments == {"q": "rain"}
assert tc.token_span is not None and tc.token_span[0] < tc.token_span[1]
# content_ids should cover everything up to (but not including) <tool_call>
content_text = tok.decode(content_ids, skip_special_tokens=False)
assert "hello" in content_text
@@ -54,10 +57,44 @@ def test_qwen3_tool_parser_no_tool_call():
parser = get_tool_parser("qwen3", tok)
ids = tok.encode("just plain text response", add_special_tokens=False)
content_ids, tool_calls = parser.extract(list(ids))
assert tool_calls is None
assert tool_calls == []
assert content_ids == list(ids)
def test_qwen3_tool_parser_records_invalid_json():
"""Malformed JSON in a <tool_call> block surfaces as INVALID_JSON, not silently dropped."""
tok = load_tokenizer("Qwen/Qwen3-0.6B")
parser = get_tool_parser("qwen3", tok)
completion = (
'hi\n<tool_call>\n{"name": "f", "arguments": {broken json\n</tool_call>'
)
ids = tok.encode(completion, add_special_tokens=False)
_, tool_calls = parser.extract(list(ids))
assert len(tool_calls) == 1
assert tool_calls[0].status == ToolCallParseStatus.INVALID_JSON
assert tool_calls[0].raw # raw block text preserved
def test_qwen3_tool_parser_parallel_partial_success():
"""Parallel calls: parser keeps the good ones AND records the broken one."""
tok = load_tokenizer("Qwen/Qwen3-0.6B")
parser = get_tool_parser("qwen3", tok)
completion = (
"pre\n"
'<tool_call>\n{"name": "a", "arguments": {}}\n</tool_call>\n'
"<tool_call>\n{broken\n</tool_call>\n"
'<tool_call>\n{"name": "c", "arguments": {"x": 1}}\n</tool_call>'
)
ids = tok.encode(completion, add_special_tokens=False)
_, tool_calls = parser.extract(list(ids))
assert [tc.status for tc in tool_calls] == [
ToolCallParseStatus.OK,
ToolCallParseStatus.INVALID_JSON,
ToolCallParseStatus.OK,
]
assert [tc.name for tc in tool_calls] == ["a", None, "c"]
def test_think_reasoning_parser_extracts_block():
tok = load_tokenizer("Qwen/Qwen3-0.6B")
parser = get_reasoning_parser("think", tok)
@@ -90,8 +127,9 @@ def test_default_renderer_uses_parsers():
parsed = renderer.parse_response(list(ids))
assert parsed.reasoning_content == "think"
assert parsed.content.startswith("ok")
assert parsed.tool_calls is not None
assert parsed.tool_calls[0]["function"]["name"] == "f"
assert len(parsed.tool_calls) == 1
assert parsed.tool_calls[0].name == "f"
assert parsed.tool_calls[0].status == ToolCallParseStatus.OK
def test_default_renderer_without_parsers_is_backward_compatible():
@@ -106,4 +144,4 @@ def test_default_renderer_without_parsers_is_backward_compatible():
parsed = renderer.parse_response(list(ids))
assert parsed.reasoning_content == "r"
assert parsed.content == "a"
assert parsed.tool_calls is None
assert parsed.tool_calls == []
+9 -15
View File
@@ -158,8 +158,8 @@ def test_roundtrip_reasoning_and_content(rt_model, rt_tokenizer, rt_renderer):
def _maybe_skip_tool_calls(renderer_name: str) -> None:
"""DefaultRenderer without a tool_parser configured always returns
tool_calls=None. That's a documented limitation, not a bug — skip."""
"""DefaultRenderer without a tool_parser configured always returns an
empty tool_calls list. That's a documented limitation, not a bug — skip."""
if renderer_name == "default":
pytest.skip(
"DefaultRenderer requires an explicit tool_parser to parse tool "
@@ -194,11 +194,9 @@ def test_roundtrip_single_tool_call(
assert parsed.tool_calls, f"{rt_model}: tool_calls lost, got {parsed.tool_calls!r}"
assert len(parsed.tool_calls) == 1
tc = parsed.tool_calls[0]
assert tc["function"]["name"] == "get_weather", (
f"{rt_model}: name mangled, got {tc!r}"
)
assert _normalize_args(tc["function"]["arguments"]) == {"city": "Tokyo"}, (
f"{rt_model}: args mangled, got {tc['function']['arguments']!r}"
assert tc.name == "get_weather", f"{rt_model}: name mangled, got {tc!r}"
assert _normalize_args(tc.arguments) == {"city": "Tokyo"}, (
f"{rt_model}: args mangled, got {tc.arguments!r}"
)
@@ -235,19 +233,15 @@ def test_roundtrip_multiple_tool_calls(
completion_ids = _extract_assistant_tokens(rt_renderer, PROMPT, msg)
parsed = rt_renderer.parse_response(completion_ids)
assert parsed.tool_calls is not None and len(parsed.tool_calls) == 2, (
assert len(parsed.tool_calls) == 2, (
f"{rt_model}: expected 2 tool_calls, got {parsed.tool_calls!r}"
)
names = [tc["function"]["name"] for tc in parsed.tool_calls]
names = [tc.name for tc in parsed.tool_calls]
assert names == ["get_weather", "get_time"], (
f"{rt_model}: names/order wrong, got {names}"
)
assert _normalize_args(parsed.tool_calls[0]["function"]["arguments"]) == {
"city": "Tokyo"
}
assert _normalize_args(parsed.tool_calls[1]["function"]["arguments"]) == {
"zone": "JST"
}
assert _normalize_args(parsed.tool_calls[0].arguments) == {"city": "Tokyo"}
assert _normalize_args(parsed.tool_calls[1].arguments) == {"zone": "JST"}
# ── byte-exact re-render invariant ─────────────────────────────────────