Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
562db77eff | ||
|
|
40620409ed | ||
|
|
f99428a35b | ||
|
|
2c2aa00d42 | ||
|
|
3ebfe7b67e | ||
|
|
073389004f |
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for describing the origin of the Work and
|
||||
reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Support. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or support.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Prime Intellect
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -141,3 +141,7 @@ uv run pytest
|
||||
```
|
||||
|
||||
Round-trip parity (render → parse → original) and token-level parity against `apply_chat_template` are tested per renderer. End-to-end validation runs against Reverse-Text, Wordle, OpenCode-Math, and RLM-SWE environments.
|
||||
|
||||
## License
|
||||
|
||||
Licensed under the [Apache License, Version 2.0](LICENSE).
|
||||
|
||||
@@ -31,6 +31,24 @@ CUDA_VISIBLE_DEVICES=1 uv run --script examples/sglang/multiturn_generate_sglang
|
||||
The SGLang script uses `input_ids`, so SGLang does not apply a chat template.
|
||||
It leaves `openai-harmony` at SGLang's pinned version for dependency resolution.
|
||||
|
||||
### SGLang HTTP Recipe (online)
|
||||
|
||||
For a token-in/token-out HTTP path against an already-running SGLang server:
|
||||
|
||||
```bash
|
||||
sglang serve --model-path Qwen/Qwen3.5-4B \
|
||||
--host 0.0.0.0 --port 30000 --tensor-parallel-size 1 --trust-remote-code &
|
||||
|
||||
uv run python examples/sglang/online_multiturn_sglang.py \
|
||||
--base-url http://localhost:30000 --model Qwen/Qwen3.5-4B
|
||||
```
|
||||
|
||||
The HTTP recipe posts `input_ids` to `/generate`; streaming is intentionally
|
||||
unsupported because `parse_response`/`bridge_to_next_turn` require the full
|
||||
completion. The source-checkout command above uses the local `renderers`
|
||||
package; the PEP 723 `uv run --script` form requires a published package that
|
||||
satisfies the script header.
|
||||
|
||||
## Transformers Multi-Turn Recipe
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
#!/usr/bin/env -S uv run --script
|
||||
# /// script
|
||||
# requires-python = ">=3.10,<3.14"
|
||||
# dependencies = [
|
||||
# "renderers>=0.1.6",
|
||||
# "transformers>=5.3.0",
|
||||
# "httpx>=0.27",
|
||||
# "openai-harmony==0.0.4",
|
||||
# "tiktoken",
|
||||
# "jinja2",
|
||||
# "numpy",
|
||||
# ]
|
||||
# ///
|
||||
"""SGLang online generation from renderer-owned prompt token IDs.
|
||||
|
||||
Mirrors `multiturn_generate_sglang.py` but talks to an already-running SGLang
|
||||
HTTP server over `/generate` instead of an in-process `sgl.Engine`. The
|
||||
renderer owns chat templating and parsing; SGLang only does token-in,
|
||||
token-out.
|
||||
|
||||
Streaming is intentionally not supported: `parse_response` and
|
||||
`bridge_to_next_turn` both need the complete `completion_ids`.
|
||||
|
||||
Launch a server first, e.g.
|
||||
|
||||
sglang serve --model-path Qwen/Qwen3.5-4B \\
|
||||
--host 0.0.0.0 --port 30000 --tensor-parallel-size 1 --trust-remote-code
|
||||
|
||||
then, from a source checkout,
|
||||
|
||||
uv run python examples/sglang/online_multiturn_sglang.py \\
|
||||
--base-url http://localhost:30000 --model Qwen/Qwen3.5-4B
|
||||
|
||||
The PEP 723 `uv run --script` form requires a published `renderers` package
|
||||
that satisfies the script header.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from renderers.base import Renderer
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "multiply",
|
||||
"description": "Multiply two integers.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"a": {"type": "integer"},
|
||||
"b": {"type": "integer"},
|
||||
},
|
||||
"required": ["a", "b"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def make_renderer(model: str, enable_thinking: bool | None) -> Renderer:
|
||||
tokenizer = AutoTokenizer.from_pretrained(model, trust_remote_code=False)
|
||||
if model.startswith("Qwen/Qwen3.5-"):
|
||||
return Qwen35Renderer(tokenizer, enable_thinking=enable_thinking)
|
||||
if model == "openai/gpt-oss-20b":
|
||||
return GptOssRenderer(tokenizer)
|
||||
raise ValueError(f"unsupported demo model: {model}")
|
||||
|
||||
|
||||
def completion_ids(output: dict, prompt_ids: list[int]) -> list[int]:
|
||||
ids = list(output.get("output_ids") or output.get("token_ids") or [])
|
||||
if not ids:
|
||||
raise RuntimeError("SGLang did not return completion token IDs")
|
||||
# Match offline recipe: strip prefix only if SGLang echoed the prompt back.
|
||||
return ids[len(prompt_ids) :] if ids[: len(prompt_ids)] == prompt_ids else ids
|
||||
|
||||
|
||||
async def generate_sglang(
|
||||
*,
|
||||
client: httpx.AsyncClient,
|
||||
base_url: str,
|
||||
renderer: Renderer,
|
||||
prompt_ids: list[int],
|
||||
max_new_tokens: int,
|
||||
extra_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
body: dict[str, Any] = {
|
||||
"input_ids": prompt_ids,
|
||||
"sampling_params": {
|
||||
"temperature": 0.0,
|
||||
"max_new_tokens": max_new_tokens,
|
||||
"stop_token_ids": renderer.get_stop_token_ids(),
|
||||
"skip_special_tokens": False,
|
||||
"no_stop_trim": True,
|
||||
},
|
||||
"stream": False,
|
||||
}
|
||||
if extra_key is not None:
|
||||
body["extra_key"] = extra_key
|
||||
response = await client.post(f"{base_url.rstrip('/')}/generate", json=body)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
def print_parsed(label: str, turn: str, parsed) -> None:
|
||||
print(f"\n[{label}] {turn}")
|
||||
if parsed.reasoning_content:
|
||||
print(f"reasoning: {parsed.reasoning_content[:240]}")
|
||||
if parsed.tool_calls:
|
||||
print(f"tool_calls: {json.dumps(parsed.tool_calls, ensure_ascii=False)}")
|
||||
if parsed.content:
|
||||
print(f"content: {parsed.content}")
|
||||
|
||||
|
||||
async def run_one(
|
||||
*,
|
||||
client: httpx.AsyncClient,
|
||||
base_url: str,
|
||||
model: str,
|
||||
enable_thinking: bool | None,
|
||||
max_new_tokens: int,
|
||||
) -> None:
|
||||
label = (
|
||||
model
|
||||
if enable_thinking is None
|
||||
else f"{model} enable_thinking={enable_thinking}"
|
||||
)
|
||||
print(f"\n=== {label} ===")
|
||||
|
||||
renderer = make_renderer(model, enable_thinking)
|
||||
|
||||
messages: list[dict[str, Any]] = [
|
||||
{"role": "system", "content": "You are a concise tool-using assistant."},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Use the multiply tool for 17 * 23, then summarize.",
|
||||
},
|
||||
]
|
||||
|
||||
# Turn 1: render locally, send token IDs. SGLang never sees messages.
|
||||
prompt_ids = renderer.render_ids(messages, tools=TOOLS, add_generation_prompt=True)
|
||||
output1 = await generate_sglang(
|
||||
client=client,
|
||||
base_url=base_url,
|
||||
renderer=renderer,
|
||||
prompt_ids=prompt_ids,
|
||||
max_new_tokens=max_new_tokens,
|
||||
)
|
||||
completion1 = completion_ids(output1, prompt_ids)
|
||||
parsed1 = renderer.parse_response(completion1)
|
||||
print_parsed(label, "turn 1", parsed1)
|
||||
|
||||
assistant: dict[str, Any] = {"role": "assistant", "content": parsed1.content}
|
||||
if parsed1.reasoning_content:
|
||||
assistant["reasoning_content"] = parsed1.reasoning_content
|
||||
if parsed1.tool_calls:
|
||||
assistant["tool_calls"] = parsed1.tool_calls
|
||||
messages.append(assistant)
|
||||
|
||||
if parsed1.tool_calls:
|
||||
new_messages: list[dict[str, Any]] = []
|
||||
for idx, tool_call in enumerate(parsed1.tool_calls):
|
||||
fn = tool_call.get("function") or tool_call
|
||||
tool_args = fn.get("arguments") or {}
|
||||
if isinstance(tool_args, str):
|
||||
tool_args = json.loads(tool_args)
|
||||
new_messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.get("id", f"call_{idx}"),
|
||||
"name": fn.get("name", "multiply"),
|
||||
"content": json.dumps(
|
||||
{"result": int(tool_args["a"]) * int(tool_args["b"])}
|
||||
),
|
||||
}
|
||||
)
|
||||
else:
|
||||
new_messages = [
|
||||
{"role": "user", "content": "Give the final answer in one sentence."}
|
||||
]
|
||||
|
||||
# Turn 2: bridge extends prompt_ids + completion1 exactly.
|
||||
bridged_ids = renderer.bridge_to_next_turn(
|
||||
prompt_ids, completion1, new_messages, tools=TOOLS
|
||||
)
|
||||
if bridged_ids is None:
|
||||
raise RuntimeError("bridge_to_next_turn returned None")
|
||||
assert bridged_ids[: len(prompt_ids) + len(completion1)] == (
|
||||
prompt_ids + completion1
|
||||
)
|
||||
|
||||
output2 = await generate_sglang(
|
||||
client=client,
|
||||
base_url=base_url,
|
||||
renderer=renderer,
|
||||
prompt_ids=bridged_ids,
|
||||
max_new_tokens=max_new_tokens,
|
||||
)
|
||||
completion2 = completion_ids(output2, bridged_ids)
|
||||
print_parsed(label, "turn 2", renderer.parse_response(completion2))
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--base-url",
|
||||
default="http://localhost:30000",
|
||||
help="SGLang HTTP server base URL.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--model",
|
||||
default="Qwen/Qwen3.5-4B",
|
||||
help="Must match the model the SGLang server is serving.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--enable-thinking",
|
||||
choices=["true", "false", "both"],
|
||||
default="both",
|
||||
help="Qwen3.5 thinking mode. Ignored for gpt-oss.",
|
||||
)
|
||||
parser.add_argument("--max-new-tokens", type=int, default=512)
|
||||
parser.add_argument("--timeout", type=float, default=600.0)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.model.startswith("Qwen/Qwen3.5-"):
|
||||
if args.enable_thinking == "both":
|
||||
modes: list[bool | None] = [True, False]
|
||||
else:
|
||||
modes = [args.enable_thinking == "true"]
|
||||
else:
|
||||
modes = [None]
|
||||
|
||||
async with httpx.AsyncClient(timeout=args.timeout) as client:
|
||||
for mode in modes:
|
||||
await run_one(
|
||||
client=client,
|
||||
base_url=args.base_url,
|
||||
model=args.model,
|
||||
enable_thinking=mode,
|
||||
max_new_tokens=args.max_new_tokens,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -11,6 +11,8 @@ name = "renderers"
|
||||
dynamic = ["version"]
|
||||
description = "Chat template renderers — deterministic message-to-token conversion for LLM training"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
license-files = ["LICENSE"]
|
||||
requires-python = ">=3.10,<3.14"
|
||||
dependencies = [
|
||||
"numpy",
|
||||
|
||||
@@ -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,
|
||||
@@ -41,6 +43,7 @@ from renderers.glm45 import GLM45Renderer
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.kimi_k2 import KimiK2Renderer
|
||||
from renderers.kimi_k25 import KimiK25Renderer
|
||||
from renderers.laguna_xs2 import LagunaXS2Renderer
|
||||
from renderers.minimax_m2 import MiniMaxM2Renderer
|
||||
from renderers.nemotron3 import Nemotron3Renderer
|
||||
from renderers.qwen3 import Qwen3Renderer
|
||||
@@ -59,6 +62,7 @@ __all__ = [
|
||||
"ImagePart",
|
||||
"KimiK2Renderer",
|
||||
"KimiK25Renderer",
|
||||
"LagunaXS2Renderer",
|
||||
"MULTIMODAL_MODELS",
|
||||
"Message",
|
||||
"MiniMaxM2Renderer",
|
||||
@@ -66,6 +70,7 @@ __all__ = [
|
||||
"MultimodalRenderer",
|
||||
"Nemotron3Renderer",
|
||||
"ParsedResponse",
|
||||
"ParsedToolCall",
|
||||
"PlaceholderRange",
|
||||
"Qwen3Renderer",
|
||||
"Qwen3VLRenderer",
|
||||
@@ -79,6 +84,7 @@ __all__ = [
|
||||
"ThinkingPart",
|
||||
"ToolCall",
|
||||
"ToolCallFunction",
|
||||
"ToolCallParseStatus",
|
||||
"ToolSpec",
|
||||
"VideoPart",
|
||||
"__version__",
|
||||
|
||||
+87
-6
@@ -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
|
||||
@@ -235,8 +297,23 @@ class Renderer(Protocol):
|
||||
"""Render messages to token IDs (without attribution metadata)."""
|
||||
...
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
"""Parse completion tokens back into a structured message."""
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
"""Parse completion tokens back into a structured message.
|
||||
|
||||
``tools`` is the same list passed to ``render`` for this turn.
|
||||
XML-style formats (Qwen3.5, GLM, MiniMax, Laguna) render argument
|
||||
values verbatim inside ``<arg_value>`` tags with no quoting, so
|
||||
a value like ``true`` is ambiguous between bool and the string
|
||||
``"true"``. When ``tools`` is supplied, the parser consults each
|
||||
parameter's declared JSON-schema type to preserve string args
|
||||
verbatim. Without ``tools``, parsers fall back to the historical
|
||||
``json.loads``-with-text-fallback behavior.
|
||||
"""
|
||||
...
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
@@ -541,6 +618,8 @@ MODEL_RENDERER_MAP: dict[str, str] = {
|
||||
# Nemotron 3.
|
||||
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "nemotron-3",
|
||||
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "nemotron-3",
|
||||
# Poolside Laguna.
|
||||
"poolside/Laguna-XS.2": "laguna-xs.2",
|
||||
# GPT-OSS.
|
||||
"openai/gpt-oss-20b": "gpt-oss",
|
||||
"openai/gpt-oss-120b": "gpt-oss",
|
||||
@@ -677,6 +756,7 @@ def _populate_registry():
|
||||
from renderers.gpt_oss import GptOssRenderer
|
||||
from renderers.kimi_k2 import KimiK2Renderer
|
||||
from renderers.kimi_k25 import KimiK25Renderer
|
||||
from renderers.laguna_xs2 import LagunaXS2Renderer
|
||||
from renderers.minimax_m2 import MiniMaxM2Renderer
|
||||
from renderers.nemotron3 import Nemotron3Renderer
|
||||
from renderers.qwen3 import Qwen3Renderer
|
||||
@@ -698,6 +778,7 @@ def _populate_registry():
|
||||
"deepseek-v3": DeepSeekV3Renderer,
|
||||
"kimi-k2": KimiK2Renderer,
|
||||
"kimi-k2.5": KimiK25Renderer,
|
||||
"laguna-xs.2": LagunaXS2Renderer,
|
||||
"nemotron-3": Nemotron3Renderer,
|
||||
"gpt-oss": GptOssRenderer,
|
||||
}
|
||||
@@ -762,8 +843,8 @@ def create_renderer(
|
||||
tokenizer: HuggingFace tokenizer instance.
|
||||
renderer: Renderer name ('qwen3', 'qwen3-vl', 'qwen3.5', 'qwen3.6',
|
||||
'glm-5', 'glm-5.1', 'glm-4.5', 'minimax-m2', 'deepseek-v3',
|
||||
'kimi-k2', 'kimi-k2.5', 'nemotron-3', 'gpt-oss', 'default')
|
||||
or 'auto' to detect from model name.
|
||||
'kimi-k2', 'kimi-k2.5', 'laguna-xs.2', 'nemotron-3',
|
||||
'gpt-oss', 'default') or 'auto' to detect from model name.
|
||||
tool_parser: Name of a tool parser registered in ``renderers.parsers``.
|
||||
Only consumed by DefaultRenderer. Model-specific renderers
|
||||
have their own parsing wired in.
|
||||
|
||||
+19
-6
@@ -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")
|
||||
|
||||
@@ -143,7 +150,7 @@ async def generate(
|
||||
completion_ids = choice.get("token_ids") or []
|
||||
|
||||
parsed = await _maybe_offload(
|
||||
renderer, lambda: renderer.parse_response(completion_ids)
|
||||
renderer, lambda: renderer.parse_response(completion_ids, tools=tools)
|
||||
)
|
||||
|
||||
# ChatCompletionLogProbs flatten: {"content": [{"logprob": ...}, ...]}
|
||||
@@ -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 {
|
||||
|
||||
@@ -221,7 +221,12 @@ class DeepSeekV3Renderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — args land in a ```json fence, schema not needed
|
||||
) -> ParsedResponse:
|
||||
return parse_deepseek_v3(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
|
||||
@@ -167,14 +167,19 @@ class DefaultRenderer:
|
||||
messages, tools=tools, add_generation_prompt=add_generation_prompt
|
||||
)
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — DefaultRenderer relies on configured tool_parser, schema not consulted here
|
||||
) -> ParsedResponse:
|
||||
# 1. Extract tool calls while we still have token ids (most formats
|
||||
# use special-token delimiters, so id-level matching is reliable).
|
||||
if self._tool_parser is not None:
|
||||
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).
|
||||
|
||||
+7
-1
@@ -214,7 +214,12 @@ class GLM45Renderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_glm(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
@@ -227,6 +232,7 @@ class GLM45Renderer:
|
||||
arg_key_end_id=self._arg_key_end,
|
||||
arg_value_id=self._arg_value,
|
||||
arg_value_end_id=self._arg_value_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
|
||||
+7
-1
@@ -226,7 +226,12 @@ class GLM5Renderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_glm(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
@@ -239,6 +244,7 @@ class GLM5Renderer:
|
||||
arg_key_end_id=self._arg_key_end,
|
||||
arg_value_id=self._arg_value,
|
||||
arg_value_end_id=self._arg_value_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
|
||||
@@ -307,7 +307,12 @@ class GptOssRenderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — harmony args land in a JSON object, schema not needed
|
||||
) -> ParsedResponse:
|
||||
return parse_gpt_oss(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
|
||||
@@ -279,7 +279,12 @@ class KimiK2Renderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — section-JSON wire format quotes strings, schema not needed
|
||||
) -> ParsedResponse:
|
||||
return parse_kimi_k2(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
|
||||
+137
-44
@@ -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,
|
||||
@@ -795,6 +851,7 @@ class KimiK25Renderer:
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_ids=emit_ids,
|
||||
emit_image=emit_image,
|
||||
)
|
||||
elif msg.get("content") is not None:
|
||||
# User / other content branches — images allowed.
|
||||
@@ -848,22 +905,44 @@ class KimiK25Renderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — section-JSON wire format quotes strings, schema not needed
|
||||
) -> ParsedResponse:
|
||||
stop_ids: set[int] = {self._im_end}
|
||||
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:
|
||||
@@ -956,6 +1035,7 @@ class KimiK25Renderer:
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_ids=emit_ids,
|
||||
emit_image=emit_image,
|
||||
)
|
||||
elif msg.get("content") is not None:
|
||||
self._emit_content(
|
||||
@@ -1168,6 +1248,7 @@ class KimiK25Renderer:
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_ids,
|
||||
emit_image=None,
|
||||
) -> None:
|
||||
"""Emit tool-result body (after the role tag): ``## Return of {id}\\n``
|
||||
+ content. No ``<|im_end|>``; caller emits that.
|
||||
@@ -1175,12 +1256,24 @@ class KimiK25Renderer:
|
||||
The K2.5 template emits the ``## Return of …`` header unconditionally
|
||||
— when ``tool_call_id`` is missing the interpolation yields empty
|
||||
string and you get ``## Return of \\n``. We mirror that.
|
||||
|
||||
``emit_image`` is threaded through to ``_emit_content`` so image parts
|
||||
inside ``content`` lists (browser-agent screenshots, etc.) render as
|
||||
``<|media_begin|>image<|media_content|><|media_pad|><|media_end|>``
|
||||
inline. Without it those parts are silently dropped.
|
||||
"""
|
||||
tool_call_id = msg.get("tool_call_id") or ""
|
||||
emit_text(f"## Return of {tool_call_id}\n", msg_idx)
|
||||
content = msg.get("content")
|
||||
if content is not None:
|
||||
self._emit_content(content, msg_idx, emit_special, emit_text, emit_ids)
|
||||
self._emit_content(
|
||||
content,
|
||||
msg_idx,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_ids,
|
||||
emit_image=emit_image,
|
||||
)
|
||||
|
||||
def _normalize_response_tokens(self, response: list[int]) -> list[int]:
|
||||
"""Restore the synthetic ``<think>`` prefill if the sampler stripped it.
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
"""Laguna-XS.2 Renderer.
|
||||
|
||||
Main properties:
|
||||
- Prefix is the single token ``〈|EOS|〉`` (also the EOS / stop token).
|
||||
- Role markers are block-style: ``<system>...</system>``, ``<user>...</user>``,
|
||||
``<assistant>...</assistant>``, ``<tool_response>...</tool_response>``. Of
|
||||
these, only ``<assistant>`` / ``</assistant>`` are single (added) tokens
|
||||
in the tokenizer; everything else is plain text and BPEs into multiple
|
||||
subwords.
|
||||
- Assistant turn has an explicit close: ``</assistant>`` is the canonical
|
||||
stop token (alongside ``〈|EOS|〉``).
|
||||
- Tool calls: ``<tool_call>`` / ``</tool_call>`` ARE single tokens, but the
|
||||
inner ``<arg_key>`` / ``</arg_key>`` / ``<arg_value>`` / ``</arg_value>``
|
||||
markers are plain text — parsed via regex on the decoded inner block.
|
||||
- The template bakes in a default system prompt when ``messages[0]`` is not
|
||||
a system message. The system block also contains the tools section (under
|
||||
a ``### Tools`` header with an ``<available_tools>`` listing and prose
|
||||
format instructions that vary on ``enable_thinking``).
|
||||
- Reasoning is rendered for every assistant message — no last-user-index
|
||||
gating. ``preserve_all_thinking`` and
|
||||
``preserve_thinking_between_tool_calls`` are accepted for protocol
|
||||
uniformity but are effectively no-ops since past reasoning is preserved
|
||||
by default.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from renderers.base import (
|
||||
Content,
|
||||
Message,
|
||||
ParsedResponse,
|
||||
RenderedTokens,
|
||||
ToolSpec,
|
||||
reject_assistant_in_extension,
|
||||
)
|
||||
from renderers.parsing import parse_laguna_xs2
|
||||
|
||||
_DEFAULT_SYSTEM_MESSAGE = (
|
||||
"You are a helpful, conversationally-fluent assistant made by Poolside. "
|
||||
"You are here to be helpful to users through natural language conversations."
|
||||
)
|
||||
|
||||
_TOOLS_HEADER = (
|
||||
"\n\n### Tools\n\n"
|
||||
"You may call functions to assist with the user query.\n"
|
||||
"All available function signatures are listed below:\n"
|
||||
"<available_tools>\n"
|
||||
)
|
||||
|
||||
_TOOLS_FOOTER_THINKING = (
|
||||
"</available_tools>\n\n"
|
||||
"Wrap your thinking in '<think>', '</think>' tags, followed by a function call. "
|
||||
"For each function call, return an unescaped XML-like object with function name "
|
||||
"and arguments within '<tool_call>' and '</tool_call>' tags, like here:\n"
|
||||
"<think> your thoughts here </think>\n"
|
||||
"<tool_call>function-name\n"
|
||||
"<arg_key>argument-key</arg_key>\n"
|
||||
"<arg_value>value-of-argument-key</arg_value>\n"
|
||||
"</tool_call>"
|
||||
)
|
||||
|
||||
_TOOLS_FOOTER_NO_THINKING = (
|
||||
"</available_tools>\n\n"
|
||||
"For each function call, return an unescaped XML-like object with function name "
|
||||
"and arguments within '<tool_call>' and '</tool_call>' tags, like here:\n"
|
||||
"<tool_call>function-name\n"
|
||||
"<arg_key>argument-key</arg_key>\n"
|
||||
"<arg_value>value-of-argument-key</arg_value>\n"
|
||||
"</tool_call>"
|
||||
)
|
||||
|
||||
|
||||
class LagunaXS2Renderer:
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
*,
|
||||
enable_thinking: bool = False,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
):
|
||||
self._tokenizer = tokenizer
|
||||
self._enable_thinking = enable_thinking
|
||||
# Accepted for protocol uniformity. The chat template renders
|
||||
# reasoning on every assistant message regardless, so flipping
|
||||
# these flags has no effect on the byte-level output.
|
||||
self._preserve_all_thinking = preserve_all_thinking
|
||||
self._preserve_thinking_between_tool_calls = (
|
||||
preserve_thinking_between_tool_calls
|
||||
)
|
||||
|
||||
self._eos = self._token_id("〈|EOS|〉")
|
||||
self._think = self._token_id("<think>")
|
||||
self._think_end = self._token_id("</think>")
|
||||
self._assistant = self._token_id("<assistant>")
|
||||
self._assistant_end = self._token_id("</assistant>")
|
||||
self._tool_call = self._token_id("<tool_call>")
|
||||
self._tool_call_end = self._token_id("</tool_call>")
|
||||
|
||||
def _token_id(self, token: str) -> int:
|
||||
tid = self._tokenizer.convert_tokens_to_ids(token)
|
||||
assert isinstance(tid, int) and tid != self._tokenizer.unk_token_id, (
|
||||
f"Special token {token!r} not found in tokenizer vocabulary"
|
||||
)
|
||||
return tid
|
||||
|
||||
def _encode(self, text: str) -> list[int]:
|
||||
if not text:
|
||||
return []
|
||||
return self._tokenizer.encode(text, add_special_tokens=False)
|
||||
|
||||
@staticmethod
|
||||
def _visible_text(content: Content | None) -> str:
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for item in content:
|
||||
if isinstance(item, dict) and item.get("type") == "text":
|
||||
parts.append(item.get("text", ""))
|
||||
return "".join(parts)
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _thinking_text(content: Content | None) -> str:
|
||||
"""Concatenate ``ThinkingPart`` entries from list-form content.
|
||||
|
||||
Used as a reasoning source in ``_render_assistant`` when neither
|
||||
``reasoning`` nor ``reasoning_content`` is present on the message.
|
||||
Returns ``""`` for any non-list input.
|
||||
"""
|
||||
if not isinstance(content, list):
|
||||
return ""
|
||||
parts: list[str] = []
|
||||
for item in content:
|
||||
if isinstance(item, dict) and item.get("type") == "thinking":
|
||||
parts.append(item.get("thinking", ""))
|
||||
return "".join(parts)
|
||||
|
||||
def render(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> RenderedTokens:
|
||||
if not messages:
|
||||
raise ValueError("No messages provided.")
|
||||
|
||||
tokens: list[int] = []
|
||||
indices: list[int] = []
|
||||
|
||||
def emit_special(token_id: int, msg_idx: int) -> None:
|
||||
tokens.append(token_id)
|
||||
indices.append(msg_idx)
|
||||
|
||||
def emit_text(text: str, msg_idx: int) -> None:
|
||||
ids = self._encode(text)
|
||||
tokens.extend(ids)
|
||||
indices.extend([msg_idx] * len(ids))
|
||||
|
||||
emit_special(self._eos, -1)
|
||||
|
||||
# ── System header (absorbs messages[0] if it's a system message) ──
|
||||
system_content = _DEFAULT_SYSTEM_MESSAGE
|
||||
system_msg_idx = -1
|
||||
if messages and messages[0].get("role") == "system":
|
||||
system_content = self._visible_text(messages[0].get("content"))
|
||||
system_msg_idx = 0
|
||||
|
||||
has_sys_content = bool(system_content and system_content.strip())
|
||||
# Mirrors the template's ``(system_message and system_message.strip()) or tools``
|
||||
# gate: when the caller passes an empty system message and no tools,
|
||||
# the whole ``<system>...</system>`` block is omitted.
|
||||
if has_sys_content or tools:
|
||||
# The template emits ``<system>\n`` then conditionally a second
|
||||
# ``\n``. Bundle those into one emit so BPE merges ``\n\n`` into
|
||||
# its single-token form (rather than two ``\n`` atoms).
|
||||
emit_text("<system>\n\n" if has_sys_content else "<system>\n", -1)
|
||||
if has_sys_content:
|
||||
emit_text(system_content.rstrip(), system_msg_idx)
|
||||
if tools:
|
||||
tool_text = _TOOLS_HEADER
|
||||
for tool in tools:
|
||||
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
|
||||
tool_text += (
|
||||
_TOOLS_FOOTER_THINKING
|
||||
if self._enable_thinking
|
||||
else _TOOLS_FOOTER_NO_THINKING
|
||||
)
|
||||
emit_text(tool_text, -1)
|
||||
emit_text("\n</system>\n", -1)
|
||||
|
||||
# ── Per-message loop ──────────────────────────────────────────
|
||||
for i, msg in enumerate(messages):
|
||||
content = self._visible_text(msg.get("content"))
|
||||
|
||||
match msg["role"]:
|
||||
case "system":
|
||||
# Already consumed in the header block.
|
||||
if i == 0:
|
||||
continue
|
||||
emit_text("<system>\n" + content + "\n</system>\n", i)
|
||||
case "user":
|
||||
emit_text("<user>\n" + content + "\n</user>\n", i)
|
||||
case "assistant":
|
||||
self._render_assistant(
|
||||
msg, i, content, emit_special=emit_special, emit_text=emit_text
|
||||
)
|
||||
case "tool":
|
||||
emit_text("<tool_response>\n" + content + "\n</tool_response>\n", i)
|
||||
|
||||
# ── Generation prompt ─────────────────────────────────────────
|
||||
if add_generation_prompt:
|
||||
emit_special(self._assistant, -1)
|
||||
emit_text("\n", -1)
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think, -1)
|
||||
else:
|
||||
emit_special(self._think_end, -1)
|
||||
|
||||
return RenderedTokens(token_ids=tokens, message_indices=indices)
|
||||
|
||||
def render_ids(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> list[int]:
|
||||
return self.render(
|
||||
messages,
|
||||
tools=tools,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_laguna_xs2(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
stop_ids={self._assistant_end, self._eos},
|
||||
think_id=self._think,
|
||||
think_end_id=self._think_end,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
return [self._assistant_end, self._eos]
|
||||
|
||||
def bridge_to_next_turn(
|
||||
self,
|
||||
previous_prompt_ids: list[int],
|
||||
previous_completion_ids: list[int],
|
||||
new_messages: list[Message],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> RenderedTokens | None:
|
||||
if (
|
||||
not previous_prompt_ids
|
||||
or not new_messages
|
||||
or reject_assistant_in_extension(new_messages)
|
||||
):
|
||||
return None
|
||||
|
||||
# The canonical assistant-turn close is ``</assistant>``. ``〈|EOS|〉``
|
||||
# also stops generation; either being the final token means the turn
|
||||
# ended cleanly. Truncation (no stop token at the tail) synthesises
|
||||
# ``</assistant>\n`` — the same scaffold the template emits.
|
||||
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
|
||||
stop_ids = {self._assistant_end, self._eos}
|
||||
if (
|
||||
not previous_ids[len(previous_prompt_ids) :]
|
||||
or previous_ids[-1] not in stop_ids
|
||||
):
|
||||
previous_ids.append(self._assistant_end)
|
||||
previous_ids.extend(self._encode("\n"))
|
||||
|
||||
ext: list[int] = []
|
||||
|
||||
def emit_special(token_id: int, _msg_idx: int = -1) -> None:
|
||||
ext.append(token_id)
|
||||
|
||||
def emit_text(text: str, _msg_idx: int = -1) -> None:
|
||||
ext.extend(self._encode(text))
|
||||
|
||||
for msg in new_messages:
|
||||
role = msg.get("role")
|
||||
content = self._visible_text(msg.get("content"))
|
||||
if role == "user":
|
||||
emit_text("<user>\n" + content + "\n</user>\n")
|
||||
elif role == "system":
|
||||
emit_text("<system>\n" + content + "\n</system>\n")
|
||||
elif role == "tool":
|
||||
emit_text("<tool_response>\n" + content + "\n</tool_response>\n")
|
||||
else:
|
||||
return None
|
||||
|
||||
emit_special(self._assistant)
|
||||
emit_text("\n")
|
||||
if self._enable_thinking:
|
||||
emit_special(self._think)
|
||||
else:
|
||||
emit_special(self._think_end)
|
||||
|
||||
return RenderedTokens(token_ids=previous_ids + ext)
|
||||
|
||||
def _render_assistant(
|
||||
self,
|
||||
msg: Message,
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
) -> None:
|
||||
reasoning_content = ""
|
||||
if isinstance(msg.get("reasoning_content"), str):
|
||||
reasoning_content = msg["reasoning_content"]
|
||||
else:
|
||||
# When the caller stores reasoning as a ``ThinkingPart`` inside
|
||||
# a list-form ``content`` (e.g. after parse_response →
|
||||
# reserialize), pull it out here so it survives the re-render.
|
||||
part_thinking = self._thinking_text(msg.get("content"))
|
||||
if part_thinking:
|
||||
reasoning_content = part_thinking
|
||||
|
||||
emit_special(self._assistant, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
|
||||
if reasoning_content:
|
||||
emit_special(self._think, msg_idx)
|
||||
emit_text("\n" + reasoning_content.strip() + "\n", msg_idx)
|
||||
emit_special(self._think_end, msg_idx)
|
||||
else:
|
||||
emit_special(self._think_end, msg_idx)
|
||||
|
||||
# Combined newline-after-</think> with optional content. Bundling
|
||||
# preserves BPE merges across the boundary.
|
||||
post_think_text = "\n"
|
||||
if content.strip():
|
||||
post_think_text += content.strip() + "\n"
|
||||
emit_text(post_think_text, msg_idx)
|
||||
|
||||
tool_calls = msg.get("tool_calls") or []
|
||||
for tc in tool_calls:
|
||||
func = tc.get("function") or tc
|
||||
name = func.get("name", "")
|
||||
arguments = func.get("arguments", {})
|
||||
if isinstance(arguments, str):
|
||||
try:
|
||||
arguments = json.loads(arguments)
|
||||
except json.JSONDecodeError:
|
||||
arguments = {}
|
||||
|
||||
emit_special(self._tool_call, msg_idx)
|
||||
inner = name + "\n"
|
||||
if isinstance(arguments, dict):
|
||||
for k, v in arguments.items():
|
||||
inner += "<arg_key>" + k + "</arg_key>\n"
|
||||
if isinstance(v, str):
|
||||
val_text = v
|
||||
else:
|
||||
val_text = json.dumps(v, ensure_ascii=False)
|
||||
inner += "<arg_value>" + val_text + "</arg_value>\n"
|
||||
emit_text(inner, msg_idx)
|
||||
emit_special(self._tool_call_end, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
|
||||
emit_special(self._assistant_end, msg_idx)
|
||||
emit_text("\n", msg_idx)
|
||||
@@ -223,7 +223,12 @@ class MiniMaxM2Renderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_minimax(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
@@ -232,6 +237,7 @@ class MiniMaxM2Renderer:
|
||||
think_end_id=self._think_end,
|
||||
tool_call_id=self._tool_call_tok,
|
||||
tool_call_end_id=self._tool_call_end_tok,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
|
||||
@@ -384,7 +384,12 @@ class Nemotron3Renderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — args land in a JSON object, schema not needed
|
||||
) -> ParsedResponse:
|
||||
stop_ids = {self._im_end}
|
||||
if self._endoftext is not None:
|
||||
stop_ids.add(self._endoftext)
|
||||
|
||||
+168
-52
@@ -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 ────────────────────────────────────────────────
|
||||
|
||||
+665
-183
File diff suppressed because it is too large
Load Diff
+6
-1
@@ -209,7 +209,12 @@ class Qwen3Renderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — hermes wire format quotes strings, schema not needed
|
||||
) -> ParsedResponse:
|
||||
return parse_qwen3(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
|
||||
+55
-7
@@ -439,9 +439,9 @@ class Qwen35Renderer:
|
||||
self._render_tool(
|
||||
messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_image=emit_image,
|
||||
)
|
||||
|
||||
else:
|
||||
@@ -487,7 +487,12 @@ class Qwen35Renderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None,
|
||||
) -> ParsedResponse:
|
||||
return parse_qwen35(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
@@ -496,6 +501,7 @@ class Qwen35Renderer:
|
||||
think_end_id=self._think_end,
|
||||
tool_call_id=self._tool_call,
|
||||
tool_call_end_id=self._tool_call_end,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self) -> list[int]:
|
||||
@@ -539,7 +545,7 @@ class Qwen35Renderer:
|
||||
def emit_text(text: str, _msg_idx: int = -1) -> None:
|
||||
tokens.extend(self._encode(text))
|
||||
|
||||
def emit_image(part: dict[str, Any]) -> None:
|
||||
def emit_image(part: dict[str, Any], _msg_idx: int = -1) -> None:
|
||||
_, out, n, h = self._process_image(part)
|
||||
emit_special(self._vision_start)
|
||||
offset = len(tokens)
|
||||
@@ -613,9 +619,9 @@ class Qwen35Renderer:
|
||||
self._render_tool(
|
||||
new_messages,
|
||||
i,
|
||||
content,
|
||||
emit_special=emit_special,
|
||||
emit_text=emit_text,
|
||||
emit_image=emit_image,
|
||||
)
|
||||
else:
|
||||
return None
|
||||
@@ -793,16 +799,20 @@ class Qwen35Renderer:
|
||||
self,
|
||||
messages: list[Message],
|
||||
msg_idx: int,
|
||||
content: str,
|
||||
*,
|
||||
emit_special,
|
||||
emit_text,
|
||||
emit_image,
|
||||
) -> None:
|
||||
# Consecutive tool messages are grouped under a single <|im_start|>user block
|
||||
# Consecutive tool messages share a single <|im_start|>user ... <|im_end|>
|
||||
# envelope. Whether to open and close the envelope depends only on the
|
||||
# neighbouring roles, never on the content type of this or any other
|
||||
# tool message — keep this predicate text/media-agnostic.
|
||||
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
|
||||
next_is_tool = (
|
||||
msg_idx + 1 < len(messages) and messages[msg_idx + 1]["role"] == "tool"
|
||||
)
|
||||
raw_content = messages[msg_idx].get("content")
|
||||
|
||||
if not prev_is_tool:
|
||||
emit_special(self._im_start, msg_idx)
|
||||
@@ -810,7 +820,45 @@ class Qwen35Renderer:
|
||||
|
||||
emit_text("\n", msg_idx)
|
||||
emit_special(self._tool_response, msg_idx)
|
||||
emit_text("\n" + content + "\n", msg_idx)
|
||||
|
||||
if self._content_has_media(raw_content):
|
||||
# Mirror the chat template's ``render_content`` macro for list
|
||||
# content: text segments BPE-encode together up to a media
|
||||
# boundary, then each image emits ``<|vision_start|>`` + N×
|
||||
# ``<|image_pad|>`` + ``<|vision_end|>`` inline.
|
||||
# ``_content_has_media`` returns False unless content is a list,
|
||||
# but the type checker can't follow that through the call.
|
||||
assert isinstance(raw_content, list)
|
||||
buf: list[str] = ["\n"]
|
||||
|
||||
def flush_buf() -> None:
|
||||
if buf:
|
||||
emit_text("".join(buf), msg_idx)
|
||||
buf.clear()
|
||||
|
||||
for item in raw_content:
|
||||
if isinstance(item, str):
|
||||
buf.append(item)
|
||||
elif isinstance(item, dict):
|
||||
if _is_image_part(item):
|
||||
flush_buf()
|
||||
emit_image(item, msg_idx)
|
||||
elif _is_video_part(item):
|
||||
raise NotImplementedError(
|
||||
"Video parts are not yet supported by Qwen35Renderer."
|
||||
)
|
||||
elif "text" in item:
|
||||
buf.append(item["text"])
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
else:
|
||||
raise ValueError(f"Unexpected content item: {item}")
|
||||
flush_buf()
|
||||
emit_text("\n", msg_idx)
|
||||
else:
|
||||
content = self._render_content(raw_content).strip()
|
||||
emit_text("\n" + content + "\n", msg_idx)
|
||||
|
||||
emit_special(self._tool_response_end, msg_idx)
|
||||
|
||||
if not next_is_tool:
|
||||
|
||||
@@ -506,7 +506,12 @@ class Qwen3VLRenderer:
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
).token_ids
|
||||
|
||||
def parse_response(self, token_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self,
|
||||
token_ids: list[int],
|
||||
*,
|
||||
tools: list[ToolSpec] | None = None, # noqa: ARG002 — hermes wire format quotes strings, schema not needed
|
||||
) -> ParsedResponse:
|
||||
return parse_qwen3(
|
||||
self._tokenizer,
|
||||
token_ids,
|
||||
|
||||
@@ -32,6 +32,7 @@ RENDERER_MODELS = [
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
|
||||
]
|
||||
|
||||
+80
-29
@@ -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
|
||||
|
||||
|
||||
@@ -24,18 +29,22 @@ class _FakeRenderer:
|
||||
def get_stop_token_ids(self):
|
||||
return [99]
|
||||
|
||||
def parse_response(self, completion_ids: list[int]) -> ParsedResponse:
|
||||
def parse_response(
|
||||
self, completion_ids: list[int], *, tools=None
|
||||
) -> ParsedResponse:
|
||||
assert completion_ids == [7, 8]
|
||||
# Stores tools so tests can assert the client plumbed them through.
|
||||
self._last_parse_tools = tools
|
||||
return ParsedResponse(
|
||||
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,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
@@ -80,11 +89,12 @@ class _FakeClient:
|
||||
|
||||
def test_generate_builds_request_body_and_parses_response():
|
||||
client = _FakeClient()
|
||||
renderer = _FakeRenderer()
|
||||
|
||||
result = asyncio.run(
|
||||
generate(
|
||||
client=client,
|
||||
renderer=_FakeRenderer(),
|
||||
renderer=renderer,
|
||||
messages=[{"role": "user", "content": "hi"}],
|
||||
model="test-model",
|
||||
tools=[{"type": "function", "function": {"name": "echo"}}],
|
||||
@@ -93,6 +103,12 @@ def test_generate_builds_request_body_and_parses_response():
|
||||
)
|
||||
)
|
||||
|
||||
# The client must plumb `tools` through to parse_response so XML-style
|
||||
# parsers can preserve declared-string args verbatim.
|
||||
assert renderer._last_parse_tools == [
|
||||
{"type": "function", "function": {"name": "echo"}}
|
||||
]
|
||||
|
||||
assert len(client.calls) == 1
|
||||
# /inference/v1/generate is mounted at the server root, so we post to
|
||||
# an absolute URL stripped of the OpenAI SDK's automatic /v1 prefix.
|
||||
@@ -111,26 +127,61 @@ 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], *, tools=None
|
||||
) -> 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):
|
||||
|
||||
@@ -299,11 +299,142 @@ def _build_cases(make_part, image):
|
||||
]
|
||||
|
||||
|
||||
def _build_tool_image_cases(make_part, image):
|
||||
"""Tool-message image scenarios. Targets renderers that emit image
|
||||
placeholders inside ``<tool_response>`` blocks. Browser-agent style
|
||||
trajectories produce post-action screenshots as tool responses, so
|
||||
handling images here is load-bearing for that workload."""
|
||||
return [
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "Take a screenshot."},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "c1",
|
||||
"type": "function",
|
||||
"function": {"name": "screenshot", "arguments": {}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": "c1",
|
||||
"content": [
|
||||
{"type": "text", "text": "Screenshot captured."},
|
||||
make_part(image),
|
||||
],
|
||||
},
|
||||
],
|
||||
False,
|
||||
id="tool_response_with_image",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "Screenshot then describe."},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "c1",
|
||||
"type": "function",
|
||||
"function": {"name": "screenshot", "arguments": {}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": "c1",
|
||||
"content": [
|
||||
{"type": "text", "text": "Done:"},
|
||||
make_part(image),
|
||||
],
|
||||
},
|
||||
{"role": "assistant", "content": "A square."},
|
||||
{"role": "user", "content": "Now show me the next page."},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "c2",
|
||||
"type": "function",
|
||||
"function": {"name": "screenshot", "arguments": {}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": "c2",
|
||||
"content": [
|
||||
{"type": "text", "text": "Next page:"},
|
||||
make_part(image),
|
||||
],
|
||||
},
|
||||
],
|
||||
False,
|
||||
id="multi_turn_tool_response_images",
|
||||
),
|
||||
pytest.param(
|
||||
[
|
||||
{"role": "user", "content": "Run a few tools."},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "c1",
|
||||
"type": "function",
|
||||
"function": {"name": "ping", "arguments": {}},
|
||||
},
|
||||
{
|
||||
"id": "c2",
|
||||
"type": "function",
|
||||
"function": {"name": "screenshot", "arguments": {}},
|
||||
},
|
||||
{
|
||||
"id": "c3",
|
||||
"type": "function",
|
||||
"function": {"name": "ping", "arguments": {}},
|
||||
},
|
||||
],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "c1", "content": "pong"},
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": "c2",
|
||||
"content": [
|
||||
{"type": "text", "text": "Screenshot:"},
|
||||
make_part(image),
|
||||
],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "c3", "content": "pong"},
|
||||
],
|
||||
False,
|
||||
id="consecutive_tools_mixed_media",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _supports_tool_message_images(renderer) -> bool:
|
||||
"""True iff this renderer emits image placeholders inside tool-response
|
||||
content. Renderers without the feature silently drop image parts in tool
|
||||
content; as they grow the feature they get added here and the test starts
|
||||
asserting against them."""
|
||||
from renderers.kimi_k25 import KimiK25Renderer
|
||||
from renderers.qwen35 import Qwen35Renderer
|
||||
|
||||
return isinstance(renderer, (Qwen35Renderer, KimiK25Renderer))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mm_model_name,modality", _CASES, ids=[f"{m}|{mo}" for m, mo in _CASES]
|
||||
)
|
||||
@@ -513,6 +644,44 @@ def test_modality_registry_models_route_to_renderer():
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mm_model_name,modality", _CASES, ids=[f"{m}|{mo}" for m, mo in _CASES]
|
||||
)
|
||||
def test_tool_response_image_byte_parity(mm_model_name, modality, tiny_image):
|
||||
"""Tool-message image parity vs ``processor.apply_chat_template`` + ``processor(...)``.
|
||||
|
||||
Browser-agent SFT traces carry post-action screenshots as ``tool``
|
||||
responses. Renderers that drop those image parts silently — historically
|
||||
every Qwen-VL family renderer did — produce token streams that diverge
|
||||
from the HF processor and lose most of the visual learning signal.
|
||||
Skipped for renderers that haven't grown the feature yet; flips to a
|
||||
real assertion as they do.
|
||||
"""
|
||||
if modality != "image":
|
||||
pytest.skip("Tool-response media path is image-only for now.")
|
||||
if not _hf_snapshot_cached(mm_model_name):
|
||||
pytest.skip(f"{mm_model_name}: HF snapshot not cached locally")
|
||||
|
||||
kit = _modality_kit(modality, mm_model_name)
|
||||
tokenizer, processor, renderer = _load_processor_and_renderer(mm_model_name)
|
||||
|
||||
if not _supports_tool_message_images(renderer):
|
||||
pytest.skip(
|
||||
f"{type(renderer).__name__} does not yet emit images inside tool responses"
|
||||
)
|
||||
|
||||
for case in _build_tool_image_cases(kit["make_part"], tiny_image):
|
||||
messages, add_gp = case.values
|
||||
ours = renderer.render_ids(messages, add_generation_prompt=add_gp)
|
||||
theirs = kit["processor_input_ids"](processor, messages, add_gp)
|
||||
assert ours == theirs, (
|
||||
f"{mm_model_name} / tool / case={case.id}: "
|
||||
f"renderer diverges from processor.\n"
|
||||
f" len(ours)={len(ours)} len(theirs)={len(theirs)}\n"
|
||||
f" ours[:60]={ours[:60]}\n theirs[:60]={theirs[:60]}"
|
||||
)
|
||||
|
||||
|
||||
def test_qwen3_vl_renderer_exposes_image_modality():
|
||||
"""The flagship multimodal renderer is concretely Qwen3VLRenderer.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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 == []
|
||||
|
||||
@@ -42,6 +42,7 @@ NO_OP_MODELS = {
|
||||
"Qwen/Qwen3-VL-4B-Instruct",
|
||||
"Qwen/Qwen3-VL-8B-Instruct",
|
||||
"Qwen/Qwen3-VL-30B-A3B-Instruct",
|
||||
"poolside/Laguna-XS.2",
|
||||
}
|
||||
|
||||
|
||||
|
||||
+10
-15
@@ -43,6 +43,7 @@ _ROUNDTRIP_MODELS = [
|
||||
("moonshotai/Kimi-K2.6", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
|
||||
("poolside/Laguna-XS.2", "auto"),
|
||||
("openai/gpt-oss-20b", "gpt-oss"),
|
||||
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
|
||||
]
|
||||
@@ -158,8 +159,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 +195,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 +234,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 ─────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Tool-arg string-type preservation across renderers.
|
||||
|
||||
XML-style chat templates (Qwen3.5, GLM, MiniMax, Laguna) render tool-call
|
||||
argument values verbatim inside ``<arg_value>X</arg_value>`` tags with
|
||||
no quoting, so a value of ``true`` could be either a bool or the string
|
||||
``"true"``. Without the tool schema, the parser has no signal to choose
|
||||
between them and defaults to ``json.loads`` — which silently corrupts
|
||||
string args that look like JSON.
|
||||
|
||||
This test passes the tool schema to ``parse_response`` so the parser can
|
||||
preserve declared-string params verbatim, matching vLLM / SGLang's
|
||||
reference parsers (e.g. ``vllm/glm45_tool_parser.py``). The hermes-JSON
|
||||
(Qwen3) and section-JSON (Kimi K2) parsers sidestep the bug because
|
||||
their wire format quotes strings; both serve as controls.
|
||||
|
||||
Originally raised by Robin (Poolside) on PR #21.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# (HuggingFace model name, renderer name). Two JSON-shaped controls
|
||||
# (string types already preserved by the wire format) + four XML-style
|
||||
# parsers that rely on the schema to preserve them.
|
||||
_MODELS = [
|
||||
("Qwen/Qwen3-8B", "auto"), # hermes JSON — control
|
||||
("moonshotai/Kimi-K2-Instruct", "auto"), # section JSON — control
|
||||
("Qwen/Qwen3.5-9B", "auto"), # XML
|
||||
("zai-org/GLM-5", "auto"), # XML
|
||||
("MiniMaxAI/MiniMax-M2.5", "auto"), # XML
|
||||
("poolside/Laguna-XS.2", "auto"), # XML
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def _load(model: str, renderer_name: str):
|
||||
from renderers import create_renderer
|
||||
from renderers.base import load_tokenizer
|
||||
|
||||
tok = load_tokenizer(model)
|
||||
return tok, create_renderer(tok, renderer=renderer_name)
|
||||
|
||||
|
||||
def pytest_generate_tests(metafunc):
|
||||
if "model" in metafunc.fixturenames:
|
||||
metafunc.parametrize(
|
||||
"model,renderer_name",
|
||||
_MODELS,
|
||||
ids=[m for m, _ in _MODELS],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def renderer(model, renderer_name):
|
||||
return _load(model, renderer_name)[1]
|
||||
|
||||
|
||||
PROMPT = [
|
||||
{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "Call f."},
|
||||
]
|
||||
|
||||
|
||||
# Each case: a single ``x`` argument whose value is a STRING that
|
||||
# happens to be valid JSON of another type. With a schema declaring
|
||||
# ``x: string``, the parser must return the string verbatim.
|
||||
JSON_LOOKING_STRING_ARGS = [
|
||||
pytest.param({"x": "true"}, id="string-bool"),
|
||||
pytest.param({"x": "42"}, id="string-int"),
|
||||
pytest.param({"x": "null"}, id="string-null"),
|
||||
pytest.param({"x": "[1,2,3]"}, id="string-array"),
|
||||
pytest.param({"x": '{"k": 1}'}, id="string-object"),
|
||||
]
|
||||
|
||||
|
||||
# Tool schema with the single string-typed parameter exercised by every
|
||||
# case above. Passed to both ``render`` (so the system prompt declares
|
||||
# the tool) and ``parse_response`` (so the parser preserves the type).
|
||||
TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "f",
|
||||
"description": "Test tool with one string parameter.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"x": {"type": "string"}},
|
||||
"required": ["x"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def _normalize_args(args: Any) -> Any:
|
||||
"""Mirror ``test_roundtrip._normalize_args`` — some parsers return a
|
||||
JSON string, others a dict; compare by value."""
|
||||
if isinstance(args, str):
|
||||
try:
|
||||
return json.loads(args)
|
||||
except json.JSONDecodeError:
|
||||
return args
|
||||
return args
|
||||
|
||||
|
||||
def _extract_assistant_tokens(renderer, prompt, assistant_msg, *, tools=None):
|
||||
prompt_ids = renderer.render_ids(prompt, tools=tools, add_generation_prompt=False)
|
||||
full_ids = renderer.render_ids(prompt + [assistant_msg], tools=tools)
|
||||
return full_ids[len(prompt_ids) :]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args", JSON_LOOKING_STRING_ARGS)
|
||||
def test_string_arg_preserves_type(model, renderer_name, renderer, args):
|
||||
"""Tool-call args of declared type ``str`` must round-trip as ``str``,
|
||||
not get re-parsed as bool/int/null/list/dict by the parser."""
|
||||
msg = {
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "functions.f:0",
|
||||
"function": {"name": "f", "arguments": args},
|
||||
}
|
||||
],
|
||||
}
|
||||
completion_ids = _extract_assistant_tokens(renderer, PROMPT, msg, tools=TOOLS)
|
||||
parsed = renderer.parse_response(completion_ids, tools=TOOLS)
|
||||
|
||||
assert parsed.tool_calls, f"{model}: parser returned no tool_calls"
|
||||
got = _normalize_args(parsed.tool_calls[0].arguments)
|
||||
assert got == args, (
|
||||
f"{model}: tool-arg type drift — sent {args!r}, parser returned {got!r}"
|
||||
)
|
||||
Reference in New Issue
Block a user