add renderers

This commit is contained in:
hallerite
2026-05-04 22:29:52 +00:00
commit 3e5c2660f0
33 changed files with 11135 additions and 0 deletions
+214
View File
@@ -0,0 +1,214 @@
# renderers
A per-model, Python-native chat-template layer that moves prompt assembly, tool-call parsing, and reasoning parsing out of vLLM and into our own code. Lives in `packages/renderers/` in the verifiers repo; consumed by `verifiers.clients.renderer_client`.
> **Status: experimental.** Available alongside the production `openai_chat_completions_token` (TITO) client. Use TITO for tried-and-tested workloads; renderers offer stronger token-preservation guarantees but only ship hand-coded support for a subset of models and corner cases are still being shaken out.
---
## 1. Why renderers?
Previously, most of "what the prompt actually looks like" was delegated to vLLM: its chat-template application, its tool-call parser, its reasoning parser. That is a fruitful source of bugs, but the reason we need something like renderers is more fundamental.
For RL we need **Token-In, Token-Out (TITO)**: the trainer must see the exact token ids the sampler saw, with an exact loss mask. This is essential for keeping train-inference KL mismatch low and keeping the trainer stepping fast — rollouts whose per-turn prefixes drift under re-tokenization cannot be stitched into a single training sample and fragment into many partial ones.
Renderers turn vLLM into a dumb TITO inference engine. Every prompt manipulation happens client-side:
- **Chat template application** — we render `messages → token ids` ourselves, either with a hand-coded Python renderer that mirrors the Jinja template or with `DefaultRenderer`, which wraps `tokenizer.apply_chat_template` but still owns the tokenization boundary.
- **Tool-call parsing** — `ToolParser` implementations scan token ids for the model's special delimiter tokens (e.g. token id `151657` for `<tool_call>` on Qwen3). A regex-on-decoded-text parser can mistake a literal `"<tool_call>"` inside user content for a real tool-call opener; matching by id can't, because regular text never tokenizes to the special-token id.
- **Reasoning parsing** — `ReasoningParser` implementations split `<think>…</think>` with a tested whitespace-preservation contract (bit-exact newline handling around the closing tag — a spot where we had a real bug that silently broke the extension property at the think boundary).
### What we gain
- **RL correctness.** A prompt/completion split we control, which is exactly what `bridge_to_next_turn` relies on to keep rollouts from fragmenting under truncation or re-tokenization.
- **Testable parity.** Per-model renderers are plain Python. We can render the same conversation through the renderer and through HF's `apply_chat_template` and assert token-level parity. Every edge case (empty thinking, multiple tool calls, truncated turns) becomes a unit test instead of undefined behavior buried inside Jinja.
- **Escape hatch.** Anything without a hand-coded renderer falls back to `DefaultRenderer` (a generic `apply_chat_template` wrapper), which mirrors the previous TITO path.
---
## 2. API
### Renderer protocol
Every renderer implements this (`renderers.base.Renderer`):
```python
render(messages, *, tools=None, add_generation_prompt=False) -> RenderedTokens
render_ids(messages, *, tools=None, add_generation_prompt=False) -> list[int]
parse_response(token_ids) -> ParsedResponse
get_stop_token_ids() -> list[int]
bridge_to_next_turn(prev_prompt_ids, prev_completion_ids, new_messages, *, tools=None) -> list[int] | None
```
`RenderedTokens` carries `token_ids` **and** `message_indices` — one entry per token attributing each token to its source message, so the loss mask can be built from message roles. This lets `build_supervised_sample` assemble samples in O(1) renders instead of O(n).
`ParsedResponse` is `(content, reasoning_content, tool_calls)`.
Round-trip invariant: rendering `[user, assistant(content=X, reasoning=Y, tool_calls=[T])]` to token ids, slicing out the assistant completion, and feeding it through `parse_response` returns an equivalent structured assistant message (modulo field formatting). Tested per-renderer in `tests/test_roundtrip.py`.
### Picking a renderer
```python
from transformers import AutoTokenizer
from renderers import create_renderer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")
r = create_renderer(tok, renderer="auto") # → Qwen3Renderer
```
`renderer="auto"` matches `tokenizer.name_or_path` against `MODEL_RENDERER_MAP` by **exact match**. Prefix matching is intentionally off: two models with the same architecture can ship different chat templates (base vs instruct, fine-tune renames), and prefix routing would silently pick a renderer that doesn't produce template-parity output. Fine-tunes must pass `renderer=<name>` explicitly; unknown names fall back to `DefaultRenderer`.
Available hand-coded renderers: `qwen3`, `qwen3_vl`, `qwen3.5`, `glm5`, `glm4.5`, `minimax-m2`, `deepseek_v3`, `kimi_k2`, `kimi_k25`, `nemotron3`, `gpt_oss`, `default`.
### Pools
For multi-threaded pre-tokenization, use `RendererPool`:
```python
from renderers import create_renderer_pool
pool = create_renderer_pool("Qwen/Qwen3-8B", renderer="auto", size=16)
with pool.checkout() as r:
ids = r.render_ids(messages)
```
Each slot owns its own tokenizer copy. Construction fans out across a thread pool.
---
## 3. The bridge (the core contract)
After rollout step *N* the agent has produced `prompt_ids_N` and `completion_ids_N`. Call their concatenation *stream_N* — the exact bytes vLLM saw at sampling time plus what it emitted. For step *N+1* we require: **`prompt_ids_{N+1}` starts with *stream_N* token-for-token**, then continues with new tokens for the incoming tool result / user message / generation-prompt opener. This is the **extension property**.
```
stream_N = [t0, t1, t2, …, tK] # prompt_N + completion_N, length K+1
prompt_ids_N+1 = [t0, t1, t2, …, tK, tK+1, tK+2, …] # identical prefix, then new turn bytes
```
The next turn's prompt must **extend** the previous turn's tokens; it must never re-tokenize them.
If it holds, `interleave_rollout` merges the two steps into one training sample with one clean `completion_mask`. If it doesn't, the rollout fragments into multiple samples and `samples_per_rollout` drifts above 1.0 — significantly slowing the trainer without adding signal.
The bridge is what produces the tokens needed to uphold the extension property in accordance with the chat template the model was trained on.
### Per-renderer bridges
Each hand-coded renderer implements `bridge_to_next_turn` directly for its model's chat template — no shared generic helper, just Python that knows what tokens the template would insert between turns. Qwen3's bridge knows about `<|im_start|>role\n … <|im_end|>\n`; GLM's bridge knows that turns end when the next role marker appears; DeepSeek V3, Kimi K2/K2.5, Nemotron-3, GPT-OSS, MiniMax each have their own. On a clean stop, vLLM's `completion_ids` already includes the template's close token; on truncation, the renderer synthesizes the canonical close (`<|im_end|>`, `<|endoftext|>`, or the equivalent for that model) so the extension invariant still holds, and the synthetic close is masked out of the loss because the model didn't produce it.
`DefaultRenderer.bridge_to_next_turn` returns `None` by default (forcing a full `apply_chat_template` re-render, which is where modes a–e in §4 strike). Hand-coded bridges are what actually close the gap.
### Turn truncation
When a turn hits `max_tokens`, its `completion_ids` have no end-of-turn marker. A hand-coded renderer's bridge appends the template's canonical turn-close (`<|im_end|>`, `<|endoftext|>`, or equivalent) to the truncated completion and emits new messages on top. The synthetic close lands in `prompt_ids` of the merged sample with `prompt_mask=False`, so loss and KL never see it, and the extension invariant still holds.
---
## 4. Breaking behaviors you might not expect
Everything in this section has been observed in production RL runs on Qwen3, Qwen3.5, GLM-4.5, and opencode-scaffolded environments. Each is a concrete reason why the "render full history through `apply_chat_template` every turn" pattern breaks the extension property. Hand-coded renderers sidestep all of them because `bridge_to_next_turn` never re-renders prior turns.
### a. Boolean type round-trip
vLLM emits a literal `false` inside a parameter block; the client parses `<parameter=dry_run>false</parameter>` into a Python `bool(False)`; `apply_chat_template` re-renders via `str(False)` → `"False"`. Capital F. Every rollout with a boolean parameter breaks on re-render.
```
prev stream: '<parameter=dry_run>\nfalse\n</parameter>'
re-rendered: '<parameter=dry_run>\nFalse\n</parameter>'
```
Reproducible on Qwen3.5-35B-A3B + mini-swe-agent-plus: roughly 50% break rate per rollout (32 of 64 rollouts in a single step).
### b. BPE retokenization drift
The BPE tokenizer is context-sensitive. The same substring tokenizes differently depending on neighboring bytes, which can shift by one whitespace or boundary character between the raw completion and the re-rendered history. Example around `jsonp` inside a Python snippet:
```
prev ids: [..., 2164, 79, 50586, ...] # 'json' + 'p' + 'enderer' (3 tokens)
cur ids: [..., 55137, 50586, ...] # 'jsonp' + 'enderer' (2 tokens)
```
Same text, different token ids, different token count — from that point on every subsequent token id is shifted. Same class of bug we hit when `json.dumps` (Python, `{"k": "v"}` with spaces) vs. `JSON.stringify` (JS, `{"k":"v"}` compact) produced different raw arg bytes in an opencode scaffold and cascaded BPE drift through thousands of tokens of Python code.
### c. Tool-call XML structure drift
vLLM emits a no-arg tool call with a stylistic empty `</parameter>`; the Jinja template re-renders the reconstructed dict without it:
```
prev stream: '<function=echo ...>\n</parameter>\n</function>\n</tool_call>'
re-rendered: '<function=echo ...>\n</function>\n</tool_call>'
```
The `</parameter>\n` vanishes on re-render. Extension property broken at the close of every such call.
### d. Thinking stripped from non-latest assistant turns
Some chat templates strip `<think>…</think>` blocks out of prior assistant turns when re-rendering history. The rollout's recorded stream has the thinking content; the next turn's re-rendered prompt does not. Applies across the Qwen3-series under certain message shapes.
### e. Max-seq-len truncation zeroing the anchor
This one is client-side. When `parse_response_tokens` enforces the trainer's `max_seq_len`, it zeros out `completion_ids` whenever `prompt_len > max_seq_len`. On the next turn, the bridge's anchor (`prev_prompt_ids + prev_completion_ids`) is empty, so the bridge returns `None` and the caller falls back to full re-render — triggering modes a–d for every rollout that truncated. `_step_token_ids` now prefers populated `step.tokens` and falls back to the raw, un-truncated `step.response.message.tokens` specifically to defend against this.
### f. Scaffold-level history rewriting
Some agent scaffolds (e.g. opencode's AI-SDK `experimental_repairToolCall` hook) rewrite tool calls on the client before sending them back as history. If the model emits `Bash` (capital B), the hook rewrites it to a synthetic `{name: "invalid", input: {tool: "Bash", error: "Model tried to call unavailable tool Bash"}}`. The next turn's prompt now contains a tool call that the model never actually emitted — an unfixable extension break as long as the scaffold is in the loop. Renderers' bridge cannot help here because the drift is not in rendering; it's in the history the scaffold handed us.
### How renderers avoids the client-side ones
`bridge_to_next_turn(prev_prompt_ids, prev_completion_ids, new_messages, ...)` constructs the next-turn prompt as `prev_prompt_ids + prev_completion_ids + render_only_new_messages(...)`. It never re-parses prior tool call arguments, never re-tokenizes prior turns, never re-serializes prior tool-call XML. Modes a–e disappear by construction. Mode f is structural and outside the renderer's reach.
On Qwen3.5-35B-A3B + mini-swe-agent-plus step 0, the delta with renderers-v2 vs. `apply_chat_template`-based TITO:
| client path | breaks per step 0 | samples from 64 rollouts |
|--------------------------------------------|-------------------|---------------------------|
| `apply_chat_template` (full re-render) | 32 | 77 |
| renderers `bridge_to_next_turn` | 0 | 64 |
---
## 5. `DefaultRenderer`
Fallback for anything without a hand-coded renderer. Wraps `apply_chat_template` and accepts optional `tool_parser` / `reasoning_parser` kwargs (mirroring vLLM's convention) — it does its best to keep the Renderer contract even without model-specific knowledge.
That said, **prefer a hand-coded renderer** for any model you actually train on. Hand-coded renderers are the only path that closes all the extension-property gaps in §4 by construction. `DefaultRenderer` is there so an unknown model doesn't block you from running — not as the recommended steady state. If your model doesn't have one yet, implementing a renderer for it is a few hundred lines of Python (`render_ids` + `parse_response` + `bridge_to_next_turn`).
---
## 6. VLM support
Renderers are text-only — `ContentPart` admits `TextPart` and `ThinkingPart`, no image or video parts. `Qwen3VLRenderer` is shipped only because the Qwen3-VL tokenizer's text-only chat template differs from Qwen3's; passing image content to any renderer raises. For multimodal training, route the model to MITO (server-side templating) instead.
---
## 7. Patched vs. "correct" chat templates
Many chat templates are poorly suited to RL — they re-tokenize history on every turn, or normalize boolean/JSON values, or auto-strip thinking content from past turns, each of which breaks the extension property.
There is a balance to strike between exact parity with the shipped template — which some downstream consumers expect — and giving users faster, more correct training.
Roadmap: add a `use_patched` flag on renderers whose shipped template is sub-optimal for RL. The patched variant would render the same surface form but avoid the known extension-breaking patterns.
### Training-inference parity in production
Downstream customers typically host the trained model on vLLM. Training with renderers (client-side TITO) and then serving through vLLM's default `/v1/chat/completions` path is a source of subtle drift.
Approach: train with renderers (Renderer client), but run evals during training through the normal `/v1/chat/completions` endpoint — that is the most prod-like setting and surfaces any train-to-serve mismatch before it ships.
---
## 8. Validation surface
Environments used to validate renderer parity and break behavior end-to-end:
- Reverse-Text — single-turn, no tools
- Wordle — multi-turn, deterministic feedback
- OpenCode-Math — multi-turn tool-calling scaffold with invalid-tool rewrites
- RLM-SWE — multi-turn SWE tool-calling against remote sandbox
Renderer-by-renderer: round-trip parity tests (`render` → `parse_response` returns the original messages) and token-level parity against `apply_chat_template` live in `packages/renderers/tests/`.
---
## 9. Resources
- **verifiers PR** — Renderers package + replace TITO client with Renderer client: [PrimeIntellect-ai/verifiers#1068](https://github.com/PrimeIntellect-ai/verifiers/pull/1068)
- **prime-rl PR** — switch RL trainer to renderers: [PrimeIntellect-ai/prime-rl#2278](https://github.com/PrimeIntellect-ai/prime-rl/pull/2278)
+33
View File
@@ -0,0 +1,33 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "renderers"
version = "0.1.5"
description = "Chat template renderers — deterministic message-to-token conversion for LLM training"
readme = "README.md"
requires-python = ">=3.10,<3.14"
dependencies = [
"numpy",
"openai>=1.108.1",
"tiktoken",
"jinja2",
"transformers>=4.50.0",
# Used by GptOssRenderer to render and parse harmony tokens. Vendoring
# OpenAI's reference implementation keeps us byte-identical with vLLM
# (which also uses it) and saves us mirroring a 330-line Jinja template.
"openai-harmony>=0.0.8",
]
[tool.hatch.build.targets.wheel]
packages = ["renderers"]
[dependency-groups]
dev = [
"pytest>=7.0.0",
"pytest-asyncio>=0.21.0",
]
[tool.uv]
exclude-newer = "7 days"
+69
View File
@@ -0,0 +1,69 @@
from renderers.base import (
Content,
ContentPart,
Message,
ParsedResponse,
RenderedConversation,
RenderedTokens,
Renderer,
RendererPool,
TextPart,
ThinkingPart,
ToolCall,
ToolCallFunction,
ToolSpec,
build_training_sample,
build_trajectory_step,
create_renderer,
create_renderer_pool,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.deepseek_v3 import DeepSeekV3Renderer
from renderers.default import DefaultRenderer
from renderers.glm5 import GLM5Renderer
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.minimax_m2 import MiniMaxM2Renderer
from renderers.nemotron3 import Nemotron3Renderer
from renderers.qwen3 import Qwen3Renderer
from renderers.qwen3_vl import Qwen3VLRenderer
from renderers.qwen35 import Qwen35Renderer
from renderers.qwen36 import Qwen36Renderer
__all__ = [
"Content",
"ContentPart",
"DeepSeekV3Renderer",
"DefaultRenderer",
"GLM45Renderer",
"GLM5Renderer",
"GptOssRenderer",
"KimiK2Renderer",
"KimiK25Renderer",
"Message",
"MiniMaxM2Renderer",
"Nemotron3Renderer",
"ParsedResponse",
"Qwen3Renderer",
"Qwen3VLRenderer",
"Qwen35Renderer",
"Qwen36Renderer",
"RenderedConversation",
"RenderedTokens",
"Renderer",
"RendererPool",
"TextPart",
"ThinkingPart",
"ToolCall",
"ToolCallFunction",
"ToolSpec",
"build_training_sample",
"build_trajectory_step",
"create_renderer",
"create_renderer_pool",
"reject_assistant_in_extension",
"trim_to_turn_close",
]
+537
View File
@@ -0,0 +1,537 @@
from __future__ import annotations
import logging
import queue
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Callable, Literal, Protocol, TypedDict, runtime_checkable
logger = logging.getLogger("renderers.base")
# ---------------------------------------------------------------------------
# Message types — strong typing for the conversation data model
# ---------------------------------------------------------------------------
class TextPart(TypedDict):
"""A chunk of text content in a message."""
type: Literal["text"]
text: str
class ThinkingPart(TypedDict):
"""Model's internal reasoning (chain-of-thought) as a content part."""
type: Literal["thinking"]
thinking: str
ContentPart = TextPart | ThinkingPart
# Content is either a plain string or a list of structured parts.
Content = str | list[ContentPart]
class ToolCallFunction(TypedDict):
"""Function body within a tool call."""
name: str
arguments: dict[str, Any] | str
class ToolCall(TypedDict, total=False):
"""Structured tool invocation following OpenAI function-calling format."""
type: str # "function"
id: str
function: ToolCallFunction
class ToolSpec(TypedDict):
"""Tool specification (OpenAI function-calling format)."""
name: str
description: str
parameters: dict[str, Any]
class Message(TypedDict, total=False):
"""A single turn in a multi-turn conversation.
Required keys: role, content.
Optional keys mirror the OpenAI chat format for tool calling.
"""
role: str
content: Content
tool_calls: list[ToolCall]
tool_call_id: str
name: str
reasoning_content: str
# ---------------------------------------------------------------------------
# Renderer data types
# ---------------------------------------------------------------------------
@dataclass
class RenderedTokens:
"""Result of rendering messages to tokens.
Each token carries an index into the original message list so callers can
build per-token loss masks without re-rendering. Tokens from structural
scaffolding (generation prompt, im_start/im_end wrapping) carry index -1.
"""
token_ids: list[int] = field(default_factory=list)
message_indices: list[int] = field(default_factory=list)
@dataclass
class ParsedResponse:
"""Result of parsing completion tokens back into a structured message."""
content: str
reasoning_content: str | None = None
tool_calls: list[dict[str, Any]] | None = None
@dataclass
class RenderedConversation:
"""Exact token state for a rendered conversation."""
prompt_ids: list[int]
completion_ids: list[int] = field(default_factory=list)
completion_logprobs: list[float] = field(default_factory=list)
messages: list[Message] = field(default_factory=list)
parsed_completion: ParsedResponse | None = None
@property
def token_ids(self) -> list[int]:
return self.prompt_ids + self.completion_ids
def with_completion(
self,
completion_ids: list[int],
*,
completion_logprobs: list[float] | None = None,
parsed_completion: ParsedResponse | None = None,
) -> "RenderedConversation":
return RenderedConversation(
prompt_ids=list(self.prompt_ids),
completion_ids=list(completion_ids),
completion_logprobs=list(completion_logprobs or []),
messages=list(self.messages),
parsed_completion=parsed_completion,
)
@runtime_checkable
class Renderer(Protocol):
"""Owns message ↔ token conversion for a specific model family."""
def render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> RenderedTokens:
"""Render messages to token IDs with per-token message attribution."""
...
def render_ids(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> list[int]:
"""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 get_stop_token_ids(self) -> list[int]:
"""Return token IDs that signal generation should stop."""
...
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,
) -> list[int] | None:
"""Extend ``prev_prompt_ids + prev_completion_ids`` with the tokens
the next turn adds, without re-rendering the sampled tokens.
Contract: if the return value ``B`` is not None, then
``B[: len(prev_prompt) + len(prev_completion)] == prev_prompt + prev_completion``
and ``B`` ends at the position where the next assistant turn begins
generating (i.e. equivalent to rendering the full message list so far
with ``add_generation_prompt=True`` — except prev sampled tokens are
kept verbatim rather than re-rendered).
Return ``None`` whenever the renderer can't prove that contract
holds — the caller falls back to a full re-render. In particular,
bridges refuse assistant messages in ``new_messages`` (those would
re-tokenize model-sampled content). Hand-coded renderers know their
canonical close and synthesise it on truncated priors;
DefaultRenderer always returns ``None`` because the template's
close is unknown.
"""
...
class RendererPool:
"""Thread-safe pool of Renderer instances for parallel pretokenization.
Each Renderer wraps its own tokenizer copy, avoiding contention.
Construction parallelism matters: ``AutoTokenizer.from_pretrained`` takes
hundreds of ms per call (JSON parse + Rust tokenizer build + HF cache
lookup), so populating a 32-slot pool serially costs ~10-15s on startup
and shows up directly as a step-0 stall. We fan the factory out across a
short-lived thread pool; since HF fast tokenizers release the GIL during
the Rust build phase, this parallelizes well.
"""
def __init__(self, factory: Callable[[], Renderer], size: int):
from concurrent.futures import ThreadPoolExecutor
self._factory = factory
self._pool: queue.Queue[Renderer] = queue.Queue(maxsize=size)
# Cap workers so we don't spawn an oversized thread pool just to init
# a small pool; clamp to 8 because past that the GIL-bound Python
# portion of from_pretrained stops scaling.
workers = min(size, 8)
with ThreadPoolExecutor(max_workers=workers) as executor:
for renderer in executor.map(lambda _: factory(), range(size)):
self._pool.put(renderer)
@contextmanager
def checkout(self):
renderer = self._pool.get()
try:
yield renderer
finally:
self._pool.put(renderer)
@property
def size(self) -> int:
return self._pool.maxsize
RENDERER_REGISTRY: dict[str, type] = {}
# Exact canonical HF model names → renderer. We do NOT use prefix
# matching because models with the same architecture may ship different
# chat templates (base vs instruct, tuned vs pretrained) — matching on
# prefix silently routes them to a renderer that doesn't produce
# template-parity output. Fine-tunes and renamed checkpoints MUST pass
# ``renderer=<name>`` explicitly; the auto path falls back to
# ``DefaultRenderer`` (which uses ``apply_chat_template`` verbatim) and
# logs a loud INFO line with the chosen fallback.
MODEL_RENDERER_MAP: dict[str, str] = {
# Qwen3 — base and Instruct variants share the same chat template.
"Qwen/Qwen3-0.6B": "qwen3",
"Qwen/Qwen3-1.7B": "qwen3",
"Qwen/Qwen3-4B": "qwen3",
"Qwen/Qwen3-4B-Instruct-2507": "qwen3",
"Qwen/Qwen3-4B-Thinking-2507": "qwen3",
"Qwen/Qwen3-8B": "qwen3",
"Qwen/Qwen3-14B": "qwen3",
"Qwen/Qwen3-32B": "qwen3",
"Qwen/Qwen3-30B-A3B": "qwen3",
"Qwen/Qwen3-235B-A22B": "qwen3",
# Qwen3.5.
"Qwen/Qwen3.5-9B": "qwen3.5",
"Qwen/Qwen3.5-35B-A3B": "qwen3.5",
"Qwen/Qwen3.5-122B-A10B": "qwen3.5",
# Qwen3.6.
"Qwen/Qwen3.6-35B-A3B": "qwen3.6",
# Qwen3-VL.
"Qwen/Qwen3-VL-4B-Instruct": "qwen3_vl",
"Qwen/Qwen3-VL-8B-Instruct": "qwen3_vl",
"Qwen/Qwen3-VL-30B-A3B-Instruct": "qwen3_vl",
# GLM-5 family (GLM-4.7 reuses the GLM-5 template).
"zai-org/GLM-5": "glm5",
"zai-org/GLM-4.7-Flash": "glm5",
"zai-org/GLM-5.1": "glm5.1",
# GLM-4.5.
"THUDM/GLM-4.5-Air": "glm4.5",
"zai-org/GLM-4.5-Air": "glm4.5",
# MiniMax.
"MiniMaxAI/MiniMax-M2": "minimax-m2",
"MiniMaxAI/MiniMax-M2.5": "minimax-m2",
# DeepSeek V3.
"deepseek-ai/DeepSeek-V3": "deepseek_v3",
"deepseek-ai/DeepSeek-V3-Base": "deepseek_v3",
# Kimi K2 (K2.5 and K2.6 share the K2.5 template, distinct from K2).
"moonshotai/Kimi-K2-Instruct": "kimi_k2",
"moonshotai/Kimi-K2.5": "kimi_k25",
"moonshotai/Kimi-K2.6": "kimi_k25",
# Nemotron 3.
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "nemotron3",
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "nemotron3",
# GPT-OSS.
"openai/gpt-oss-20b": "gpt_oss",
"openai/gpt-oss-120b": "gpt_oss",
}
def _populate_registry():
if RENDERER_REGISTRY:
return
from renderers.default import DefaultRenderer
from renderers.deepseek_v3 import DeepSeekV3Renderer
from renderers.glm5 import GLM5Renderer, GLM51Renderer
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.minimax_m2 import MiniMaxM2Renderer
from renderers.nemotron3 import Nemotron3Renderer
from renderers.qwen3 import Qwen3Renderer
from renderers.qwen3_vl import Qwen3VLRenderer
from renderers.qwen35 import Qwen35Renderer
from renderers.qwen36 import Qwen36Renderer
RENDERER_REGISTRY.update(
{
"default": DefaultRenderer,
"qwen3": Qwen3Renderer,
"qwen3_vl": Qwen3VLRenderer,
"qwen3.5": Qwen35Renderer,
"qwen3.6": Qwen36Renderer,
"glm5": GLM5Renderer,
"glm5.1": GLM51Renderer,
"glm4.5": GLM45Renderer,
"minimax-m2": MiniMaxM2Renderer,
"deepseek_v3": DeepSeekV3Renderer,
"kimi_k2": KimiK2Renderer,
"kimi_k25": KimiK25Renderer,
"nemotron3": Nemotron3Renderer,
"gpt_oss": GptOssRenderer,
}
)
def create_renderer_pool(
tokenizer_name_or_path: str,
renderer: str = "auto",
size: int = 16,
*,
tool_parser: str | None = None,
reasoning_parser: str | None = None,
) -> RendererPool:
"""Create a RendererPool with *size* independent tokenizer copies.
Each slot loads its own tokenizer so threads never share mutable state.
HuggingFace fast tokenizers release the GIL during Rust encoding, so
threads achieve real parallelism.
``tool_parser`` and ``reasoning_parser`` are forwarded to
``create_renderer`` when the pool falls back to ``DefaultRenderer``.
"""
def factory() -> Renderer:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
tokenizer_name_or_path, trust_remote_code=True
)
return create_renderer(
tokenizer,
renderer=renderer,
tool_parser=tool_parser,
reasoning_parser=reasoning_parser,
)
return RendererPool(factory, size=size)
def create_renderer(
tokenizer,
renderer: str = "auto",
*,
tool_parser: str | None = None,
reasoning_parser: str | None = None,
) -> Renderer:
"""Create a Renderer by name, or auto-detect from the tokenizer's model name.
Args:
tokenizer: HuggingFace tokenizer instance.
renderer: Renderer name ('qwen3', 'qwen3_vl', 'qwen3.5', 'glm5', 'glm4.5',
'minimax-m2', 'deepseek_v3', 'kimi_k2', 'kimi_k25', 'nemotron3',
'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.
reasoning_parser: Name of a reasoning parser registered in
``renderers.parsers``. Only consumed by DefaultRenderer.
"""
_populate_registry()
default_kwargs: dict = {}
if tool_parser is not None:
default_kwargs["tool_parser"] = tool_parser
if reasoning_parser is not None:
default_kwargs["reasoning_parser"] = reasoning_parser
if renderer != "auto":
cls = RENDERER_REGISTRY.get(renderer)
if cls is None:
raise ValueError(
f"Unknown renderer {renderer!r}. Available: {', '.join(sorted(RENDERER_REGISTRY))}"
)
if renderer == "default":
return cls(tokenizer, **default_kwargs)
if default_kwargs:
logger.info(
"tool_parser / reasoning_parser are only consumed by "
"DefaultRenderer; ignoring for renderer=%r which has "
"built-in behavior.",
renderer,
)
return cls(tokenizer)
# Auto-detect from model name via exact match on the canonical HF id.
# Fine-tunes and renamed checkpoints miss on purpose — their chat
# template may differ from the original even when the architecture
# matches, so silently mapping them would produce template-parity
# bugs. Set ``renderer=<name>`` explicitly for those.
model_name = getattr(tokenizer, "name_or_path", "")
renderer_name = MODEL_RENDERER_MAP.get(model_name)
if renderer_name is not None:
return RENDERER_REGISTRY[renderer_name](tokenizer)
# No match — fall back to default (apply_chat_template). For fine-tunes
# with customized chat templates this is the *correct* choice, so we don't
# warn. Note the pick at INFO and advertise the parser knobs.
logger.info(
"No model-specific renderer matched %r. Using DefaultRenderer "
"(apply_chat_template). Pass tool_parser=<name> or "
"reasoning_parser=<name> to enable structured output parsing.",
model_name or "<unnamed tokenizer>",
)
return RENDERER_REGISTRY["default"](tokenizer, **default_kwargs)
# ---------------------------------------------------------------------------
# Standalone helpers that work with any Renderer implementation
# ---------------------------------------------------------------------------
def build_training_sample(
renderer: Renderer,
messages: list[Message],
*,
role_to_mask: Callable[[Message], bool],
tools: list[ToolSpec] | None = None,
) -> tuple[list[int], list[bool]]:
"""Build (token_ids, loss_mask) for supervised training.
Single render() call + message_indices → per-token mask.
Replaces build_incremental_token_mask (O(N) renders → O(1)).
"""
rendered = renderer.render(messages, tools=tools)
loss_mask: list[bool] = []
for msg_idx in rendered.message_indices:
if msg_idx < 0:
loss_mask.append(False)
else:
loss_mask.append(role_to_mask(messages[msg_idx]))
return rendered.token_ids, loss_mask
def _common_prefix_len(a: list[int], b: list[int]) -> int:
max_len = min(len(a), len(b))
for idx in range(max_len):
if a[idx] != b[idx]:
return idx
return max_len
def trim_to_turn_close(
previous_prompt_ids: list[int],
previous_completion_ids: list[int],
close_token_ids: set[int],
*,
synthesize_close: int | None = None,
) -> list[int] | None:
"""Return the longest prefix of ``prev_prompt + prev_completion`` that
ends at a turn-close token, or ``None`` if none exists and
``synthesize_close`` is not provided.
Scans only within ``prev_completion_ids`` — a close token in
``prev_prompt_ids`` is structural template scaffolding, not a turn
boundary the current step's completion produced.
When ``prev_completion_ids`` has no close token, the prior turn was
truncated at max_tokens. The caller opts in to synthesising the
canonical close by passing ``synthesize_close`` (its token id).
Otherwise the caller falls back to a fresh re-render.
Hand-coded renderers pass this helper a set they know describes their
turn boundaries. DefaultRenderer can't know its template's close, so
it doesn't call this — it returns ``None`` from ``bridge_to_next_turn``
unconditionally.
"""
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
for idx in range(len(previous_ids) - 1, len(previous_prompt_ids) - 1, -1):
if previous_ids[idx] in close_token_ids:
return previous_ids[: idx + 1]
if synthesize_close is None:
return None
previous_ids.append(synthesize_close)
return previous_ids
def reject_assistant_in_extension(new_messages: list[Message]) -> bool:
"""Return True if any message in ``new_messages`` is an assistant turn.
Bridges refuse to re-tokenize assistant content because it would
replace model-sampled tokens with canonical template text — violating
the contract that sampled tokens land in training exactly as emitted.
"""
return any(m.get("role") == "assistant" for m in new_messages)
def build_trajectory_step(
renderer: Renderer,
prompt_messages: list[Message],
completion_messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
) -> dict[str, Any]:
"""Build prompt_ids / completion_ids / masks for a trajectory step.
Uses common_prefix_len to find the split point because generation prompts
may diverge from the full sequence at token boundaries (e.g., ``\\n`` vs
``\\n\\n`` when thinking content is empty in Qwen3.5).
"""
has_completion = len(completion_messages) > 0
prompt_ids = renderer.render_ids(
prompt_messages, tools=tools, add_generation_prompt=has_completion
)
full_ids = renderer.render_ids(prompt_messages + completion_messages, tools=tools)
split_idx = _common_prefix_len(prompt_ids, full_ids)
completion_ids = full_ids[split_idx:]
return {
"prompt_ids": full_ids[:split_idx],
"prompt_mask": [False] * split_idx,
"completion_ids": completion_ids,
"completion_mask": [True] * len(completion_ids),
"completion_logprobs": [0.0] * len(completion_ids),
"routed_experts": None,
}
+238
View File
@@ -0,0 +1,238 @@
"""Renderer-based verifiers client.
All tokenization happens client-side via a Renderer:
messages → Renderer.render_ids() → token IDs → vLLM /v1/generate → completion tokens
completion tokens → Renderer.parse_response() → structured message back to verifiers
When a RendererPool is passed instead of a single Renderer, the sync tokenization
and parsing work is offloaded to threads for parallel execution across rollouts.
HuggingFace fast tokenizers release the GIL during Rust encoding, so threads
achieve real parallelism.
"""
from __future__ import annotations
import asyncio
import base64
import logging
from typing import Any, cast
import numpy as np
from openai import AsyncOpenAI, BadRequestError
from renderers.base import Message, Renderer, RendererPool, ToolSpec
# Logs the (per-message length, total prompt length) on every vLLM /generate
# call at DEBUG, and the same plus the response text on a 4xx at WARNING.
# Lets us post-mortem overlong-prompt rejections without re-running.
_request_logger = logging.getLogger("verifiers.renderer_client.completions_request")
async def _run_pooled(pool: RendererPool, fn):
"""Check out a renderer, run *fn(renderer)* in a thread, return result."""
def _work():
with pool.checkout() as r:
return fn(r)
return await asyncio.to_thread(_work)
async def completions_request(
client: AsyncOpenAI,
renderer: Renderer | RendererPool,
messages: list[Message],
model: str,
tools: list[ToolSpec] | None = None,
prompt_ids: list[int] | None = None,
**sampling_args: Any,
) -> dict[str, Any]:
"""Render messages to tokens, call vLLM /v1/generate, return parsed result.
Returns a dict with: prompt_ids, completion_ids, completion_logprobs,
content, reasoning_content, tool_calls, finish_reason, usage, routed_experts.
"""
if tools and not getattr(renderer, "supports_tools", True):
raise ValueError(
f"{type(renderer).__name__} does not support tools. "
"Choose a model-specific renderer instead of the default fallback."
)
pool = renderer if isinstance(renderer, RendererPool) else None
# -- Prepare: tokenize prompt --
def _prepare(r: Renderer):
prepared_prompt_ids = (
list(prompt_ids)
if prompt_ids is not None
else r.render_ids(messages, tools=tools, add_generation_prompt=True)
)
stop_token_ids = r.get_stop_token_ids()
return prepared_prompt_ids, stop_token_ids
if pool is not None:
prompt_ids, stop_token_ids = await _run_pooled(pool, _prepare)
else:
prompt_ids, stop_token_ids = _prepare(renderer)
# -- Build request body --
body: dict[str, Any] = {
"model": model,
"prompt_token_ids": prompt_ids,
"stop_token_ids": stop_token_ids,
}
# Top-level keys accepted by vLLM /generate's GenerateRequest schema. We
# forward anything the caller set, mirroring the OpenAI chat-completions
# client (which splats ``sampling_args`` into the SDK call). ``cache_salt``
# is set by prime-rl's orchestrator per ckpt_step to invalidate stale
# prefix-cache KV after each policy update — without forwarding it, vLLM
# silently reuses KV computed with older weights → mismatch_kl drifts up
# over training.
_GENERATE_KEYS = (
"temperature",
"top_p",
"top_k",
"min_p",
"seed",
"n",
"repetition_penalty",
"min_tokens",
"prompt_logprobs",
"priority",
"cache_salt",
)
for key in _GENERATE_KEYS:
if key in sampling_args and sampling_args[key] is not None:
body[key] = sampling_args[key]
max_tokens = sampling_args.get("max_completion_tokens") or sampling_args.get(
"max_tokens"
)
if max_tokens is not None:
body["max_tokens"] = max_tokens
# Fallback for callers using the OpenAI-SDK convention of stuffing
# vLLM-specific args under ``extra_body``.
extra_body = sampling_args.get("extra_body") or {}
for key in _GENERATE_KEYS:
if key not in body and key in extra_body and extra_body[key] is not None:
body[key] = extra_body[key]
# Pass through caller-supplied HTTP headers (auth, tracing, etc.) to vLLM.
extra_headers = sampling_args.get("extra_headers") or {}
# -- Send to vLLM --
_request_logger.debug(
"vllm /generate: prompt_len=%d messages=%d max_tokens=%s",
len(prompt_ids),
len(messages),
max_tokens,
)
post_kwargs: dict[str, Any] = {
"cast_to": cast(Any, dict[str, Any]),
"body": body,
}
if extra_headers:
post_kwargs["options"] = cast(Any, {"headers": extra_headers})
try:
data = await client.post("/generate", **post_kwargs)
except BadRequestError as exc:
_log_overlong_prompt_diagnostic(
prompt_ids=prompt_ids,
messages=messages,
max_tokens=max_tokens,
exc=exc,
)
raise
choices = data.get("choices") or [{}]
choice = choices[0]
# -- Parse completion tokens --
completion_ids = choice.get("token_ids") or []
if pool is not None:
parsed = await _run_pooled(pool, lambda r: r.parse_response(completion_ids))
else:
parsed = renderer.parse_response(completion_ids)
completion_logprobs = [
float(lp) if lp is not None else 0.0 for lp in choice.get("logprobs") or []
]
# Extract routed experts
routed_experts = None
raw_re = choice.get("routed_experts")
if isinstance(raw_re, dict) and "data" in raw_re and "shape" in raw_re:
routed_experts = (
np.frombuffer(base64.b85decode(raw_re["data"]), dtype=np.int32)
.reshape(raw_re["shape"])
.tolist()
)
# vLLM's /v1/generate only knows about the raw generate loop, so it
# returns finish_reason in {"stop","length",…} — never "tool_calls",
# which is a chat-completions concept. When we extract tool calls
# client-side from the tokens, promote "stop" → "tool_calls" so
# OpenAI-compatible agent loops (AI SDK, opencode) continue past the
# tool turn instead of treating the response as final output.
finish_reason = choice.get("finish_reason")
if parsed.tool_calls and finish_reason == "stop":
finish_reason = "tool_calls"
return {
"id": data.get("id") or "",
"created": data.get("created") or 0,
"model": data.get("model") or "",
"prompt_ids": list(prompt_ids),
"completion_ids": list(completion_ids),
"completion_logprobs": completion_logprobs,
"content": parsed.content,
"reasoning_content": parsed.reasoning_content,
"tool_calls": parsed.tool_calls,
"finish_reason": finish_reason,
"usage": data.get("usage"),
"routed_experts": routed_experts,
}
def _log_overlong_prompt_diagnostic(
*,
prompt_ids: list[int],
messages: list[Message],
max_tokens: int | None,
exc: BadRequestError,
) -> None:
"""Log a structured snapshot when vLLM rejects with 4xx — usually overlong.
Captures total prompt length, per-message role + character count, and
the first chunk of the response body. Lets us post-mortem WHICH rollout
blew the context window without rerunning.
"""
body_text = ""
response = getattr(exc, "response", None)
if response is not None:
body_text = (response.text or "")[:500].replace("\n", " ")
msg_summary = []
for i, m in enumerate(messages):
role = m.get("role", "?")
content = m.get("content")
if isinstance(content, str):
content_len = len(content)
elif isinstance(content, list):
content_len = sum(
len(p.get("text", "")) if isinstance(p, dict) else 0 for p in content
)
else:
content_len = 0
tool_calls = m.get("tool_calls")
tc_count = len(tool_calls) if tool_calls else 0
msg_summary.append(f"[{i}]{role}(c={content_len},tc={tc_count})")
_request_logger.warning(
"vllm 4xx prompt_len=%d messages=%d max_tokens=%s per_msg=%s response_body=%s",
len(prompt_ids),
len(messages),
max_tokens,
" ".join(msg_summary),
body_text,
)
+401
View File
@@ -0,0 +1,401 @@
"""DeepSeek V3 Renderer — hard-coded Python mirroring the DeepSeek V3 Jinja chat template.
Special tokens use fullwidth Unicode vertical bar (| = U+FF5C) and underscores
rendered as ▁ (U+2581), e.g. <|begin▁of▁sentence|>.
Format:
<|begin▁of▁sentence|>{system}<|User|>{user}<|Assistant|>{assistant}<|end▁of▁sentence|>
Thinking uses plain text tags <think>...</think> (NOT special tokens).
When enable_thinking=True the generation prompt prefills <think>\\n to trigger reasoning.
"""
from __future__ import annotations
import json
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.parsing import parse_deepseek_v3
# Fullwidth vertical bar used in DeepSeek special token names.
_SEP = "\uff5c" # | (U+FF5C)
# Fullwidth underscore substitute used in DeepSeek special token names.
_US = "\u2581" # ▁ (U+2581)
def _ds_token(name: str) -> str:
"""Build a DeepSeek special-token string: <|{name}|>."""
return f"<{_SEP}{name}{_SEP}>"
class DeepSeekV3Renderer:
"""Deterministic message → token renderer for DeepSeek V3 models."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
# ── BOS / EOS ────────────────────────────────────────────────
self._bos = self._get_special_token(f"begin{_US}of{_US}sentence")
self._eos = self._get_special_token(f"end{_US}of{_US}sentence")
# ── Role tokens ───────────────────────────────────────────────
self._user_token = self._get_special_token("User")
self._assistant_token = self._get_special_token("Assistant")
# ── Tool call section tokens ──────────────────────────────────
self._tool_calls_begin = self._get_special_token(f"tool{_US}calls{_US}begin")
self._tool_calls_end = self._get_special_token(f"tool{_US}calls{_US}end")
self._tool_call_begin = self._get_special_token(f"tool{_US}call{_US}begin")
self._tool_call_end = self._get_special_token(f"tool{_US}call{_US}end")
self._tool_sep = self._get_special_token(f"tool{_US}sep")
# ── Tool output section tokens ────────────────────────────────
self._tool_outputs_begin = self._get_special_token(
f"tool{_US}outputs{_US}begin"
)
self._tool_outputs_end = self._get_special_token(f"tool{_US}outputs{_US}end")
self._tool_output_begin = self._get_special_token(f"tool{_US}output{_US}begin")
self._tool_output_end = self._get_special_token(f"tool{_US}output{_US}end")
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
def _get_special_token(self, name: str) -> int:
"""Encode <|{name}|> and assert it maps to exactly one token."""
token_str = _ds_token(name)
ids = self._tokenizer.encode(token_str, add_special_tokens=False)
assert len(ids) == 1, f"Expected single token for {token_str!r}, got {ids}"
return ids[0]
def _encode(self, text: str) -> list[int]:
if not text:
return []
return self._tokenizer.encode(text, add_special_tokens=False)
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
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_ids(ids: list[int], msg_idx: int) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
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:
emit_ids(self._encode(text), msg_idx)
# ── 1. BOS token ─────────────────────────────────────────────
emit_special(self._bos, -1)
# ── 2. Collect system messages at the start ───────────────────
# All leading system messages are concatenated with "\n\n" and emitted
# before the first non-system message (no role token), matching the HF
# chat template behaviour.
sys_parts: list[str] = []
first_non_sys = 0
for msg in messages:
if msg["role"] == "system":
content = msg.get("content") or ""
if isinstance(content, list):
content = "".join(
p.get("text", "") for p in content if isinstance(p, dict)
)
sys_parts.append(str(content))
first_non_sys += 1
else:
break
if sys_parts:
# Attribute the concatenated system text to the first system message (index 0).
emit_text("\n\n".join(sys_parts), 0)
# ── 3. Render non-system messages ─────────────────────────────
num_messages = len(messages)
for i in range(first_non_sys, num_messages):
msg = messages[i]
role = msg["role"]
if role == "system":
# System messages after the initial block — treat as user turns.
content = msg.get("content") or ""
if isinstance(content, list):
content = "".join(
p.get("text", "") for p in content if isinstance(p, dict)
)
emit_special(self._user_token, i)
emit_text(str(content), i)
elif role == "user":
content = msg.get("content") or ""
if isinstance(content, list):
content = "".join(
p.get("text", "")
if isinstance(p, dict) and p.get("type") == "text"
else p.get("text", "")
if isinstance(p, dict)
else ""
for p in content
)
emit_special(self._user_token, i)
emit_text(str(content), i)
elif role == "assistant":
self._render_assistant(
msg,
i,
messages,
emit_special=emit_special,
emit_text=emit_text,
)
elif role == "tool":
self._render_tool(
messages,
i,
emit_special=emit_special,
emit_text=emit_text,
)
# ── 4. Generation prompt ──────────────────────────────────────
if add_generation_prompt:
# Don't add <|Assistant|> after tool outputs — content flows directly.
last_role = messages[-1]["role"] if messages else None
if last_role != "tool":
emit_special(self._assistant_token, -1)
if self._enable_thinking:
emit_text("<think>\n", -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]) -> ParsedResponse:
return parse_deepseek_v3(
self._tokenizer,
token_ids,
stop_ids={self._eos},
tool_calls_begin_id=self._tool_calls_begin,
tool_calls_end_id=self._tool_calls_end,
tool_call_begin_id=self._tool_call_begin,
tool_call_end_id=self._tool_call_end,
tool_sep_id=self._tool_sep,
)
def get_stop_token_ids(self) -> list[int]:
return [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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._eos},
synthesize_close=self._eos,
)
if previous_ids is None:
return None
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 i, msg in enumerate(new_messages):
role = msg.get("role")
content = msg.get("content") or ""
if isinstance(content, list):
content = "".join(
p.get("text", "") for p in content if isinstance(p, dict)
)
content = str(content)
if role == "user":
emit_special(self._user_token, i)
emit_text(content, i)
elif role == "system":
# Post-initial system messages render as user turns.
emit_special(self._user_token, i)
emit_text(content, i)
elif role == "tool":
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
next_is_tool = (
i + 1 < len(new_messages)
and new_messages[i + 1].get("role") == "tool"
)
if not prev_is_tool:
emit_special(self._tool_outputs_begin, i)
emit_special(self._tool_output_begin, i)
emit_text(content, i)
emit_special(self._tool_output_end, i)
if not next_is_tool:
emit_special(self._tool_outputs_end, i)
else:
return None
# Generation prompt — skip ``<|Assistant|>`` when the prior new
# message was a tool response (matches render()'s behaviour: tool
# output flows directly into assistant content).
last_role = new_messages[-1].get("role") if new_messages else None
if last_role != "tool":
emit_special(self._assistant_token, -1)
if self._enable_thinking:
emit_text("<think>\n", -1)
return previous_ids + ext
# ------------------------------------------------------------------
# Assistant rendering
# ------------------------------------------------------------------
def _render_assistant(
self,
msg: Message,
msg_idx: int,
messages: list[Message],
*,
emit_special,
emit_text,
) -> None:
# Determine whether this message follows a tool output sequence.
# The HF template emits <|tool▁outputs▁end|> before the assistant content
# without a new <|Assistant|> token in that case.
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
content = msg.get("content") or ""
# Support structured content (ThinkingPart / TextPart list).
if isinstance(content, list):
parts_text: list[str] = []
for p in content:
if not isinstance(p, dict):
continue
if p.get("type") == "thinking":
thinking = p.get("thinking", "")
parts_text.append(f"<think>{thinking}</think>")
elif p.get("type") == "text":
parts_text.append(p.get("text", ""))
content = "".join(parts_text)
# Also accept reasoning_content stored separately (OpenAI-style).
elif isinstance(msg.get("reasoning_content"), str) and msg["reasoning_content"]:
reasoning = msg["reasoning_content"]
content = f"<think>{reasoning}</think>{content}"
tool_calls = msg.get("tool_calls") or []
if not prev_is_tool:
emit_special(self._assistant_token, msg_idx)
if not tool_calls:
emit_text(content, msg_idx)
else:
# Emit any pre-tool-call content first.
emit_text(content, msg_idx)
# Tool call section.
emit_special(self._tool_calls_begin, msg_idx)
for tc in tool_calls:
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
args_str = (
json.dumps(arguments, ensure_ascii=False)
if not isinstance(arguments, str)
else arguments
)
# Format: <|tool▁call▁begin|>function<|tool▁sep|>{name}\n```json\n{args}\n```<|tool▁call▁end|>
# tool_sep is a special token; type ("function") and name+args are plain text.
emit_special(self._tool_call_begin, msg_idx)
emit_text("function", msg_idx)
emit_special(self._tool_sep, msg_idx)
emit_text(f"{name}\n```json\n{args_str}\n```", msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_calls_end, msg_idx)
emit_special(self._eos, msg_idx)
# ------------------------------------------------------------------
# Tool (tool-response) rendering
# ------------------------------------------------------------------
def _render_tool(
self,
messages: list[Message],
msg_idx: int,
*,
emit_special,
emit_text,
) -> None:
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"
)
content = messages[msg_idx].get("content") or ""
if isinstance(content, list):
content = "".join(p.get("text", "") for p in content if isinstance(p, dict))
if not prev_is_tool:
emit_special(self._tool_outputs_begin, msg_idx)
emit_special(self._tool_output_begin, msg_idx)
emit_text(str(content), msg_idx)
emit_special(self._tool_output_end, msg_idx)
if not next_is_tool:
emit_special(self._tool_outputs_end, msg_idx)
+241
View File
@@ -0,0 +1,241 @@
"""Default Renderer — falls back to tokenizer.apply_chat_template() for unsupported models.
This is the escape hatch: works with any model that has a Jinja chat template,
but doesn't provide message_indices (so build_training_sample uses incremental
rendering) and parse_response is basic text extraction unless tool/reasoning
parsers are plugged in.
"""
from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
)
from renderers.parsers import (
ReasoningParser,
ToolParser,
get_reasoning_parser,
get_tool_parser,
)
def _decode_tool_call_arguments(messages: list) -> list:
"""JSON-decode assistant tool_call ``arguments`` strings into dicts.
OpenAI-format tool_calls carry ``arguments`` as a JSON-encoded string.
Several chat templates (GLM-4.5, GLM-5) iterate ``arguments.items()``
directly and crash on strings. Others (Qwen3 Hermes-style) branch on
string-vs-dict and handle both. Decoding to dict is safe for both.
Works on Pydantic AssistantMessage objects and plain dicts. Preserves
non-JSON argument strings as-is so Hermes-style templates can still
render them via the ``is string`` branch.
"""
out: list[Any] = []
for m in messages:
if isinstance(m, dict):
role = m.get("role")
tcs = m.get("tool_calls")
else:
role = getattr(m, "role", None)
tcs = getattr(m, "tool_calls", None)
if role != "assistant" or not tcs:
out.append(m)
continue
md = m if isinstance(m, dict) else m.model_dump() # type: ignore[attr-defined]
md = dict(md)
new_tcs: list[Any] = []
for tc in md.get("tool_calls") or []:
tc = dict(tc) if isinstance(tc, dict) else tc
fn = tc.get("function") if isinstance(tc, dict) else None
if isinstance(fn, dict):
fn = dict(fn)
args = fn.get("arguments")
if isinstance(args, str):
try:
fn["arguments"] = json.loads(args)
except (ValueError, TypeError):
pass
tc["function"] = fn
else:
args = tc.get("arguments") if isinstance(tc, dict) else None
if isinstance(args, str):
try:
tc["arguments"] = json.loads(args)
except (ValueError, TypeError):
pass
new_tcs.append(tc)
md["tool_calls"] = new_tcs
out.append(md)
return out
class DefaultRenderer:
"""Fallback renderer using tokenizer.apply_chat_template().
Works with any model. Pass ``tool_parser`` and/or ``reasoning_parser``
(by name, resolved against the registries in ``renderers.parsers``) to
enable structured output extraction.
"""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
tool_parser: str | ToolParser | None = None,
reasoning_parser: str | ReasoningParser | None = None,
**chat_template_kwargs,
):
self._tokenizer = tokenizer
self._chat_template_kwargs = chat_template_kwargs
self._tool_parser = _resolve_parser(tool_parser, tokenizer, get_tool_parser)
self._reasoning_parser = _resolve_parser(
reasoning_parser, tokenizer, get_reasoning_parser
)
@property
def supports_tools(self) -> bool:
return self._tool_parser is not None
def render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> RenderedTokens:
# Incremental rendering to get per-token message attribution
token_ids: list[int] = []
message_indices: list[int] = []
prev_len = 0
for idx, message in enumerate(messages):
cur_ids = self._apply(messages[: idx + 1], tools=tools)
new_tokens = cur_ids[prev_len:]
token_ids = cur_ids
message_indices.extend([idx] * len(new_tokens))
prev_len = len(cur_ids)
if add_generation_prompt:
full_ids = self._apply(messages, tools=tools, add_generation_prompt=True)
gen_tokens = full_ids[prev_len:]
token_ids = full_ids
message_indices.extend([-1] * len(gen_tokens))
return RenderedTokens(token_ids=token_ids, message_indices=message_indices)
def _apply(self, messages, *, tools=None, add_generation_prompt=False) -> list[int]:
kwargs = dict(self._chat_template_kwargs)
kwargs["add_generation_prompt"] = add_generation_prompt
kwargs["tokenize"] = True
if tools is not None:
kwargs["tools"] = tools
kwargs["return_dict"] = False
messages = _decode_tool_call_arguments(messages)
result = self._tokenizer.apply_chat_template(messages, **kwargs)
return list(result)
def render_ids(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> list[int]:
return self._apply(
messages, tools=tools, add_generation_prompt=add_generation_prompt
)
def parse_response(self, token_ids: list[int]) -> 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
# 2. Decode (keep special tokens so a downstream reasoning parser can
# still see things like <think>/</think> when they're tokens).
text = self._tokenizer.decode(content_ids, skip_special_tokens=False)
# 3. Extract reasoning from the decoded text. Falls back to a built-in
# <think>...</think> sniff so unconfigured users get the same behavior
# as before. Preserve whitespace at the <think>/</think> boundary —
# the chat template round-trips it verbatim (e.g. GLM emits
# `{{ '\\n<think>' + reasoning_content + '</think>' }}` then
# `{{- content }}` with no separator), so a leading `\\n` on content
# or trailing `\\n` on reasoning_content must stay in the parsed
# fields for re-render to be byte-identical. Stripping here causes
# the re-rendered assistant message to shift by one BPE token after
# `</think>`, cascading through downstream tokenization and breaking
# the "extension property" in trajectory step tokenization.
if self._reasoning_parser is not None:
reasoning_content, text = self._reasoning_parser.extract(text)
else:
reasoning_content = None
if "</think>" in text:
before, after = text.split("</think>", 1)
if "<think>" in before:
reasoning_content = before.split("<think>", 1)[-1]
else:
reasoning_content = before
text = after
# Strip any remaining special tokens from the final content (we kept
# them around for the reasoning parser above).
text = _strip_special_tokens(self._tokenizer, text)
return ParsedResponse(
content=text,
reasoning_content=reasoning_content if reasoning_content else None,
tool_calls=tool_calls,
)
def get_stop_token_ids(self) -> list[int]:
stop_ids = []
if self._tokenizer.eos_token_id is not None:
stop_ids.append(self._tokenizer.eos_token_id)
return stop_ids
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,
) -> list[int] | None:
"""DefaultRenderer wraps an unknown Jinja template — it has no
hand-coded extension logic to emit. Return ``None`` so the caller
falls back to a full re-render; that's correct whenever the
template is prefix-stable under the new messages, which our parity
suite enforces for anything we ship a renderer for.
"""
return None
def _resolve_parser(value, tokenizer, factory):
if value is None:
return None
if isinstance(value, str):
return factory(value, tokenizer)
return value
def _strip_special_tokens(tokenizer, text: str) -> str:
"""Remove any special-token substrings that slipped into decoded text."""
specials = getattr(tokenizer, "all_special_tokens", None) or []
for token in specials:
if token and token in text:
text = text.replace(token, "")
return text
+365
View File
@@ -0,0 +1,365 @@
"""GLM-4.5 Air Renderer — hard-coded Python mirroring the GLM-4.5 Jinja chat template.
Key differences from GLM-5:
- \\n after every role marker (<|user|>\\n, <|assistant|>\\n)
- <think></think>\\n separator (vs bare </think> in GLM-5)
- Tool calls have \\n between arg tags
- Thinking disabled via /nothink appended to user content
- Gen prompt (thinking=True): just <|assistant|> (no <think>)
"""
from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
)
from renderers.parsing import parse_glm
_TOOLS_HEADER = (
"\n# Tools\n\n"
"You may call one or more functions to assist with the user query.\n\n"
"You are provided with function signatures within <tools></tools> XML tags:\n"
"<tools>\n"
)
_TOOLS_FOOTER = (
"</tools>\n\n"
"For each function call, output the function name and arguments "
"within the following XML format:\n"
"<tool_call>{function-name}\n"
"<arg_key>{arg-key-1}</arg_key>\n"
"<arg_value>{arg-value-1}</arg_value>\n"
"<arg_key>{arg-key-2}</arg_key>\n"
"<arg_value>{arg-value-2}</arg_value>\n"
"...\n"
"</tool_call>"
)
class GLM45Renderer:
"""Deterministic message → token renderer for GLM-4.5 Air models."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._gmask = self._token_id("[gMASK]")
self._sop = self._token_id("<sop>")
self._system = self._token_id("<|system|>")
self._user = self._token_id("<|user|>")
self._assistant = self._token_id("<|assistant|>")
self._observation = self._token_id("<|observation|>")
self._endoftext = self._token_id("<|endoftext|>")
self._think = self._token_id("<think>")
self._think_end = self._token_id("</think>")
self._tool_call_tok = self._token_id("<tool_call>")
self._tool_call_end_tok = self._token_id("</tool_call>")
self._arg_key = self._token_id("<arg_key>")
self._arg_key_end = self._token_id("</arg_key>")
self._arg_value = self._token_id("<arg_value>")
self._arg_value_end = self._token_id("</arg_value>")
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: Any) -> str:
if content is None:
return "None"
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict) and item.get("type") == "text":
parts.append(item.get("text", ""))
return "".join(parts)
return str(content)
@staticmethod
def _last_user_index(messages: list[Message]) -> int:
for i in range(len(messages) - 1, -1, -1):
if messages[i].get("role") == "user":
return i
return -1
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))
# ── Prefix ──────────────────────────────────────────────────
emit_special(self._gmask, -1)
emit_special(self._sop, -1)
# ── Tools in system prompt ──────────────────────────────────
if tools:
emit_special(self._system, -1)
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += json.dumps(tool, ensure_ascii=False) + "\n"
tool_text += _TOOLS_FOOTER
emit_text(tool_text, -1)
# ── Compute last_user_index ─────────────────────────────────
last_ui = self._last_user_index(messages)
# ── Iterate messages ────────────────────────────────────────
for i, msg in enumerate(messages):
role = msg["role"]
content = self._visible_text(msg.get("content"))
if role == "system":
emit_special(self._system, i)
emit_text("\n" + content, i)
elif role == "user":
emit_special(self._user, i)
user_text = "\n" + content
if not self._enable_thinking and not content.endswith("/nothink"):
user_text += "/nothink"
emit_text(user_text, i)
elif role == "assistant":
self._render_assistant(
msg,
i,
content,
last_ui,
emit_special=emit_special,
emit_text=emit_text,
)
elif role == "tool":
self._render_tool(
messages, i, content, emit_special=emit_special, emit_text=emit_text
)
# ── Generation prompt ───────────────────────────────────────
if add_generation_prompt:
emit_special(self._assistant, -1)
if not self._enable_thinking:
emit_text("\n", -1)
emit_special(self._think, -1)
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]) -> ParsedResponse:
return parse_glm(
self._tokenizer,
token_ids,
stop_ids={self._endoftext, self._user, self._observation},
think_id=self._think,
think_end_id=self._think_end,
tool_call_id=self._tool_call_tok,
tool_call_end_id=self._tool_call_end_tok,
arg_key_id=self._arg_key,
arg_key_end_id=self._arg_key_end,
arg_value_id=self._arg_value,
arg_value_end_id=self._arg_value_end,
)
def get_stop_token_ids(self) -> list[int]:
return [self._endoftext, self._user, self._observation]
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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
# Same next-turn-marker scheme as GLM-5, but role markers are
# followed by a literal ``\n`` in the prompt text.
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
stop_ids = {self._endoftext, self._user, self._observation}
if (
not previous_ids[len(previous_prompt_ids) :]
or previous_ids[-1] not in stop_ids
):
previous_ids.append(self._endoftext)
last_prev = previous_ids[-1]
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 i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._visible_text(msg.get("content"))
if role == "user":
if not (i == 0 and last_prev == self._user):
emit_special(self._user, i)
user_text = "\n" + content
if not self._enable_thinking and not content.endswith("/nothink"):
user_text += "/nothink"
emit_text(user_text, i)
elif role == "system":
emit_special(self._system, i)
emit_text("\n" + content, i)
elif role == "tool":
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
if i == 0 and last_prev == self._observation:
pass
elif not prev_is_tool:
emit_special(self._observation, i)
emit_text("\n<tool_response>\n" + content + "\n</tool_response>", i)
else:
return None
# Generation prompt.
emit_special(self._assistant, -1)
if not self._enable_thinking:
emit_text("\n", -1)
emit_special(self._think, -1)
emit_special(self._think_end, -1)
return previous_ids + ext
def _render_assistant(
self, msg, msg_idx, content, last_user_index, *, emit_special, emit_text
):
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
elif "</think>" in content:
before, after = content.split("</think>", 1)
if "<think>" in before:
reasoning_content = before.split("<think>")[-1].lstrip("\n")
else:
reasoning_content = before.lstrip("\n")
reasoning_content = reasoning_content.rstrip("\n")
content = after.lstrip("\n")
emit_special(self._assistant, msg_idx)
if msg_idx > last_user_index and reasoning_content:
emit_text("\n", msg_idx)
emit_special(self._think, msg_idx)
emit_text(reasoning_content.strip(), msg_idx)
emit_special(self._think_end, msg_idx)
else:
emit_text("\n", msg_idx)
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
# Tool calls — keep content + \n contiguous to preserve BPE merges
tool_calls = msg.get("tool_calls") or []
if content.strip() and tool_calls:
emit_text("\n" + content.strip() + "\n", msg_idx)
elif content.strip():
emit_text("\n" + content.strip(), msg_idx)
for tc in tool_calls:
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
if not content.strip():
emit_text("\n", msg_idx)
emit_special(self._tool_call_tok, msg_idx)
emit_text(name + "\n", msg_idx)
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
emit_special(self._arg_key, msg_idx)
emit_text(arg_name, msg_idx)
emit_special(self._arg_key_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._arg_value, msg_idx)
if isinstance(arg_value, str):
emit_text(arg_value, msg_idx)
else:
emit_text(json.dumps(arg_value, ensure_ascii=False), msg_idx)
emit_special(self._arg_value_end, msg_idx)
emit_text("\n", msg_idx)
emit_special(self._tool_call_end_tok, msg_idx)
def _render_tool(
self,
messages: list[Message],
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
) -> None:
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
if not prev_is_tool:
emit_special(self._observation, msg_idx)
emit_text("\n<tool_response>\n" + content + "\n</tool_response>", msg_idx)
+409
View File
@@ -0,0 +1,409 @@
"""GLM-5 Renderer — hard-coded Python mirroring the GLM-5 Jinja chat template.
Key differences from Qwen family:
- Prefix: [gMASK]<sop> before all content
- Role markers: <|system|>, <|user|>, <|assistant|>, <|observation|> (no im_start/im_end)
- No end-of-message token — messages separated by next role marker
- Assistant always emits </think> as separator (even without thinking content)
- Tool calls: <tool_call>name<arg_key>k</arg_key><arg_value>v</arg_value></tool_call>
- Tool responses: <|observation|><tool_response>content</tool_response>
"""
from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
)
from renderers.parsing import parse_glm
_TOOLS_HEADER = (
"\n# Tools\n\n"
"You may call one or more functions to assist with the user query.\n\n"
"You are provided with function signatures within <tools></tools> XML tags:\n"
"<tools>\n"
)
_TOOLS_FOOTER = (
"</tools>\n\n"
"For each function call, output the function name and arguments "
"within the following XML format:\n"
"<tool_call>{function-name}"
"<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value>"
"<arg_key>{arg-key-2}</arg_key><arg_value>{arg-value-2}</arg_value>"
"...</tool_call>"
)
class GLM5Renderer:
"""Deterministic message → token renderer for GLM-5 models."""
# GLM-5.1 flips this on: even when the most-recent assistant has no
# reasoning content, the template wraps it with ``<think></think>``
# instead of just emitting ``</think>`` as a separator. Subclassed in
# GLM51Renderer; GLM-5 proper keeps this off.
empty_think_on_last_assistant: bool = False
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
clear_thinking: bool = True,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._clear_thinking = clear_thinking
self._gmask = self._token_id("[gMASK]")
self._sop = self._token_id("<sop>")
self._system = self._token_id("<|system|>")
self._user = self._token_id("<|user|>")
self._assistant = self._token_id("<|assistant|>")
self._observation = self._token_id("<|observation|>")
self._endoftext = self._token_id("<|endoftext|>")
self._think = self._token_id("<think>")
self._think_end = self._token_id("</think>")
self._tool_call_tok = self._token_id("<tool_call>")
self._tool_call_end_tok = self._token_id("</tool_call>")
self._tool_response_tok = self._token_id("<tool_response>")
self._tool_response_end_tok = self._token_id("</tool_response>")
self._arg_key = self._token_id("<arg_key>")
self._arg_key_end = self._token_id("</arg_key>")
self._arg_value = self._token_id("<arg_value>")
self._arg_value_end = self._token_id("</arg_value>")
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: Any) -> str:
if content is None:
return "None"
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict) and item.get("type") == "text":
parts.append(item.get("text", ""))
return "".join(parts)
return str(content)
@staticmethod
def _last_user_index(messages: list[Message]) -> int:
for i in range(len(messages) - 1, -1, -1):
if messages[i].get("role") == "user":
return i
return -1
@staticmethod
def _format_tool_spec(tool: ToolSpec) -> str:
"""Serialise a single tool spec to the exact JSON the Jinja template
emits. GLM-5 just ``tojson``s the dict as passed; GLM-5.1 overrides
this to unwrap the OpenAI-style ``{"type":"function","function":…}``
envelope and filter internal-only keys first.
"""
return json.dumps(tool, ensure_ascii=False)
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))
# ── Prefix ──────────────────────────────────────────────────
emit_special(self._gmask, -1)
emit_special(self._sop, -1)
# ── Tools in system prompt ──────────────────────────────────
if tools:
emit_special(self._system, -1)
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += self._format_tool_spec(tool) + "\n"
tool_text += _TOOLS_FOOTER
emit_text(tool_text, -1)
# ── Compute last_user_index ─────────────────────────────────
last_ui = self._last_user_index(messages)
# ── Iterate messages ────────────────────────────────────────
for i, msg in enumerate(messages):
role = msg["role"]
content = self._visible_text(msg.get("content"))
if role == "system":
emit_special(self._system, i)
emit_text(content, i)
elif role == "user":
emit_special(self._user, i)
emit_text(content, i)
elif role == "assistant":
self._render_assistant(
msg,
i,
content,
last_ui,
emit_special=emit_special,
emit_text=emit_text,
)
elif role == "tool":
self._render_tool(
messages, i, content, emit_special=emit_special, emit_text=emit_text
)
# ── Generation prompt ───────────────────────────────────────
if add_generation_prompt:
emit_special(self._assistant, -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]) -> ParsedResponse:
return parse_glm(
self._tokenizer,
token_ids,
stop_ids={self._endoftext, self._user, self._observation},
think_id=self._think,
think_end_id=self._think_end,
tool_call_id=self._tool_call_tok,
tool_call_end_id=self._tool_call_end_tok,
arg_key_id=self._arg_key,
arg_key_end_id=self._arg_key_end,
arg_value_id=self._arg_value,
arg_value_end_id=self._arg_value_end,
)
def get_stop_token_ids(self) -> list[int]:
return [self._endoftext, self._user, self._observation]
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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
# GLM has no per-turn close token. An assistant turn ends when the
# next turn's role marker appears, OR the model emits <|endoftext|>.
# vLLM includes these in ``stop_token_ids`` so a clean stop leaves
# one of {endoftext, user, observation} at the tail of
# previous_completion_ids. Truncation means none is there yet.
previous_ids = list(previous_prompt_ids) + list(previous_completion_ids)
stop_ids = {self._endoftext, self._user, self._observation}
if (
not previous_ids[len(previous_prompt_ids) :]
or previous_ids[-1] not in stop_ids
):
# Truncation: synthesise <|endoftext|> as the canonical turn end.
previous_ids.append(self._endoftext)
last_prev = previous_ids[-1]
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 i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._visible_text(msg.get("content"))
if role == "user":
# Dedup: model already emitted <|user|> as its stop token.
if not (i == 0 and last_prev == self._user):
emit_special(self._user, i)
emit_text(content, i)
elif role == "system":
emit_special(self._system, i)
emit_text(content, i)
elif role == "tool":
prev_is_tool = i > 0 and new_messages[i - 1].get("role") == "tool"
if i == 0 and last_prev == self._observation:
# Model already emitted <|observation|>; don't repeat.
pass
elif not prev_is_tool:
emit_special(self._observation, i)
emit_special(self._tool_response_tok, i)
emit_text(content, i)
emit_special(self._tool_response_end_tok, i)
else:
return None
# Generation prompt — match the gen-prompt branch of ``render()``.
emit_special(self._assistant, -1)
if self._enable_thinking:
emit_special(self._think, -1)
else:
emit_special(self._think_end, -1)
return previous_ids + ext
def _render_assistant(
self, msg, msg_idx, content, last_user_index, *, emit_special, emit_text
):
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
elif "</think>" in content:
before, after = content.split("</think>", 1)
if "<think>" in before:
reasoning_content = before.split("<think>")[-1].lstrip("\n")
else:
reasoning_content = before.lstrip("\n")
reasoning_content = reasoning_content.rstrip("\n")
content = after.lstrip("\n")
emit_special(self._assistant, msg_idx)
include_thinking = (
not self._clear_thinking or msg_idx > last_user_index
) and reasoning_content
if include_thinking:
emit_special(self._think, msg_idx)
emit_text(reasoning_content.strip(), msg_idx)
emit_special(self._think_end, msg_idx)
elif self.empty_think_on_last_assistant and msg_idx > last_user_index:
# GLM-5.1: wrap the last assistant with an empty <think></think>
# even without reasoning, matching the Jinja template.
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
else:
emit_special(self._think_end, msg_idx)
if content.strip():
emit_text(content.strip(), msg_idx)
# Tool calls (directly after content, no newlines)
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", {})
emit_special(self._tool_call_tok, msg_idx)
emit_text(name, msg_idx)
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
emit_special(self._arg_key, msg_idx)
emit_text(arg_name, msg_idx)
emit_special(self._arg_key_end, msg_idx)
emit_special(self._arg_value, msg_idx)
if isinstance(arg_value, str):
emit_text(arg_value, msg_idx)
else:
emit_text(json.dumps(arg_value, ensure_ascii=False), msg_idx)
emit_special(self._arg_value_end, msg_idx)
emit_special(self._tool_call_end_tok, msg_idx)
def _render_tool(
self,
messages: list[Message],
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
) -> None:
prev_is_tool = msg_idx > 0 and messages[msg_idx - 1]["role"] == "tool"
if not prev_is_tool:
emit_special(self._observation, msg_idx)
emit_special(self._tool_response_tok, msg_idx)
emit_text(content, msg_idx)
emit_special(self._tool_response_end_tok, msg_idx)
class GLM51Renderer(GLM5Renderer):
"""Deterministic message → token renderer for GLM-5.1 models.
Diverges from GLM-5 in two places:
- The most-recent assistant turn is wrapped with an empty
``<think></think>`` block even when no ``reasoning_content`` is
supplied. Historical assistants collapse to just ``</think>``.
- Tool specs are unwrapped before serialisation: if the caller
passes the OpenAI ``{"type":"function","function":{…}}`` envelope,
only the inner ``function`` payload is rendered (minus
``defer_loading`` / ``strict`` internal keys).
"""
empty_think_on_last_assistant = True
@staticmethod
def _format_tool_spec(tool: ToolSpec) -> str:
spec = tool["function"] if "function" in tool else tool
spec = {k: v for k, v in spec.items() if k not in ("defer_loading", "strict")}
return json.dumps(spec, ensure_ascii=False)
+459
View File
@@ -0,0 +1,459 @@
"""GptOssRenderer — adapter over OpenAI's harmony reference encoder.
Wire format: harmony (channel-based, no BOS). The official renderer ships
in the ``openai-harmony`` package — vLLM uses it directly, so matching
its output guarantees byte-identical tokens with vLLM's serving path
(and with what the model was trained on).
This renderer is a thin adapter that:
- converts each ``RendererMessage`` to one or more ``openai_harmony``
messages (assistant tool_calls split into per-call ASSISTANT messages
with channel=commentary and recipient=functions.<name>; tool results
routed via TOOL author + recipient=assistant)
- prepends the canonical SystemContent preamble (model identity,
knowledge cutoff, current date, reasoning_effort, channel config)
when ``use_system_prompt`` is set — matches HF's apply_chat_template
behaviour, which the model was trained against
- renders one harmony message at a time via ``enc.render(m)`` so each
token can be attributed to its source caller index. ``enc.render``
is byte-identical to ``enc.render_conversation`` when concatenated;
verified empirically.
Special tokens
--------------
<|start|> message start
<|end|> message end (non-terminal)
<|return|> message end (terminal — last assistant turn)
<|call|> tool call end (terminal)
<|channel|> followed by channel name
<|message|> content start
<|constrain|> followed by constraint (e.g. "json")
"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any
from openai_harmony import (
Conversation,
DeveloperContent,
HarmonyEncoding,
HarmonyEncodingName,
Message as HarmonyMessage,
ReasoningEffort,
Role,
SystemContent,
ToolDescription,
load_harmony_encoding,
)
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.parsing import parse_gpt_oss
def _reasoning_effort(effort: str | None) -> ReasoningEffort:
if effort is None:
return ReasoningEffort.MEDIUM
e = effort.lower()
if e == "low":
return ReasoningEffort.LOW
if e == "medium":
return ReasoningEffort.MEDIUM
if e == "high":
return ReasoningEffort.HIGH
raise ValueError(f"Unknown reasoning_effort: {effort!r}")
def _content_text(content: Any) -> str:
"""Flatten content (string or list of parts) to plain text."""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
out = []
for p in content:
if not isinstance(p, dict):
continue
ptype = p.get("type")
if ptype == "text":
out.append(p.get("text", ""))
elif ptype == "thinking":
out.append(p.get("thinking", ""))
return "".join(out)
return str(content)
def _tool_to_description(tool: ToolSpec) -> ToolDescription:
"""Convert an OpenAI-format tool spec to a harmony ToolDescription."""
if tool.get("type") == "function" and isinstance(tool.get("function"), dict):
fn = tool["function"]
else:
fn = tool
return ToolDescription.new(
name=fn.get("name", ""),
description=fn.get("description", ""),
parameters=fn.get("parameters") or {},
)
def _arguments_to_str(arguments: Any) -> str:
if isinstance(arguments, str):
return arguments
return json.dumps(arguments, ensure_ascii=False)
class GptOssRenderer:
"""Deterministic message → token renderer for OpenAI gpt-oss (harmony)."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
use_system_prompt: bool = True,
reasoning_effort: str | None = "medium",
conversation_start_date: str | None = None,
knowledge_cutoff: str | None = None,
model_identity: str | None = None,
):
"""Initialise the renderer.
Args:
tokenizer: HuggingFace tokenizer.
use_system_prompt: When True (default), prepend the canonical
harmony SystemContent preamble. Matches HF's
apply_chat_template behaviour.
reasoning_effort: ``"low" | "medium" | "high"``. Default
``"medium"`` (matches apply_chat_template).
conversation_start_date: Optional ISO date for the preamble.
Defaults to today's date in YYYY-MM-DD form.
knowledge_cutoff: Optional knowledge cutoff string. Harmony's
default is built into ``SystemContent.new()``.
model_identity: Optional override for the model identity line.
"""
self._tokenizer = tokenizer
self._enc: HarmonyEncoding = load_harmony_encoding(
HarmonyEncodingName.HARMONY_GPT_OSS
)
self._use_system_prompt = use_system_prompt
self._reasoning_effort = _reasoning_effort(reasoning_effort)
self._conversation_start_date = (
conversation_start_date or datetime.now().strftime("%Y-%m-%d")
)
self._knowledge_cutoff = knowledge_cutoff
self._model_identity = model_identity
# Cache special-token IDs for the bridge / generation-prompt path.
self._start = self._token_id("<|start|>")
self._end = self._token_id("<|end|>")
self._return = self._token_id("<|return|>")
self._call = self._token_id("<|call|>")
self._channel = self._token_id("<|channel|>")
self._message = self._token_id("<|message|>")
self._constrain = self._token_id("<|constrain|>")
# ── token utilities ──────────────────────────────────────────────────────
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)
# ── public interface ─────────────────────────────────────────────────────
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(ids: list[int], msg_idx: int) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
# ── Build harmony prefix (system + developer) ───────────────────
# When tools are present, harmony's conversation-level renderer
# injects a channel-routing line into the SystemContent block
# (``Calls to these tools must go to the commentary channel:
# 'functions'.``). Per-message ``enc.render`` doesn't know about
# the surrounding tool namespaces, so we render the prefix via
# ``render_conversation`` to pick that up correctly.
first_system_idx = next(
(i for i, m in enumerate(messages) if m.get("role") == "system"),
None,
)
prefix_msgs: list[HarmonyMessage] = []
if self._use_system_prompt:
sys_content = SystemContent.new().with_reasoning_effort(
self._reasoning_effort
)
sys_content = sys_content.with_conversation_start_date(
self._conversation_start_date
)
if self._knowledge_cutoff is not None:
sys_content = sys_content.with_knowledge_cutoff(self._knowledge_cutoff)
if self._model_identity is not None:
sys_content = sys_content.with_model_identity(self._model_identity)
prefix_msgs.append(
HarmonyMessage.from_role_and_content(Role.SYSTEM, sys_content)
)
if first_system_idx is not None or tools:
dev = DeveloperContent.new()
if first_system_idx is not None:
instructions = _content_text(messages[first_system_idx].get("content"))
if instructions:
dev = dev.with_instructions(instructions)
if tools:
dev = dev.with_function_tools([_tool_to_description(t) for t in tools])
prefix_msgs.append(
HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev)
)
if prefix_msgs:
prefix_tokens = self._enc.render_conversation(
Conversation.from_messages(prefix_msgs)
)
# Attribute the whole prefix block to first_system_idx if the
# caller supplied a system message (so its content has *some*
# caller-relative attribution); otherwise to -1 (pure scaffolding).
prefix_origin = first_system_idx if first_system_idx is not None else -1
emit(prefix_tokens, prefix_origin)
# ── Iterate the rest of the messages ────────────────────────────
last_idx = len(messages) - 1
for i, msg in enumerate(messages):
if i == first_system_idx:
continue # already emitted as developer
for hm in self._to_harmony_messages(msg):
emit(self._enc.render(hm), i)
# When the conversation ends on an assistant final-channel turn,
# ``apply_chat_template`` (and ``render_conversation_for_training``)
# close it with ``<|return|>`` instead of ``<|end|>`` to mark the
# final assistant turn as terminal. Per-message rendering always
# uses ``<|end|>``, so patch it here when applicable.
if (
not add_generation_prompt
and last_idx >= 0
and messages[last_idx].get("role") == "assistant"
and tokens
and tokens[-1] == self._end
and not (messages[last_idx].get("tool_calls"))
):
tokens[-1] = self._return
# ── Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
if add_generation_prompt:
emit([self._start], -1)
emit(self._encode("assistant"), -1)
emit([self._channel], -1)
emit(self._encode("analysis"), -1)
emit([self._message], -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]) -> ParsedResponse:
return parse_gpt_oss(
self._tokenizer,
token_ids,
return_id=self._return,
call_id=self._call,
start_id=self._start,
end_id=self._end,
channel_id=self._channel,
message_id=self._message,
constrain_id=self._constrain,
)
def get_stop_token_ids(self) -> list[int]:
return [self._return, self._call]
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,
) -> list[int] | None:
"""Per-message harmony bridge.
Each new message is rendered in isolation via ``enc.render(m)`` —
same primitive ``render()`` uses — so the bridge can never drift
from the full re-render.
"""
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._return, self._call},
synthesize_close=self._end,
)
if previous_ids is None:
return None
ext: list[int] = []
for msg in new_messages:
role = msg.get("role")
if role not in ("tool", "user", "system", "developer"):
return None
for hm in self._to_harmony_messages(msg):
ext.extend(self._enc.render(hm))
# Generation prompt: <|start|>assistant<|channel|>analysis<|message|>
ext.append(self._start)
ext.extend(self._encode("assistant"))
ext.append(self._channel)
ext.extend(self._encode("analysis"))
ext.append(self._message)
return previous_ids + ext
# ── message conversion ───────────────────────────────────────────────────
def _to_harmony_messages(self, msg: Message) -> list[HarmonyMessage]:
"""Convert a single RendererMessage to one or more harmony messages.
Splits in two cases:
- assistant with reasoning_content + content → analysis message
then final message
- assistant with multiple tool_calls → one ASSISTANT message per
tool_call, with recipient=functions.<name>, channel=commentary
"""
role = msg.get("role", "")
if role == "user":
return [
HarmonyMessage.from_role_and_content(
Role.USER, _content_text(msg.get("content"))
)
]
if role == "system" or role == "developer":
# Caller's system message is normally pulled out as developer
# Instructions in render(); reaching here means it's a
# secondary system or an explicit developer message. Render
# as developer with the content as instructions.
dev = DeveloperContent.new().with_instructions(
_content_text(msg.get("content"))
)
return [HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev)]
if role == "tool":
# Tool result. Author needs the function name; we recover it
# from `name` (set client-side via _attach_tool_call_names) or
# from the message dict.
tool_name = msg.get("name") or "unknown"
if not tool_name.startswith("functions."):
tool_name = f"functions.{tool_name}"
content = _content_text(msg.get("content"))
tm = HarmonyMessage.from_author_and_content(
{"role": "tool", "name": tool_name}, content
)
tm = tm.with_recipient("assistant").with_channel("commentary")
return [tm]
if role == "assistant":
return self._assistant_to_harmony(msg)
# Unknown role: render as developer with the raw content.
dev = DeveloperContent.new().with_instructions(
_content_text(msg.get("content"))
)
return [HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev)]
def _assistant_to_harmony(self, msg: Message) -> list[HarmonyMessage]:
"""Convert an assistant message to harmony messages.
Layout:
- text content (if any) → final channel
- each tool_call → commentary channel,
recipient=functions.<name>
``reasoning_content`` is intentionally NOT emitted: harmony strips
analysis-channel messages from history-style rendering (verified
against ``HarmonyEncoding.render_conversation`` /
``render_conversation_for_training``). Per-turn thinking is only
relevant for live generation; once a turn closes, its analysis
block is dropped from context.
"""
out: list[HarmonyMessage] = []
content = msg.get("content")
text_parts: list[str] = []
if isinstance(content, list):
for p in content:
if not isinstance(p, dict):
continue
if p.get("type") == "text":
text_parts.append(p.get("text", ""))
# Thinking parts are dropped (see docstring).
elif isinstance(content, str):
text_parts.append(content)
text = "".join(text_parts)
if text:
m = HarmonyMessage.from_role_and_content(Role.ASSISTANT, text)
m = m.with_channel("final")
out.append(m)
tool_calls = msg.get("tool_calls") or []
for tc in tool_calls:
fn = tc.get("function") or tc
name = fn.get("name", "")
args = _arguments_to_str(fn.get("arguments", {}))
recipient = name if name.startswith("functions.") else f"functions.{name}"
m = HarmonyMessage.from_role_and_content(Role.ASSISTANT, args)
m = m.with_channel("commentary").with_recipient(recipient)
out.append(m)
# Empty assistant (no text and no tool_calls) — emit an empty
# final-channel message so message_indices stays non-empty.
if not out:
m = HarmonyMessage.from_role_and_content(Role.ASSISTANT, "")
m = m.with_channel("final")
out.append(m)
return out
+426
View File
@@ -0,0 +1,426 @@
"""Kimi K2 Renderer — hard-coded Python mirroring the Kimi K2 Jinja chat template.
Key characteristics:
- Role tokens: <|im_user|>, <|im_assistant|>, <|im_system|>
- Separator token: <|im_middle|> between role name and content
- Terminator token: <|im_end|>
- Tool calls wrapped in <|tool_calls_section_begin|>...<|tool_calls_section_end|>
with individual calls in <|tool_call_begin|>id<|tool_call_argument_begin|>args<|tool_call_end|>
- Tool declaration messages use role="tool_declare" with <|im_system|>tool_declare<|im_middle|>
- Tool results use role="tool" with <|im_system|>{name}<|im_middle|>## Return of {id}\\n
- Thinking uses text tags <think>...</think>; historical messages strip to <think></think>
- Default system message injected if none present
"""
from __future__ import annotations
import json
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.parsing import parse_kimi_k2
_DEFAULT_SYSTEM = "You are Kimi, an AI assistant created by Moonshot AI."
class KimiK2Renderer:
"""Deterministic message → token renderer for Kimi K2 models."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._im_user = self._token_id("<|im_user|>")
self._im_assistant = self._token_id("<|im_assistant|>")
self._im_system = self._token_id("<|im_system|>")
self._im_middle = self._token_id("<|im_middle|>")
self._im_end = self._token_id("<|im_end|>")
self._tool_calls_section_begin = self._token_id("<|tool_calls_section_begin|>")
self._tool_calls_section_end = self._token_id("<|tool_calls_section_end|>")
self._tool_call_begin = self._token_id("<|tool_call_begin|>")
self._tool_call_argument_begin = self._token_id("<|tool_call_argument_begin|>")
self._tool_call_end = self._token_id("<|tool_call_end|>")
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)
def _ensure_system_message(
self, messages: list[Message]
) -> tuple[list[Message], int]:
"""Prepend default system message if none present.
Returns ``(messages, auto_injected_idx)``. ``auto_injected_idx`` is
the index of the auto-injected system message in the returned list,
or ``-1`` if no injection happened. The Jinja template emits a
literal ``\\n`` after the auto-injected system's ``<|im_end|>``
(but not after a user-supplied system), so the caller uses this
index to replicate that.
- If messages is empty: return list with just the default system message.
- If first message is tool_declare and no system follows: insert default
system after tool_declare.
- If first message is not system (and not tool_declare): prepend default.
- Otherwise: return unchanged.
"""
if not messages:
return [{"role": "system", "content": _DEFAULT_SYSTEM}], 0
first_role = messages[0].get("role")
if first_role == "tool_declare":
if len(messages) >= 2 and messages[1].get("role") == "system":
return messages, -1
default_sys: Message = {"role": "system", "content": _DEFAULT_SYSTEM}
return [messages[0], default_sys] + list(messages[1:]), 1
elif first_role != "system":
default_sys = {"role": "system", "content": _DEFAULT_SYSTEM}
return [default_sys] + list(messages), 0
return messages, -1
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.")
# Inject tools as tool_declare message + ensure system message.
# The Jinja template emits the tools list directly (no
# ``{"type":"function","function":...}`` wrapper) using
# ``tojson(separators=(',', ':'))``, which produces compact JSON
# with sorted keys — match both to stay byte-identical.
if tools:
tools_json = json.dumps(
list(tools), separators=(",", ":"), sort_keys=True, ensure_ascii=False
)
tool_declare_msg: Message = {
"role": "tool_declare",
"content": tools_json,
}
# Prepend tool_declare if not already present
if messages[0].get("role") != "tool_declare":
messages = [tool_declare_msg] + list(messages)
tool_declare_injected = True
else:
tool_declare_injected = False
# else leave as-is (caller already included tool_declare)
else:
tool_declare_injected = False
messages, auto_system_idx = self._ensure_system_message(messages)
# Map indices in the (possibly-normalised) ``messages`` list back to
# the caller's original list. Injected system / tool_declare get
# msg_idx=-1 (sentinel) so build_training_sample can't dereference
# past the caller's input length.
injected_positions = set()
if tool_declare_injected:
injected_positions.add(0)
if auto_system_idx >= 0:
injected_positions.add(auto_system_idx)
n_injected_before = [0] * (len(messages) + 1)
for k in range(len(messages)):
n_injected_before[k + 1] = n_injected_before[k] + (
1 if k in injected_positions else 0
)
def orig_idx(i: int) -> int:
if i in injected_positions:
return -1
return i - n_injected_before[i]
token_ids: list[int] = []
indices: list[int] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
token_ids.extend(ids)
indices.extend([msg_idx] * len(ids))
def emit_special(token_id: int, msg_idx: int) -> None:
token_ids.append(token_id)
indices.append(msg_idx)
def emit_text(text: str, msg_idx: int) -> None:
emit_ids(self._encode(text), msg_idx)
# Compute last non-tool-call assistant index to determine thinking preservation
last_plain_assistant_idx = -1
for i in range(len(messages) - 1, -1, -1):
if messages[i]["role"] == "assistant" and not messages[i].get("tool_calls"):
last_plain_assistant_idx = i
break
for i, msg in enumerate(messages):
role = msg.get("role", "")
content = msg.get("content") or ""
if not isinstance(content, str):
# Flatten list content to text
parts: list[str] = []
for part in content:
if isinstance(part, dict):
if part.get("type") == "text":
parts.append(part.get("text", ""))
elif part.get("type") == "thinking":
parts.append(
"<think>" + part.get("thinking", "") + "</think>"
)
elif isinstance(part, str):
parts.append(part)
content = "".join(parts)
oi = orig_idx(i)
if role == "system":
emit_special(self._im_system, oi)
emit_text("system", oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
# Jinja emits a literal newline only after the auto-injected
# system's <|im_end|> (see _ensure_system_message's contract).
if i == auto_system_idx:
emit_text("\n", oi)
elif role == "tool_declare":
emit_special(self._im_system, oi)
emit_text("tool_declare", oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
elif role == "user":
emit_special(self._im_user, oi)
emit_text("user", oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
elif role == "assistant":
# Kimi strips reasoning from historical assistant turns and
# only keeps it for the most-recent plain assistant. Off-by-one
# here would drop reasoning from the last turn too.
is_last_turn = (
last_plain_assistant_idx == -1 or i >= last_plain_assistant_idx
)
self._render_assistant(
msg,
oi,
content,
is_last_turn=is_last_turn,
emit_special=emit_special,
emit_text=emit_text,
)
elif role == "tool":
self._render_tool(
msg, oi, content, emit_special=emit_special, emit_text=emit_text
)
else:
# Unknown role: use system-style formatting
emit_special(self._im_system, oi)
emit_text(role, oi)
emit_special(self._im_middle, oi)
emit_text(content, oi)
emit_special(self._im_end, oi)
# Generation prompt
if add_generation_prompt:
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
return RenderedTokens(token_ids=token_ids, 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]) -> ParsedResponse:
return parse_kimi_k2(
self._tokenizer,
token_ids,
stop_ids={self._im_end},
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,
)
def get_stop_token_ids(self) -> list[int]:
return [self._im_end]
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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._im_end},
synthesize_close=self._im_end,
)
if previous_ids is None:
return None
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 i, msg in enumerate(new_messages):
role = msg.get("role")
content = msg.get("content") or ""
if not isinstance(content, str):
parts: list[str] = []
for part in content:
if isinstance(part, dict):
if part.get("type") == "text":
parts.append(part.get("text", ""))
elif part.get("type") == "thinking":
parts.append(
"<think>" + part.get("thinking", "") + "</think>"
)
elif isinstance(part, str):
parts.append(part)
content = "".join(parts)
if role == "user":
emit_special(self._im_user, i)
emit_text("user", i)
emit_special(self._im_middle, i)
emit_text(content, i)
emit_special(self._im_end, i)
elif role == "system":
emit_special(self._im_system, i)
emit_text("system", i)
emit_special(self._im_middle, i)
emit_text(content, i)
emit_special(self._im_end, i)
elif role == "tool":
self._render_tool(
msg, i, content, emit_special=emit_special, emit_text=emit_text
)
else:
return None
# Generation prompt.
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
return previous_ids + ext
def _render_assistant(
self,
msg: Message,
msg_idx: int,
content: str,
*,
is_last_turn: bool,
emit_special,
emit_text,
) -> None:
emit_special(self._im_assistant, msg_idx)
emit_text("assistant", msg_idx)
emit_special(self._im_middle, msg_idx)
# Kimi K2's Jinja template has no reasoning-content support: the
# assistant turn renders its ``content`` verbatim, including any
# inline ``<think>...</think>`` tags. The separate
# ``reasoning_content`` field is dropped (the template never reads
# it). ``is_last_turn`` is unused here for the same reason.
_ = is_last_turn
emit_text(content, msg_idx)
# Tool calls
tool_calls = msg.get("tool_calls") or []
if tool_calls:
emit_special(self._tool_calls_section_begin, msg_idx)
for tc in tool_calls:
func = tc.get("function") or tc
arguments = func.get("arguments", {})
args_str = (
json.dumps(arguments, ensure_ascii=False)
if not isinstance(arguments, str)
else arguments
)
# The Jinja template emits ``tool_call['id']`` verbatim —
# empty when missing. Round-trip parseability requires the
# caller to provide an id in ``functions.{name}:{idx}`` form
# (that's where the Kimi parser recovers the function name).
tc_id = tc.get("id") or ""
emit_special(self._tool_call_begin, msg_idx)
emit_text(tc_id, msg_idx)
emit_special(self._tool_call_argument_begin, msg_idx)
emit_text(args_str, msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_calls_section_end, msg_idx)
emit_special(self._im_end, msg_idx)
def _render_tool(
self,
msg: Message,
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
) -> None:
name = msg.get("name") or "tool"
tool_call_id = msg.get("tool_call_id") or ""
emit_special(self._im_system, msg_idx)
emit_text(name, msg_idx)
emit_special(self._im_middle, msg_idx)
emit_text(f"## Return of {tool_call_id}\n", msg_idx)
emit_text(content, msg_idx)
emit_special(self._im_end, msg_idx)
+967
View File
@@ -0,0 +1,967 @@
"""Kimi K2.5 Renderer — standalone implementation for moonshotai/Kimi-K2.5-Instruct.
Kimi K2.5 shares the same tokenizer and base message format as Kimi K2
(moonshotai/Kimi-K2-Instruct) but adds:
1. Thinking mode via a ``<think>`` prefill in the generation prompt.
2. Multimodal/vision support via ``<|media_begin|>image<|media_content|>...<|media_end|>``.
3. TypeScript-style tool declarations instead of JSON.
Message format (identical to K2):
<|im_system|>system<|im_middle|>You are Kimi...<|im_end|>
<|im_user|>user<|im_middle|>Hello<|im_end|>
<|im_assistant|>assistant<|im_middle|><think>\\n...\\n</think>\\nResponse<|im_end|>
Generation prompt (thinking enabled):
<|im_assistant|>assistant<|im_middle|><think>
Generation prompt (thinking disabled):
<|im_assistant|>assistant<|im_middle|><think></think>
"""
from __future__ import annotations
import json
import re
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
trim_to_turn_close,
)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
_DEFAULT_SYSTEM_PROMPT = "You are Kimi, an AI assistant created by Moonshot AI."
# ---------------------------------------------------------------------------
# TypeScript-style tool declaration
# ---------------------------------------------------------------------------
_TS_INDENT = " "
_TS_FIELD_DELIMITER = ",\n"
def _format_description(description: str, indent: str = "") -> str:
return "\n".join(
[f"{indent}// {line}" if line else "" for line in description.split("\n")]
)
class _BaseType:
description: str
constraints: dict[str, Any]
def __init__(self, extra_props: dict[str, Any], *, allowed_constraint_keys=()):
self.description = extra_props.get("description", "")
self.constraints = {
k: v for k, v in extra_props.items() if k in allowed_constraint_keys
}
def to_typescript_style(self, indent: str = "") -> str:
raise NotImplementedError
def format_docstring(self, indent: str) -> str:
lines = []
if self.description:
lines.append(_format_description(self.description, indent))
if self.constraints:
constraints_str = ", ".join(
f"{k}: {v}"
for k, v in sorted(self.constraints.items(), key=lambda kv: kv[0])
)
lines.append(f"{indent}// {constraints_str}")
return "".join(x + "\n" for x in lines)
class _SchemaRegistry:
def __init__(self):
self.definitions: dict[str, Any] = {}
self.has_self_ref = False
def register_definitions(self, defs: dict[str, Any]) -> None:
for def_name, def_schema in defs.items():
self.definitions[def_name] = def_schema
def resolve_ref(self, ref: str) -> dict[str, Any]:
if ref == "#":
self.has_self_ref = True
return {"$self_ref": True}
elif ref.startswith("#/$defs/"):
def_name = ref.split("/")[-1]
if def_name not in self.definitions:
raise ValueError(f"Reference not found: {ref}")
return self.definitions[def_name]
else:
raise ValueError(f"Unsupported reference format: {ref}")
class _ScalarType(_BaseType):
def __init__(self, type_: str, extra_props: dict[str, Any] | None = None):
self.type_ = type_
allowed: list[str] = []
if type_ == "string":
allowed = ["maxLength", "minLength", "pattern"]
elif type_ in ("number", "integer"):
allowed = ["maximum", "minimum"]
super().__init__(extra_props or {}, allowed_constraint_keys=allowed)
def to_typescript_style(self, indent: str = "") -> str:
return "number" if self.type_ == "integer" else self.type_
class _ObjectType(_BaseType):
def __init__(self, schema: dict[str, Any], registry: _SchemaRegistry | None = None):
super().__init__(schema)
self.properties: list[_TypedParam] = []
self.additional_properties: Any = None
if not schema:
return
if "$defs" in schema and registry:
registry.register_definitions(schema["$defs"])
self.additional_properties = schema.get("additionalProperties")
if isinstance(self.additional_properties, dict):
self.additional_properties = _parse_type(
self.additional_properties, registry
)
if "properties" not in schema:
return
required = set(schema.get("required", []))
for name, prop in schema["properties"].items():
self.properties.append(
_TypedParam(
name=name,
type_=_parse_type(prop, registry),
optional=name not in required,
default=prop.get("default") if isinstance(prop, dict) else None,
)
)
def to_typescript_style(self, indent: str = "") -> str:
required_params = sorted(
[p for p in self.properties if not p.optional], key=lambda p: p.name
)
optional_params = sorted(
[p for p in self.properties if p.optional], key=lambda p: p.name
)
params = required_params + optional_params
param_strs = [p.to_typescript_style(indent=indent + _TS_INDENT) for p in params]
if self.additional_properties is not None:
if self.additional_properties is True:
ap_type = "any"
elif self.additional_properties is False:
ap_type = "never"
else:
ap_type = self.additional_properties.to_typescript_style(
indent=indent + _TS_INDENT
)
param_strs.append(f"{indent + _TS_INDENT}[k: string]: {ap_type}")
if not param_strs:
return "{}"
params_str = _TS_FIELD_DELIMITER.join(param_strs)
return f"{{\n{params_str}\n{indent}}}"
class _ArrayType(_BaseType):
def __init__(self, schema: dict[str, Any], registry: _SchemaRegistry | None = None):
super().__init__(schema, allowed_constraint_keys=("minItems", "maxItems"))
self.item = (
_parse_type(schema["items"], registry)
if schema.get("items")
else _ScalarType("any")
)
def to_typescript_style(self, indent: str = "") -> str:
docstring = self.item.format_docstring(indent + _TS_INDENT)
if docstring:
return (
"Array<\n"
+ docstring
+ indent
+ _TS_INDENT
+ self.item.to_typescript_style(indent=indent + _TS_INDENT)
+ "\n"
+ indent
+ ">"
)
return f"Array<{self.item.to_typescript_style(indent=indent)}>"
class _EnumType(_BaseType):
def __init__(self, schema: dict[str, Any]):
super().__init__(schema)
self.enum = schema["enum"]
def to_typescript_style(self, indent: str = "") -> str:
return " | ".join(f'"{e}"' if isinstance(e, str) else str(e) for e in self.enum)
class _AnyOfType(_BaseType):
def __init__(self, schema: dict[str, Any], registry: _SchemaRegistry | None = None):
super().__init__(schema)
self.types = [_parse_type(t, registry) for t in schema["anyOf"]]
def to_typescript_style(self, indent: str = "") -> str:
return " | ".join(t.to_typescript_style(indent=indent) for t in self.types)
class _UnionType(_BaseType):
_MAPPING = {
"string": "string",
"number": "number",
"integer": "number",
"boolean": "boolean",
"null": "null",
"object": "{}",
"array": "Array<any>",
}
def __init__(self, schema: dict[str, Any]):
super().__init__(schema)
self.types = [self._MAPPING[t] for t in schema["type"]]
def to_typescript_style(self, indent: str = "") -> str:
return " | ".join(self.types)
class _RefType(_BaseType):
def __init__(self, schema: dict[str, Any], registry: _SchemaRegistry):
super().__init__(schema)
ref = schema["$ref"]
resolved = registry.resolve_ref(ref)
if resolved.get("$self_ref", False):
self.ref_name = "parameters"
self.is_self_ref = True
else:
self.ref_name = ref.split("/")[-1]
self.is_self_ref = False
def to_typescript_style(self, indent: str = "") -> str:
return self.ref_name
_ParamType = (
_ScalarType
| _ObjectType
| _ArrayType
| _EnumType
| _AnyOfType
| _UnionType
| _RefType
)
class _TypedParam:
def __init__(
self, name: str, type_: _ParamType, optional: bool = True, default: Any = None
):
self.name = name
self.type_ = type_
self.optional = optional
self.default = default
def to_typescript_style(self, indent: str = "") -> str:
comments = self.type_.format_docstring(indent)
if self.default is not None:
default_repr = (
json.dumps(self.default, ensure_ascii=False)
if not isinstance(self.default, (int, float, bool))
else repr(self.default)
)
comments += f"{indent}// Default: {default_repr}\n"
opt = "?" if self.optional else ""
return (
comments
+ f"{indent}{self.name}{opt}: {self.type_.to_typescript_style(indent=indent)}"
)
def _parse_type(
schema: dict[str, Any] | bool, registry: _SchemaRegistry | None = None
) -> _ParamType:
if isinstance(schema, bool):
return _ScalarType("any" if schema else "null")
if "$ref" in schema and registry:
return _RefType(schema, registry)
if "anyOf" in schema:
return _AnyOfType(schema, registry)
if "enum" in schema:
return _EnumType(schema)
if "type" in schema:
typ = schema["type"]
if isinstance(typ, list):
return _UnionType(schema)
if typ == "object":
return _ObjectType(schema, registry)
if typ == "array":
return _ArrayType(schema, registry)
return _ScalarType(typ, schema)
if schema == {}:
return _ScalarType("any")
raise ValueError(f"Invalid JSON Schema object: {schema}")
def _function_to_typescript(function: dict[str, Any]) -> str:
"""Convert an OpenAI-format function definition to TypeScript-style string."""
registry = _SchemaRegistry()
parameters = function.get("parameters") or {}
parsed = _ObjectType(parameters, registry)
interfaces: list[str] = []
root_interface_name: str | None = None
if registry.has_self_ref:
root_interface_name = "parameters"
params_str = _TS_FIELD_DELIMITER.join(
p.to_typescript_style(indent=_TS_INDENT) for p in parsed.properties
)
params_str = f"\n{params_str}\n" if params_str else ""
interfaces.append(f"interface {root_interface_name} {{{params_str}}}")
for def_name, def_schema in registry.definitions.items():
obj_type = _parse_type(def_schema, registry)
params_str = obj_type.to_typescript_style()
description_part = ""
if desc := def_schema.get("description", ""):
description_part = _format_description(desc) + "\n"
interfaces.append(f"{description_part}interface {def_name} {params_str}")
interface_str = "\n".join(interfaces)
func_name = function.get("name", "function")
if root_interface_name:
type_def = f"type {func_name} = (_: {root_interface_name}) => any;"
else:
params_str = parsed.to_typescript_style()
type_def = f"type {func_name} = (_: {params_str}) => any;"
description = function.get("description")
return "\n".join(
filter(
bool,
[
interface_str,
(description and _format_description(description)) or "",
type_def,
],
)
)
def _encode_tools_typescript(tools: list[ToolSpec]) -> str:
"""Convert a list of ToolSpec dicts to TypeScript-style tool declaration string.
Mirrors the upstream encoder shipped with the K2.5/K2.6 tokenizer
(``tool_declaration_ts.encode_tools_to_typescript_style``): unwraps
OpenAI ``{"type":"function","function":{...}}`` and skips other
tool types.
"""
if not tools:
return ""
functions = []
for tool in tools:
# Support both shapes:
# * OpenAI envelope: {"type": "function", "function": {...}}
# * Flat ``ToolSpec`` (TypedDict in renderers.base): {name, description, parameters}
# ToolNamespaceConfig non-function entries (e.g. ``"_plugin"``) are
# skipped explicitly.
if tool.get("type") and tool.get("type") != "function":
continue
if isinstance(tool.get("function"), dict):
func_def_dict = tool["function"]
else:
func_def_dict = tool
if not func_def_dict:
continue
func_def = _function_to_typescript(func_def_dict)
if func_def:
functions.append(func_def)
if not functions:
return ""
functions_str = "\n".join(functions)
return "# Tools\n\n## functions\nnamespace functions {\n" + functions_str + "\n}\n"
# ---------------------------------------------------------------------------
# Kimi K2.5 response parsing (mirrors K2 format, same token structure)
# ---------------------------------------------------------------------------
_TOOL_CALLS_SECTION_RE = re.compile(
r"<\|tool_calls_section_begin\|>(.*?)<\|tool_calls_section_end\|>"
r"|<\|tool_call_section_begin\|>(.*?)<\|tool_call_section_end\|>",
re.DOTALL,
)
_TOOL_CALL_RE = re.compile(
r"<\|tool_call_begin\|>\s*([^<]+:\d+)\s*<\|tool_call_argument_begin\|>\s*(.*?)\s*<\|tool_call_end\|>",
re.DOTALL,
)
def _parse_kimi_k2_response(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
think_open_ids: list[int],
think_close_ids: list[int],
) -> 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|>``
"""
# Strip stop token
ids = list(token_ids)
for i, t in enumerate(ids):
if t in stop_ids:
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 ""
# 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.
reasoning: str | None = None
if "<think>" in text:
_, _, after_open = text.partition("<think>")
if "</think>" in after_open:
reasoning_raw, _, text = after_open.partition("</think>")
reasoning = reasoning_raw.strip("\n") or None
text = text.strip("\n")
else:
# Truncated reasoning (no closing tag)
return ParsedResponse(
content="",
reasoning_content=after_open.strip() or None,
tool_calls=None,
)
elif "</think>" in text:
# Sampler stripped the prefilled <think> open tag — see
# _normalize_response_tokens. Keep prior behaviour: everything
# before </think> is reasoning, everything after is content.
before, _, after = text.partition("</think>")
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,
tool_calls=tool_calls,
)
# ---------------------------------------------------------------------------
# KimiK25Renderer
# ---------------------------------------------------------------------------
class KimiK25Renderer:
"""Deterministic message → token renderer for Kimi K2.5 models.
Renders to the same ``<|im_*|>`` format as Kimi K2 but adds:
- Generation prompt prefills ``<think>`` (enable_thinking=True, default) or
``<think></think>`` (enable_thinking=False) to control thinking mode.
- Image content rendering via ``<|media_begin|>image<|media_content|>...<|media_end|>``.
- TypeScript-style tool declarations instead of JSON.
The tokenizer should be ``moonshotai/Kimi-K2-Instruct`` (same as K2).
"""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
# Core structural tokens — all must be single special tokens in the vocab
self._im_user = self._token_id("<|im_user|>")
self._im_assistant = self._token_id("<|im_assistant|>")
self._im_system = self._token_id("<|im_system|>")
self._im_middle = self._token_id("<|im_middle|>")
self._im_end = self._token_id("<|im_end|>")
# Tool call tokens
self._tool_calls_section_begin = self._token_id("<|tool_calls_section_begin|>")
self._tool_calls_section_end = self._token_id("<|tool_calls_section_end|>")
self._tool_call_begin = self._token_id("<|tool_call_begin|>")
self._tool_call_argument_begin = self._token_id("<|tool_call_argument_begin|>")
self._tool_call_end = self._token_id("<|tool_call_end|>")
# <think> / </think> may be multi-token in K2.5; we encode them as text.
# We cache the encoded IDs for use in _normalize_response_tokens.
self._think_open_ids: list[int] = self._encode("<think>")
self._think_close_ids: list[int] = self._encode("</think>")
# The stop token for generation
self._endoftext: int | None = self._try_token_id("<|endoftext|>")
# ------------------------------------------------------------------
# Token helpers
# ------------------------------------------------------------------
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 _try_token_id(self, token: str) -> int | None:
"""Return token ID or None if not in vocabulary (used for optional tokens)."""
tid = self._tokenizer.convert_tokens_to_ids(token)
if not isinstance(tid, int) or tid == self._tokenizer.unk_token_id:
return None
return tid
def _encode(self, text: str) -> list[int]:
if not text:
return []
return self._tokenizer.encode(text, add_special_tokens=False)
# ------------------------------------------------------------------
# Core render
# ------------------------------------------------------------------
def render(
self,
messages: list[Message],
*,
tools: list[ToolSpec] | None = None,
add_generation_prompt: bool = False,
) -> RenderedTokens:
"""Render messages to tokens, matching the K2.5 chat template.
Template structure (whitespace-stripped via Jinja ``{%- ... -%}``):
- Optional ``<|im_system|>tool_declare<|im_middle|>{tools}<|im_end|>``
- For each message: role tag + role_name + ``<|im_middle|>`` + body
+ ``<|im_end|>`` (no trailing newline)
- Assistant body splits hist vs suffix at the last
non-tool-call assistant index: hist gets ``<think></think>``,
suffix gets ``<think>{reasoning_content}</think>``
- Tool body: ``## Return of {tool_call_id}\n{content}``
- Generation prompt: ``<|im_assistant|>assistant<|im_middle|>``
+ ``<think>`` (or ``<think></think>`` when thinking off)
"""
if not messages:
raise ValueError("No messages provided.")
# Hist/suffix split — assistants up to and including the last
# non-tool-call assistant strip reasoning_content, those after
# preserve it (matches the template's hist_msgs vs suffix_msgs).
last_non_tc_assistant = -1
for k in range(len(messages) - 1, -1, -1):
m = messages[k]
if m.get("role") == "assistant" and not m.get("tool_calls"):
last_non_tc_assistant = k
break
tokens: list[int] = []
indices: list[int] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
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:
emit_ids(self._encode(text), msg_idx)
# ── Tool declaration prefix (comes first) ──
# K2.5/K2.6's tokenizer auto-computes ``tools_ts_str`` and threads
# it into apply_chat_template, so the template's TS branch always
# fires when tools are present. Match that with our own TS encoder.
if tools:
tools_ts = _encode_tools_typescript(tools)
emit_special(self._im_system, -1)
emit_text("tool_declare", -1)
emit_special(self._im_middle, -1)
emit_text(tools_ts, -1)
emit_special(self._im_end, -1)
# ── Iterate messages ─────────────────────────────────────────
for i, msg in enumerate(messages):
role = msg.get("role", "")
# set_roles: role tag + role_name + <|im_middle|>
if role == "user":
emit_special(self._im_user, i)
elif role == "assistant":
emit_special(self._im_assistant, i)
else:
emit_special(self._im_system, i)
role_name = msg.get("name") or role
emit_text(role_name, i)
emit_special(self._im_middle, i)
# Body
if role == "assistant":
is_suffix = i > last_non_tc_assistant
self._render_assistant_body(
msg,
i,
is_suffix=is_suffix,
emit_special=emit_special,
emit_text=emit_text,
)
elif role == "tool":
self._render_tool_body(
msg,
i,
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
)
elif msg.get("content") is not None:
self._emit_content(
msg.get("content"), i, emit_special, emit_text, emit_ids
)
emit_special(self._im_end, i)
# ── Generation prompt ────────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
if self._enable_thinking:
# Prefill open <think> tag to trigger thinking mode
emit_text("<think>", -1)
else:
# Empty <think></think> to disable thinking
emit_text("<think></think>", -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]) -> 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
normalized = self._normalize_response_tokens(list(token_ids))
return _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,
)
def get_stop_token_ids(self) -> list[int]:
stop = [self._im_end]
if self._endoftext is not None:
stop.append(self._endoftext)
return stop
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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
close_ids: set[int] = {self._im_end}
if self._endoftext is not None:
close_ids.add(self._endoftext)
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
close_ids,
synthesize_close=self._im_end,
)
if previous_ids is None:
return None
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))
def emit_ids(ids: list[int], _msg_idx: int = -1) -> None:
ext.extend(ids)
# Bridge handles user/system/tool only (reject_assistant_in_extension
# blocks assistants), so no hist/suffix split needed.
for i, msg in enumerate(new_messages):
role = msg.get("role")
if role == "user":
emit_special(self._im_user, i)
elif role in ("system", "tool"):
emit_special(self._im_system, i)
else:
return None
role_name = msg.get("name") or role
emit_text(role_name, i)
emit_special(self._im_middle, i)
if role == "tool":
self._render_tool_body(
msg,
i,
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
)
elif msg.get("content") is not None:
self._emit_content(
msg.get("content"), i, emit_special, emit_text, emit_ids
)
emit_special(self._im_end, i)
# Generation prompt.
emit_special(self._im_assistant, -1)
emit_text("assistant", -1)
emit_special(self._im_middle, -1)
if self._enable_thinking:
emit_text("<think>", -1)
else:
emit_text("<think></think>", -1)
return previous_ids + ext
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _emit_content(
self,
content: Any,
msg_idx: int,
emit_special,
emit_text,
emit_ids,
) -> None:
"""Emit message content, handling both plain strings and multipart lists."""
if content is None:
return
if isinstance(content, str):
emit_text(content, msg_idx)
return
if isinstance(content, list):
for part in content:
if not isinstance(part, dict):
continue
ptype = part.get("type")
if ptype == "text":
emit_text(part.get("text", ""), msg_idx)
elif ptype == "thinking":
# Thinking parts in non-assistant roles are rendered as text
thinking = part.get("thinking", "")
if thinking:
emit_text(f"<think>{thinking}</think>", msg_idx)
# Other part types are silently skipped
def _render_assistant_body(
self,
msg: Message,
msg_idx: int,
*,
is_suffix: bool,
emit_special,
emit_text,
) -> None:
"""Emit assistant body (after the role tag): ``<think>...</think>`` +
content + optional tool_calls section. No ``<|im_end|>``; caller emits
that.
``is_suffix`` mirrors the template's hist/suffix split — historical
assistants strip ``reasoning_content`` (template emits literal
``<think></think>``), suffix assistants preserve it.
"""
content = msg.get("content")
reasoning_content: str = ""
# Extract reasoning from structured content parts or inline <think> tags
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
if isinstance(content, list):
text_content = "".join(
p.get("text", "")
for p in content
if isinstance(p, dict) and p.get("type") == "text"
)
else:
text_content = content or ""
elif isinstance(content, list):
thinking_parts = [
p.get("thinking", "")
for p in content
if isinstance(p, dict) and p.get("type") == "thinking"
]
text_parts = [
p.get("text", "")
for p in content
if isinstance(p, dict) and p.get("type") == "text"
]
reasoning_content = "".join(thinking_parts)
text_content = "".join(text_parts)
elif isinstance(content, str) and "</think>" in content:
before, _, after = content.partition("</think>")
if "<think>" in before:
reasoning_content = before.split("<think>", 1)[-1]
else:
reasoning_content = before
text_content = after.lstrip("\n")
else:
text_content = content or ""
# Hist/suffix split: hist drops reasoning, suffix keeps it.
if is_suffix:
emit_text(f"<think>{reasoning_content}</think>", msg_idx)
else:
emit_text("<think></think>", msg_idx)
emit_text(text_content, msg_idx)
tool_calls = msg.get("tool_calls") or []
if tool_calls:
emit_special(self._tool_calls_section_begin, msg_idx)
for tc in tool_calls:
func = tc.get("function") or tc
arguments = func.get("arguments", {})
args_str = (
json.dumps(arguments, ensure_ascii=False)
if not isinstance(arguments, str)
else arguments
)
# Template emits ``tool_call['id']`` verbatim — empty when
# missing. Round-trip requires caller to pass id in
# ``functions.{name}:{idx}`` form (Kimi's parser recovers
# the function name from that field).
tool_id = tc.get("id") or ""
emit_special(self._tool_call_begin, msg_idx)
emit_text(tool_id, msg_idx)
emit_special(self._tool_call_argument_begin, msg_idx)
emit_text(args_str, msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._tool_calls_section_end, msg_idx)
def _render_tool_body(
self,
msg: Message,
msg_idx: int,
*,
emit_special,
emit_text,
emit_ids,
) -> None:
"""Emit tool-result body (after the role tag): ``## Return of {id}\\n``
+ content. No ``<|im_end|>``; caller emits that.
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.
"""
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)
def _normalize_response_tokens(self, response: list[int]) -> list[int]:
"""Restore the synthetic ``<think>`` prefill if the sampler stripped it.
When thinking is enabled the generation prompt ends with a ``<think>``
prefill. Some samplers strip the prefill from the returned token IDs.
If the response contains ``</think>`` (encoded tokens) but does NOT
start with ``<think>`` (encoded tokens), we prepend the ``<think>``
tokens so the downstream text-based parser sees a complete block.
"""
if not response:
return response
open_ids = self._think_open_ids
close_ids = self._think_close_ids
if not open_ids or not close_ids:
return response
# Check whether <think> appears anywhere in the response. Checking
# anywhere (not just the start) avoids false positives when the
# caller's slicing happens to include earlier scaffolding tokens
# (e.g. the assistant role tag) before the open tag.
contains_open = any(
response[j : j + len(open_ids)] == open_ids
for j in range(len(response) - len(open_ids) + 1)
)
# Check whether </think> appears anywhere in the response
contains_close = any(
response[j : j + len(close_ids)] == close_ids
for j in range(len(response) - len(close_ids) + 1)
)
if not contains_open and contains_close:
return open_ids + response
return response
+398
View File
@@ -0,0 +1,398 @@
"""MiniMax M2.5 Renderer — hard-coded Python mirroring the MiniMax M2.5 Jinja chat template.
Unique characteristics:
- Token format: ]~!b[ (BOS), ]~b] (role prefix), [e~[ (EOS)
- Role "assistant" rendered as "ai"
- Default system message injected if none provided
- Tool calls use <minimax:tool_call>/<invoke>/<parameter> XML format
- Tool responses wrapped in <response> tags (regular text, not special tokens)
- Thinking only for assistant messages after last user turn
"""
from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.parsing import parse_minimax
_DEFAULT_SYSTEM = (
"You are a helpful assistant. Your name is MiniMax-M2.5 and is built by MiniMax."
)
_TOOLS_HEADER = (
"\n\n# Tools\n"
"You may call one or more tools to assist with the user query.\n"
"Here are the tools available in JSONSchema format:\n"
"\n<tools>\n"
)
_TOOLS_FOOTER_PREFIX = "</tools>\n\n"
_TOOLS_INSTRUCTIONS = (
"When making tool calls, use XML format to invoke tools and pass parameters:\n"
"\n<minimax:tool_call>\n"
'<invoke name="tool-name-1">\n'
'<parameter name="param-key-1">param-value-1</parameter>\n'
'<parameter name="param-key-2">param-value-2</parameter>\n'
"...\n"
"</invoke>\n"
"</minimax:tool_call>"
)
class MiniMaxM2Renderer:
"""Deterministic message → token renderer for MiniMax M2 / M2.5 models."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
default_system: str = _DEFAULT_SYSTEM,
):
self._tokenizer = tokenizer
self._default_system = default_system
self._bos = self._token_id("]~!b[")
self._role = self._token_id("]~b]")
self._eos = self._token_id("[e~[")
self._think = self._token_id("<think>")
self._think_end = self._token_id("</think>")
self._tool_call_tok = self._token_id("<minimax:tool_call>")
self._tool_call_end_tok = self._token_id("</minimax: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: Any) -> str:
if content is None:
return "None"
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict) and item.get("type") == "text":
parts.append(item.get("text", ""))
return "".join(parts)
return str(content)
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))
# ── Extract system message ──────────────────────────────────
first_is_system = messages[0].get("role") == "system"
sys_idx = 0 if first_is_system else -1
conversation: list[Message] = messages[1:] if first_is_system else messages
# ── System block (always present) ───────────────────────────
emit_special(self._bos, sys_idx)
emit_special(self._role, sys_idx)
sys_content = (
self._visible_text(messages[0].get("content")) if first_is_system else ""
)
system_text = "system\n" + (sys_content or self._default_system)
if tools:
system_text += _TOOLS_HEADER
for tool in tools:
func = tool.get("function", tool)
system_text += (
"<tool>" + json.dumps(func, ensure_ascii=False) + "</tool>\n"
)
system_text += _TOOLS_FOOTER_PREFIX
system_text += _TOOLS_INSTRUCTIONS
emit_text(system_text, sys_idx)
emit_special(self._eos, sys_idx)
emit_text("\n", sys_idx)
# ── Compute last_user_index (relative to conversation) ──────
last_ui = -1
for ci, msg in enumerate(conversation):
if msg.get("role") == "user":
last_ui = ci
# ── Iterate conversation messages ───────────────────────────
for ci, msg in enumerate(conversation):
role = msg["role"]
# Map back to original message index for attribution
orig_idx = ci + (1 if first_is_system else 0)
if role == "user":
emit_special(self._role, orig_idx)
emit_text("user\n" + self._visible_text(msg.get("content")), orig_idx)
emit_special(self._eos, orig_idx)
emit_text("\n", orig_idx)
elif role == "assistant":
self._render_assistant(
msg,
orig_idx,
ci,
last_ui,
emit_special=emit_special,
emit_text=emit_text,
)
elif role == "tool":
self._render_tool(
conversation,
ci,
orig_idx,
msg,
emit_special=emit_special,
emit_text=emit_text,
)
# ── Generation prompt ───────────────────────────────────────
if add_generation_prompt:
emit_special(self._role, -1)
emit_text("ai\n", -1)
emit_special(self._think, -1)
emit_text("\n", -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]) -> ParsedResponse:
return parse_minimax(
self._tokenizer,
token_ids,
stop_ids={self._eos},
think_id=self._think,
think_end_id=self._think_end,
tool_call_id=self._tool_call_tok,
tool_call_end_id=self._tool_call_end_tok,
)
def get_stop_token_ids(self) -> list[int]:
return [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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._eos},
synthesize_close=self._eos,
)
if previous_ids is None:
return None
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))
# Trailing ``\n`` after the ``[e~[`` turn close — see ``render()``.
emit_text("\n", -1)
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._visible_text(msg.get("content"))
if role == "user":
emit_special(self._role, i)
emit_text("user\n" + content, i)
emit_special(self._eos, i)
emit_text("\n", i)
elif role == "system":
emit_special(self._role, i)
emit_text("system\n" + content, i)
emit_special(self._eos, i)
emit_text("\n", i)
elif role == "tool":
self._render_tool(
new_messages,
i,
i,
msg,
emit_special=emit_special,
emit_text=emit_text,
)
else:
return None
# Generation prompt.
emit_special(self._role, -1)
emit_text("ai\n", -1)
emit_special(self._think, -1)
emit_text("\n", -1)
return previous_ids + ext
def _render_assistant(
self, msg, orig_idx, conv_idx, last_user_index, *, emit_special, emit_text
):
content = self._visible_text(msg.get("content"))
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
elif "</think>" in content:
before, after = content.split("</think>", 1)
if "<think>" in before:
reasoning_content = before.split("<think>")[-1].strip("\n")
else:
reasoning_content = before.strip("\n")
content = after.strip("\n")
emit_special(self._role, orig_idx)
# Build the full text between ]~b]ai and [e~[ with special tokens
# interspersed. Keep text segments contiguous to preserve BPE merges.
tool_calls = msg.get("tool_calls") or []
if reasoning_content and conv_idx > last_user_index:
emit_text("ai\n", orig_idx)
emit_special(self._think, orig_idx)
emit_text("\n" + reasoning_content + "\n", orig_idx)
emit_special(self._think_end, orig_idx)
# \n\n + content must be contiguous for BPE
after_think = "\n\n" + content if content else "\n\n"
else:
after_think = "ai\n" + content if content else "ai\n"
if tool_calls:
# \n before <minimax:tool_call> must be contiguous with preceding text
emit_text(after_think + "\n", orig_idx)
emit_special(self._tool_call_tok, orig_idx)
invoke_block = "\n"
for tc in tool_calls:
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
invoke_block += '<invoke name="' + name + '">\n'
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
val_str = (
arg_value
if isinstance(arg_value, str)
else json.dumps(arg_value, ensure_ascii=False)
)
invoke_block += (
'<parameter name="'
+ arg_name
+ '">'
+ val_str
+ "</parameter>\n"
)
invoke_block += "</invoke>\n"
emit_text(invoke_block, orig_idx)
emit_special(self._tool_call_end_tok, orig_idx)
else:
emit_text(after_think, orig_idx)
emit_special(self._eos, orig_idx)
emit_text("\n", orig_idx)
def _render_tool(
self,
conversation: list[Message],
conv_idx: int,
orig_idx: int,
msg: Message,
*,
emit_special,
emit_text,
) -> None:
prev_is_tool = conv_idx > 0 and conversation[conv_idx - 1]["role"] == "tool"
next_is_tool = (
conv_idx + 1 < len(conversation)
and conversation[conv_idx + 1]["role"] == "tool"
)
if not prev_is_tool:
emit_special(self._role, orig_idx)
emit_text("tool", orig_idx)
content = self._visible_text(msg.get("content"))
# Leading ``\n`` before ``<response>`` only on the first of a
# consecutive run — subsequent ones piggyback on the trailing ``\n``
# emitted below, so BPE can merge ``</response>\n<response>``
# through a single emit_text call instead of splitting the merge.
prefix = "" if prev_is_tool else "\n"
suffix = "\n" if next_is_tool else ""
emit_text(prefix + "<response>" + content + "</response>" + suffix, orig_idx)
if not next_is_tool:
emit_special(self._eos, orig_idx)
emit_text("\n", orig_idx)
+608
View File
@@ -0,0 +1,608 @@
"""Nemotron 3 Renderer — hard-coded Python that mirrors the Nemotron 3 chat template.
Nemotron 3 uses the same <|im_start|>/<|im_end|> format as Qwen3.5 but differs in:
1. Tool declarations: XML format inside <tools>...</tools> (not JSON-per-line).
2. System message ordering: system prompt goes BEFORE tools block.
3. Thinking block scope: <think></think> is prepended to ALL assistant messages
that lack thinking content (not just those after the last user query).
4. Think separator: single \\n after </think> (not \\n\\n like Qwen3.5).
5. Empty system message: always prepends an empty system message if none exists.
6. Disable-thinking generation suffix: <think></think> with no trailing newlines.
7. Tool response format: trailing newline after </tool_response>.
"""
from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.parsing import parse_qwen35
# ---------------------------------------------------------------------------
# Tool system prompt constants
# ---------------------------------------------------------------------------
_TOOLS_HEADER = "# Tools\n\nYou have access to the following functions:\n\n<tools>"
_TOOLS_FOOTER = "\n</tools>"
_TOOLS_INSTRUCTIONS = (
"\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:"
"\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1"
"\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter"
"\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>"
"\n\n<IMPORTANT>\nReminder:"
"\n- Function calls MUST follow the specified format:"
" an inner <function=...></function> block must be nested within"
" <tool_call></tool_call> XML tags"
"\n- Required parameters MUST be specified"
"\n- You may provide optional reasoning for your function call"
" in natural language BEFORE the function call, but NOT after"
"\n- If there is no function call available, answer the question like normal"
" with your current knowledge and do not tell the user about function calls"
"\n</IMPORTANT>"
)
def _render_extra_keys(obj: dict[str, Any], handled_keys: set[str]) -> list[str]:
"""Render extra dict keys as XML, mirroring the HF template's render_extra_keys macro.
Dicts and lists are JSON-encoded; scalars are string-coerced.
"""
lines: list[str] = []
for key, value in obj.items():
if key in handled_keys:
continue
if isinstance(value, (dict, list)):
lines.append(f"<{key}>{json.dumps(value)}</{key}>")
else:
lines.append(f"<{key}>{value!s}</{key}>")
return lines
class Nemotron3Renderer:
"""Deterministic message → token renderer for Nemotron 3 models."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
# Look up special token IDs from the tokenizer (not hardcoded).
# <|endoftext|> is optional: Nemotron-3 Nano / Super tokenizers ship
# <|im_end|> as the sole EOS; older / larger variants additionally
# include <|endoftext|>. Both work with the same chat template.
self._im_start = self._token_id("<|im_start|>")
self._im_end = self._token_id("<|im_end|>")
self._endoftext = self._token_id("<|endoftext|>", optional=True)
self._think = self._token_id("<think>")
self._think_end = self._token_id("</think>")
self._tool_call = self._token_id("<tool_call>")
self._tool_call_end = self._token_id("</tool_call>")
self._tool_response = self._token_id("<tool_response>")
self._tool_response_end = self._token_id("</tool_response>")
def _token_id(self, token: str, *, optional: bool = False) -> int | None:
tid = self._tokenizer.convert_tokens_to_ids(token)
if not isinstance(tid, int) or tid == self._tokenizer.unk_token_id:
if optional:
return None
raise AssertionError(
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)
# ------------------------------------------------------------------
# Content rendering
# ------------------------------------------------------------------
@staticmethod
def _render_content(content: Any) -> str:
"""Render message content to a text string (before tokenization)."""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
if "text" in item:
parts.append(item["text"])
else:
raise ValueError(f"Unexpected content item: {item}")
return "".join(parts)
raise TypeError(f"Unexpected content type: {type(content)}")
# ------------------------------------------------------------------
# Tool declaration formatting (XML, Nemotron 3 style)
# ------------------------------------------------------------------
@staticmethod
def _format_tool_declaration(tool: ToolSpec) -> str:
"""Format a single tool declaration in Nemotron 3 XML format."""
# Accept the OpenAI-style ``{"type":"function","function":{...}}``
# envelope by unwrapping before formatting.
if "function" in tool and isinstance(tool["function"], dict):
tool = tool["function"]
lines = [
"<function>",
f"<name>{tool['name']}</name>",
]
description = tool.get("description", "").strip()
if description:
lines.append(f"<description>{description}</description>")
lines.append("<parameters>")
params = tool.get("parameters") or {}
if isinstance(params, dict) and "properties" in params:
for param_name, param_fields in params["properties"].items():
lines.append("<parameter>")
lines.append(f"<name>{param_name}</name>")
if "type" in param_fields:
lines.append(f"<type>{param_fields['type']!s}</type>")
if "description" in param_fields:
lines.append(
f"<description>{param_fields['description'].strip()}</description>"
)
if "enum" in param_fields:
lines.append(f"<enum>{json.dumps(param_fields['enum'])}</enum>")
lines.extend(
_render_extra_keys(
param_fields, {"name", "type", "description", "enum"}
)
)
lines.append("</parameter>")
if isinstance(params, dict):
lines.extend(_render_extra_keys(params, {"type", "properties", "required"}))
if isinstance(params, dict) and "required" in params:
lines.append(f"<required>{json.dumps(params['required'])}</required>")
lines.append("</parameters>")
lines.extend(
_render_extra_keys(tool, {"type", "name", "description", "parameters"})
)
lines.append("</function>")
return "\n".join(lines)
# ------------------------------------------------------------------
# Message normalization
# ------------------------------------------------------------------
def _normalize_messages(
self, messages: list[Message]
) -> tuple[list[Message], bool]:
"""Prepend empty system message if none exists.
Nemotron 3's HF template always outputs a system message block even
when none is provided. Returns ``(messages, auto_injected)`` so the
caller can emit the injected system's tokens with ``msg_idx=-1``
(keeping message_indices aligned with the caller's input list —
``build_training_sample`` relies on this).
"""
if not messages or messages[0].get("role") != "system":
return [{"role": "system", "content": ""}] + list(messages), True
return list(messages), False
# ------------------------------------------------------------------
# Core render method
# ------------------------------------------------------------------
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.")
# Always ensure an empty system message is present.
messages, auto_system_injected = self._normalize_messages(messages)
# Offset to map indices in the normalized list back to the caller's
# original message list. The injected system itself uses msg_idx=-1
# (sentinel) so build_training_sample can't dereference it.
idx_offset = -1 if auto_system_injected else 0
def orig_idx(i: int) -> int:
if auto_system_injected and i == 0:
return -1
return i + idx_offset
tokens: list[int] = []
indices: list[int] = []
def emit_ids(ids: list[int], msg_idx: int) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
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:
emit_ids(self._encode(text), msg_idx)
# ── 1. System message + optional tools ──────────────────────
first_is_system = messages[0].get("role") == "system"
if tools:
# Nemotron 3: system prompt BEFORE tools block
sys_idx = orig_idx(0) if first_is_system else -1
emit_special(self._im_start, sys_idx)
emit_text("system\n", sys_idx)
# Build system content: user's system text first, then tools
if first_is_system:
sys_content = self._render_content(messages[0].get("content")).strip()
else:
sys_content = ""
tool_declarations = "\n".join(
self._format_tool_declaration(t) for t in tools
)
tools_block = (
_TOOLS_HEADER
+ "\n"
+ tool_declarations
+ _TOOLS_FOOTER
+ _TOOLS_INSTRUCTIONS
)
if sys_content:
full_sys = sys_content + "\n\n" + tools_block
else:
full_sys = tools_block
emit_text(full_sys, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
elif first_is_system:
sys_idx = orig_idx(0)
sys_content = self._render_content(messages[0].get("content")).strip()
emit_special(self._im_start, sys_idx)
emit_text("system\n" + sys_content, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
# Track the most-recent plain (non-tool-call) assistant so we can
# preserve its reasoning while stripping reasoning from earlier
# assistants — the Nemotron-3 template matches this pattern.
last_plain_assistant_idx = -1
for j in range(len(messages) - 1, -1, -1):
if messages[j].get("role") == "assistant" and not messages[j].get(
"tool_calls"
):
last_plain_assistant_idx = j
break
# ── 2. Iterate messages ─────────────────────────────────────
for i, msg in enumerate(messages):
role = msg["role"]
content = self._render_content(msg.get("content")).strip()
msg_orig_idx = orig_idx(i)
if role == "system":
if i != 0:
raise ValueError("System message must be at the beginning.")
continue # Already handled above
elif role == "user":
emit_special(self._im_start, msg_orig_idx)
emit_text("user\n" + content, msg_orig_idx)
emit_special(self._im_end, msg_orig_idx)
emit_text("\n", msg_orig_idx)
elif role == "assistant":
is_last_turn = i >= last_plain_assistant_idx
self._render_assistant(
msg,
msg_orig_idx,
content,
is_last_turn=is_last_turn,
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
)
elif role == "tool":
self._render_tool(
messages,
i,
content,
msg_orig_idx=msg_orig_idx,
auto_system_injected=auto_system_injected,
emit_special=emit_special,
emit_text=emit_text,
)
else:
raise ValueError(f"Unexpected message role: {role}")
# ── 3. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
if self._enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
else:
# Disable-thinking suffix: <think></think> with no trailing newlines
emit_special(self._think, -1)
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]) -> ParsedResponse:
stop_ids = {self._im_end}
if self._endoftext is not None:
stop_ids.add(self._endoftext)
return parse_qwen35(
self._tokenizer,
token_ids,
stop_ids=stop_ids,
think_id=self._think,
think_end_id=self._think_end,
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
)
def get_stop_token_ids(self) -> list[int]:
stop = [self._im_end]
if self._endoftext is not None:
stop.append(self._endoftext)
return stop
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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
close_ids: set[int] = {self._im_end}
if self._endoftext is not None:
close_ids.add(self._endoftext)
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
close_ids,
synthesize_close=self._im_end,
)
if previous_ids is None:
return None
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))
emit_text("\n", -1)
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._render_content(msg.get("content")).strip()
if role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "system":
emit_special(self._im_start, i)
emit_text("system\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "tool":
self._render_tool(
new_messages,
i,
content,
msg_orig_idx=i,
auto_system_injected=False,
emit_special=emit_special,
emit_text=emit_text,
)
else:
return None
# Generation prompt.
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
if self._enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
else:
emit_special(self._think, -1)
emit_special(self._think_end, -1)
return previous_ids + ext
# ------------------------------------------------------------------
# Assistant message rendering
# ------------------------------------------------------------------
def _render_assistant(
self,
msg: Message,
msg_idx: int,
content: str,
*,
is_last_turn: bool,
emit_special,
emit_text,
emit_ids,
) -> None:
# Extract reasoning_content
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
elif "</think>" in content:
before_think_end, after_think_end = content.split("</think>", 1)
if "<think>" in before_think_end:
reasoning_content = before_think_end.split("<think>")[-1].lstrip("\n")
else:
reasoning_content = before_think_end.lstrip("\n")
reasoning_content = reasoning_content.rstrip("\n")
content = after_think_end.lstrip("\n")
reasoning_content = reasoning_content.strip()
emit_special(self._im_start, msg_idx)
emit_text("assistant\n", msg_idx)
# Nemotron 3 keeps reasoning on the most-recent plain assistant but
# strips it from historical turns, which collapse to an empty
# <think></think> block. Empty <think></think> is also emitted when
# the turn has no reasoning at all. The trailing ``\n`` (when
# tool_calls follow) is glued to ``content`` in a single emit_text
# so BPE sees ``content\n`` as one chunk, matching how
# apply_chat_template tokenises the concatenated template string.
tool_calls = msg.get("tool_calls") or []
# A \n is always required between the text/think block and the first
# <tool_call>, whether the content is empty or not.
content_suffix = "\n" if tool_calls else ""
if reasoning_content and is_last_turn:
emit_special(self._think, msg_idx)
emit_text("\n" + reasoning_content + "\n", msg_idx)
emit_special(self._think_end, msg_idx)
# Single \n separator (not \n\n like Qwen3.5)
emit_text("\n" + content + content_suffix, msg_idx)
elif reasoning_content:
# Historical assistant whose reasoning got stripped — template
# keeps a single \n between the collapsed <think></think> and
# the content as a marker that reasoning existed.
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
emit_text("\n" + content + content_suffix, msg_idx)
else:
# No reasoning ever — <think></think> glued directly to content.
emit_special(self._think, msg_idx)
emit_special(self._think_end, msg_idx)
emit_text(content + content_suffix, msg_idx)
# Tool calls (leading \n was glued to the content above; each
# iteration's trailing \n after </tool_call> handles the
# separator to the next block).
if tool_calls:
for tc_idx, tc in enumerate(tool_calls):
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
emit_special(self._tool_call, msg_idx)
emit_text("\n<function=" + name + ">\n", msg_idx)
# Render arguments
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
if isinstance(arg_value, (dict, list)):
value_str = json.dumps(arg_value, ensure_ascii=False)
else:
value_str = str(arg_value)
emit_text(
"<parameter="
+ arg_name
+ ">\n"
+ value_str
+ "\n</parameter>\n",
msg_idx,
)
emit_text("</function>\n", msg_idx)
emit_special(self._tool_call_end, msg_idx)
# Trailing \n after </tool_call> (Nemotron 3 specific)
emit_text("\n", msg_idx)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# ------------------------------------------------------------------
# Tool message rendering
# ------------------------------------------------------------------
def _render_tool(
self,
messages: list[Message],
msg_idx: int,
content: str,
*,
msg_orig_idx: int,
auto_system_injected: bool,
emit_special,
emit_text,
) -> None:
# Consecutive tool messages are grouped under a single <|im_start|>user block
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"
)
oi = msg_orig_idx
if not prev_is_tool:
emit_special(self._im_start, oi)
emit_text("user\n", oi)
# else: the previous tool's trailing \n already provides the
# separator into this block.
emit_special(self._tool_response, oi)
emit_text("\n" + content + "\n", oi)
emit_special(self._tool_response_end, oi)
# Nemotron 3: trailing \n after </tool_response>
emit_text("\n", oi)
if not next_is_tool:
emit_special(self._im_end, oi)
emit_text("\n", oi)
+369
View File
@@ -0,0 +1,369 @@
"""Pluggable tool-call and reasoning parsers.
Each parser knows how to pull a specific kind of structured output out of a
completion. They're registered by name so callers can compose a
DefaultRenderer with their own tool / reasoning parsing logic without having
to author a whole Renderer.
ToolParser operates on token ids (most tool formats use special tokens as
delimiters, so matching by id is more reliable than regex on decoded text).
ReasoningParser operates on decoded text (reasoning delimiters are typically
``<think>...</think>`` and the text-vs-token distinction here rarely matters
for the final extraction).
"""
from __future__ import annotations
import json
import re
from typing import Protocol, runtime_checkable
# ── Shared helpers ───────────────────────────────────────────────────
def _find(ids: list[int], target: int, start: int = 0) -> int:
for i in range(start, len(ids)):
if ids[i] == target:
return i
return -1
def _decode(tokenizer, ids: list[int]) -> str:
if not ids:
return ""
return tokenizer.decode(ids, skip_special_tokens=False)
def _token_id(tokenizer, token: str) -> int | None:
"""Return the id for *token* if present in the vocab, else None."""
tid = tokenizer.convert_tokens_to_ids(token)
# HF returns either the unk id or None for missing tokens. Treat the unk id
# as missing here so we don't accidentally collide on it.
unk = getattr(tokenizer, "unk_token_id", None)
if tid is None or tid == unk:
return None
return tid
# ── Protocols ────────────────────────────────────────────────────────
@runtime_checkable
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.
"""
def __init__(self, tokenizer): ...
def extract(self, token_ids: list[int]) -> tuple[list[int], list[dict] | None]: ...
@runtime_checkable
class ReasoningParser(Protocol):
"""Splits reasoning content from final content.
``extract`` returns ``(reasoning_text_or_None, remaining_text)``.
"""
def __init__(self, tokenizer): ...
def extract(self, text: str) -> tuple[str | None, str]: ...
# ── Tool parsers ─────────────────────────────────────────────────────
class Qwen3ToolParser:
"""Hermes-style JSON tool calls: ``<tool_call>{"name": .., "arguments": ..}</tool_call>``."""
def __init__(self, tokenizer):
self._tokenizer = tokenizer
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]:
if self._tc_id is None:
return ids, None
tc_start = _find(ids, self._tc_id)
if tc_start == -1:
return ids, None
content_ids = ids[:tc_start]
tool_calls: list[dict] = []
i = tc_start
while i < len(ids):
if ids[i] == self._tc_id:
end = (
_find(ids, self._tc_end_id, i + 1)
if self._tc_end_id is not None
else -1
)
if end == -1:
end = len(ids)
tc_text = _decode(self._tokenizer, ids[i + 1 : end]).strip()
try:
parsed = json.loads(tc_text)
tool_calls.append(
{
"function": {
"name": parsed.get("name", ""),
"arguments": parsed.get("arguments", {}),
}
}
)
except json.JSONDecodeError:
pass
i = end + 1
else:
i += 1
return content_ids, (tool_calls or None)
class Qwen35ToolParser:
"""XML-style tool calls: ``<tool_call><function=N><parameter=K>V</parameter>...</function></tool_call>``."""
def __init__(self, tokenizer):
self._tokenizer = tokenizer
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]:
if self._tc_id is None:
return ids, None
tc_start = _find(ids, self._tc_id)
if tc_start == -1:
return ids, None
tool_calls: list[dict] = []
i = tc_start
while i < len(ids):
if ids[i] == self._tc_id:
end = (
_find(ids, self._tc_end_id, i + 1)
if self._tc_end_id is not None
else -1
)
if end == -1:
break
block_text = _decode(self._tokenizer, ids[i + 1 : end])
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
tool_calls.append(
{"function": {"name": name, "arguments": arguments}}
)
i = end + 1
else:
i += 1
return ids[:tc_start], (tool_calls or None)
class GlmToolParser:
"""GLM-5/4.5 token-level tool calls with ``<arg_key>``/``<arg_value>`` pairs."""
def __init__(self, tokenizer):
self._tokenizer = tokenizer
self._tc_id = _token_id(tokenizer, "<tool_call>")
self._tc_end_id = _token_id(tokenizer, "</tool_call>")
self._ak_id = _token_id(tokenizer, "<arg_key>")
self._ake_id = _token_id(tokenizer, "</arg_key>")
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]:
if self._tc_id is None:
return ids, None
tc_start = _find(ids, self._tc_id)
if tc_start == -1:
return ids, None
tool_calls: list[dict] = []
i = tc_start
while i < len(ids):
if ids[i] == self._tc_id:
end = (
_find(ids, self._tc_end_id, i + 1)
if self._tc_end_id is not None
else -1
)
if end == -1:
break
block = ids[i + 1 : end]
first_ak = _find(block, self._ak_id) if self._ak_id is not None else -1
if first_ak == -1:
name = _decode(self._tokenizer, block).strip()
arguments: dict = {}
else:
name = _decode(self._tokenizer, block[:first_ak]).strip()
arguments = {}
j = first_ak
while j < len(block):
if block[j] == self._ak_id:
ake = (
_find(block, self._ake_id, j + 1)
if self._ake_id is not None
else -1
)
if ake == -1:
break
key = _decode(self._tokenizer, block[j + 1 : ake]).strip()
av = (
_find(block, self._av_id, ake + 1)
if self._av_id is not None
else -1
)
if av == -1:
break
ave = (
_find(block, self._ave_id, av + 1)
if self._ave_id is not None
else -1
)
if ave == -1:
break
val_text = _decode(
self._tokenizer, block[av + 1 : ave]
).strip()
try:
arguments[key] = json.loads(val_text)
except (json.JSONDecodeError, ValueError):
arguments[key] = val_text
j = ave + 1
else:
j += 1
tool_calls.append({"function": {"name": name, "arguments": arguments}})
i = end + 1
else:
i += 1
return ids[:tc_start], (tool_calls or None)
class DeepSeekV3ToolParser:
"""DeepSeek V3 tool calls, delimited by ``<|tool▁calls▁begin|> ... <|tool▁calls▁end|>``."""
def __init__(self, tokenizer):
self._tokenizer = tokenizer
self._tcs_begin = _token_id(tokenizer, "<|tool▁calls▁begin|>")
self._tcs_end = _token_id(tokenizer, "<|tool▁calls▁end|>")
self._tc_begin = _token_id(tokenizer, "<|tool▁call▁begin|>")
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]:
if self._tcs_begin is None:
return ids, None
section_start = _find(ids, self._tcs_begin)
if section_start == -1:
return ids, None
content_ids = ids[:section_start]
section_end = (
_find(ids, self._tcs_end, section_start + 1)
if self._tcs_end is not None
else -1
)
if section_end == -1:
section_end = len(ids)
section_ids = ids[section_start + 1 : section_end]
tool_calls: list[dict] = []
i = 0
while i < len(section_ids):
if self._tc_begin is None or section_ids[i] != self._tc_begin:
i += 1
continue
end = (
_find(section_ids, self._tc_end, i + 1)
if self._tc_end is not None
else -1
)
if end == -1:
end = len(section_ids)
block_text = _decode(self._tokenizer, section_ids[i + 1 : end])
# 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 = {}
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}})
i = end + 1
return content_ids, (tool_calls or None)
# ── Reasoning parsers ────────────────────────────────────────────────
class ThinkTextReasoningParser:
"""Extracts ``<think>...</think>`` from decoded text.
Works regardless of whether ``<think>`` is a special token or plain text —
we decode with ``skip_special_tokens=False`` so both render identically.
"""
def __init__(self, tokenizer):
self._tokenizer = tokenizer # unused, for Protocol compat
def extract(self, text: str) -> tuple[str | None, str]:
if "</think>" not in text:
return None, text
before, _, after = text.partition("</think>")
if "<think>" in before:
reasoning = before.split("<think>", 1)[-1]
else:
reasoning = before
# Preserve whitespace on both sides of the `</think>` boundary —
# chat templates round-trip it verbatim (GLM-4.5 emits reasoning and
# content back-to-back with no separator), so stripping here causes
# re-render drift that breaks the trajectory-step extension property.
return (reasoning or None), after
# ── Registries ───────────────────────────────────────────────────────
TOOL_PARSERS: dict[str, type] = {
"qwen3": Qwen3ToolParser,
"qwen3.5": Qwen35ToolParser,
"glm": GlmToolParser,
"deepseek_v3": DeepSeekV3ToolParser,
}
REASONING_PARSERS: dict[str, type] = {
"think": ThinkTextReasoningParser,
}
def get_tool_parser(name: str, tokenizer) -> ToolParser:
"""Look up a tool parser by name and instantiate it with *tokenizer*."""
if name not in TOOL_PARSERS:
available = ", ".join(sorted(TOOL_PARSERS))
raise ValueError(f"Unknown tool_parser {name!r}. Available: {available}.")
return TOOL_PARSERS[name](tokenizer)
def get_reasoning_parser(name: str, tokenizer) -> ReasoningParser:
"""Look up a reasoning parser by name and instantiate it with *tokenizer*."""
if name not in REASONING_PARSERS:
available = ", ".join(sorted(REASONING_PARSERS))
raise ValueError(f"Unknown reasoning_parser {name!r}. Available: {available}.")
return REASONING_PARSERS[name](tokenizer)
+784
View File
@@ -0,0 +1,784 @@
"""Token-level parsing — operates on token IDs directly.
Finds special token boundaries by scanning token IDs, then decodes only
the text segments between them. No regex on decoded text, no false positives
from content that happens to look like special tokens.
"""
from __future__ import annotations
import json
from renderers.base import ParsedResponse
def _find(ids: list[int], target: int, start: int = 0) -> int:
"""Find index of target in ids, or -1."""
for i in range(start, len(ids)):
if ids[i] == target:
return i
return -1
def _find_all(ids: list[int], target: int) -> list[int]:
"""Find all indices of target in ids."""
return [i for i, t in enumerate(ids) if t == target]
def _strip_stop_tokens(ids: list[int], stop_ids: set[int]) -> list[int]:
"""Truncate at first stop token (model shouldn't generate past it)."""
for i, t in enumerate(ids):
if t in stop_ids:
return ids[:i]
return ids
def _decode(tokenizer, ids: list[int]) -> str:
"""Decode token IDs to text, skipping special tokens."""
if not ids:
return ""
return tokenizer.decode(ids, skip_special_tokens=False)
# ── Qwen3: <tool_call> JSON </tool_call> ────────────────────────────
def parse_qwen3(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
tool_call_id: int,
tool_call_end_id: int,
) -> ParsedResponse:
"""Parse Qwen3 completion tokens. Hermes-style JSON tool calls."""
ids = _strip_stop_tokens(token_ids, stop_ids)
# No thinking tokens in Qwen3 gen prompt — model may or may not think
# Parse from decoded text since <think>/<tool_call> may be multi-token in Qwen3
# Actually in Qwen3, <tool_call> IS a special token (151657)
# So we can find it by token ID
# Find tool calls by token ID
tc_start = _find(ids, tool_call_id)
if tc_start != -1:
content_ids = ids[:tc_start]
# Extract all tool call blocks
tool_calls = []
i = tc_start
while i < len(ids):
if ids[i] == tool_call_id:
end = _find(ids, tool_call_end_id, i + 1)
if end == -1:
end = len(ids)
tc_text = _decode(tokenizer, ids[i + 1 : end]).strip()
try:
parsed = json.loads(tc_text)
tool_calls.append(
{
"function": {
"name": parsed.get("name", ""),
"arguments": parsed.get("arguments", {}),
}
}
)
except json.JSONDecodeError:
pass
i = end + 1
else:
i += 1
# Match vLLM hermes_tool_parser: when no tool calls parse successfully,
# preserve the raw tokens as content instead of returning an empty
# response. vLLM/hermes_tool_parser.py::extract_tool_calls catches
# json.JSONDecodeError and falls through with content=model_output.
# Without this, clients raise EmptyModelResponseError on any
# <tool_call>...</tool_call> block with malformed JSON, which
# wastes inference compute on retries and diverges from main's
# behavior on hermes tool envs.
if not tool_calls:
content_ids = ids
else:
content_ids = ids
tool_calls = None
text = _decode(tokenizer, content_ids)
# Extract reasoning from text (Qwen3 doesn't have <think> as special token)
reasoning = None
if "</think>" in text:
before, _, after = text.partition("</think>")
reasoning = before.replace("<think>", "").strip("\n").strip()
text = after.strip("\n")
return ParsedResponse(
content=text.strip(),
reasoning_content=reasoning or None,
tool_calls=tool_calls or None,
)
# ── Qwen3.5: <tool_call> <function=name> <parameter=name> v </parameter> </function> </tool_call>
def parse_qwen35(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
think_id: int,
think_end_id: int,
tool_call_id: int,
tool_call_end_id: int,
) -> ParsedResponse:
"""Parse Qwen3.5 completion tokens. XML-style tool calls, token-level thinking."""
ids = _strip_stop_tokens(token_ids, stop_ids)
# Thinking: find </think> by token ID
reasoning = None
think_end = _find(ids, think_end_id)
if think_end != -1:
# Everything before </think> is reasoning
reasoning_ids = ids[:think_end]
# Strip <think> if present at start
reasoning_ids = [t for t in reasoning_ids if t != think_id]
reasoning = _decode(tokenizer, reasoning_ids).strip()
ids = ids[think_end + 1 :]
elif think_id in set(ids):
# <think> present but no </think> — truncated reasoning
think_start = _find(ids, think_id)
reasoning = _decode(tokenizer, ids[think_start + 1 :]).strip()
return ParsedResponse(
content="", reasoning_content=reasoning or None, tool_calls=None
)
# Tool calls by token ID
tc_start = _find(ids, tool_call_id)
if tc_start != -1:
content_text = _decode(tokenizer, ids[:tc_start]).strip()
tool_calls = _parse_xml_tool_calls(
tokenizer, ids[tc_start:], tool_call_id, tool_call_end_id
)
else:
content_text = _decode(tokenizer, ids).strip()
tool_calls = None
return ParsedResponse(
content=content_text,
reasoning_content=reasoning or None,
tool_calls=tool_calls or None,
)
def _parse_xml_tool_calls(
tokenizer, ids: list[int], tc_id: int, tc_end_id: int
) -> list[dict]:
"""Parse Qwen3.5-style XML tool calls from token IDs."""
import re
tool_calls = []
i = 0
while i < len(ids):
if ids[i] == tc_id:
end = _find(ids, tc_end_id, i + 1)
if end == -1:
break
block_text = _decode(tokenizer, ids[i + 1 : end])
name_match = re.search(r"<function=([^>]+)>", block_text)
if name_match:
name = name_match.group(1)
arguments = {}
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
tool_calls.append({"function": {"name": name, "arguments": arguments}})
i = end + 1
else:
i += 1
return tool_calls
# ── GLM-5/4.7/4.5: <tool_call> name <arg_key>k</arg_key> <arg_value>v</arg_value> </tool_call>
def parse_glm(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
think_id: int,
think_end_id: int,
tool_call_id: int,
tool_call_end_id: int,
arg_key_id: int,
arg_key_end_id: int,
arg_value_id: int,
arg_value_end_id: int,
) -> ParsedResponse:
"""Parse GLM completion tokens. Token-level thinking + arg_key/arg_value tool calls."""
ids = _strip_stop_tokens(token_ids, stop_ids)
# Thinking by token ID
reasoning = None
think_end = _find(ids, think_end_id)
if think_end != -1:
reasoning_ids = ids[:think_end]
reasoning_ids = [t for t in reasoning_ids if t != think_id]
reasoning = _decode(tokenizer, reasoning_ids).strip()
ids = ids[think_end + 1 :]
elif think_id in set(ids):
think_start = _find(ids, think_id)
reasoning = _decode(tokenizer, ids[think_start + 1 :]).strip()
return ParsedResponse(
content="", reasoning_content=reasoning or None, tool_calls=None
)
# Tool calls by token ID
tc_start = _find(ids, tool_call_id)
if tc_start != -1:
content_text = _decode(tokenizer, ids[:tc_start]).strip()
tool_calls = _parse_glm_tool_calls(
tokenizer,
ids[tc_start:],
tool_call_id,
tool_call_end_id,
arg_key_id,
arg_key_end_id,
arg_value_id,
arg_value_end_id,
)
else:
content_text = _decode(tokenizer, ids).strip()
tool_calls = None
return ParsedResponse(
content=content_text,
reasoning_content=reasoning or None,
tool_calls=tool_calls or None,
)
def _parse_glm_tool_calls(
tokenizer, ids, tc_id, tc_end_id, ak_id, ake_id, av_id, ave_id
) -> list[dict]:
"""Parse GLM-style tool calls: name + arg_key/arg_value pairs, all by token ID."""
tool_calls = []
i = 0
while i < len(ids):
if ids[i] == tc_id:
end = _find(ids, tc_end_id, i + 1)
if end == -1:
break
block = ids[i + 1 : end]
# Name is everything before first <arg_key>
first_ak = _find(block, ak_id)
if first_ak == -1:
name = _decode(tokenizer, block).strip()
arguments = {}
else:
name = _decode(tokenizer, block[:first_ak]).strip()
arguments = {}
j = first_ak
while j < len(block):
if block[j] == ak_id:
ake = _find(block, ake_id, j + 1)
if ake == -1:
break
key = _decode(tokenizer, block[j + 1 : ake]).strip()
av = _find(block, av_id, ake + 1)
if av == -1:
break
ave = _find(block, ave_id, av + 1)
if ave == -1:
break
val_text = _decode(tokenizer, block[av + 1 : ave]).strip()
try:
arguments[key] = json.loads(val_text)
except (json.JSONDecodeError, ValueError):
arguments[key] = val_text
j = ave + 1
else:
j += 1
tool_calls.append({"function": {"name": name, "arguments": arguments}})
i = end + 1
else:
i += 1
return tool_calls
# ── DeepSeek V3: <|tool▁calls▁begin|>...<|tool▁calls▁end|> + text <think> tags ──
def parse_deepseek_v3(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
tool_calls_begin_id: int,
tool_calls_end_id: int,
tool_call_begin_id: int,
tool_call_end_id: int,
tool_sep_id: int,
) -> ParsedResponse:
"""Parse DeepSeek V3 completion tokens.
Thinking is embedded as plain text <think>...</think> tags (not special tokens).
Tool calls are delimited by special tokens:
<|tool▁calls▁begin|>
<|tool▁call▁begin|>function<|tool▁sep|>{name}\\n```json\\n{args}\\n```<|tool▁call▁end|>
<|tool▁calls▁end|>
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
# ── Tool calls ──────────────────────────────────────────────────
tc_section_start = _find(ids, tool_calls_begin_id)
if tc_section_start != -1:
content_ids = ids[:tc_section_start]
tool_calls = _parse_deepseek_tool_calls(
tokenizer,
ids[tc_section_start:],
tool_calls_begin_id,
tool_calls_end_id,
tool_call_begin_id,
tool_call_end_id,
tool_sep_id,
)
else:
content_ids = ids
tool_calls = None
text = _decode(tokenizer, content_ids)
# ── Thinking from text tags ────────────────────────────────────
reasoning = None
if "</think>" in text:
before, _, after = text.partition("</think>")
reasoning = before.replace("<think>", "").lstrip("\n").rstrip("\n").strip()
text = after.lstrip("\n")
return ParsedResponse(
content=text.strip(),
reasoning_content=reasoning or None,
tool_calls=tool_calls or None,
)
def _parse_deepseek_tool_calls(
tokenizer,
ids: list[int],
tc_begin_id: int,
tc_end_id: int,
call_begin_id: int,
call_end_id: int,
sep_id: int,
) -> list[dict] | None:
"""Parse DeepSeek V3-style tool calls from token IDs.
Each individual tool call is delimited by <|tool▁call▁begin|> ... <|tool▁call▁end|>.
Inside, <|tool▁sep|> separates the call type (e.g. "function") from the
function name and JSON arguments block.
"""
import re
tool_calls: list[dict] = []
# Find the outer section boundaries.
section_start = _find(ids, tc_begin_id)
if section_start == -1:
return None
section_end = _find(ids, tc_end_id, section_start + 1)
if section_end == -1:
section_end = len(ids)
section_ids = ids[section_start + 1 : section_end]
i = 0
while i < len(section_ids):
if section_ids[i] == call_begin_id:
end = _find(section_ids, call_end_id, i + 1)
if end == -1:
end = len(section_ids)
call_ids = section_ids[i + 1 : end]
# Find <|tool▁sep|> to split type from name+args.
sep_pos = _find(call_ids, sep_id)
if sep_pos == -1:
# Malformed — skip.
i = end + 1
continue
# Everything after <|tool▁sep|> is the name and args block.
after_sep_ids = call_ids[sep_pos + 1 :]
after_sep_text = _decode(tokenizer, after_sep_ids).strip()
# Extract function name and JSON arguments.
# Format: "{name}\n```json\n{args}\n```"
# But we also gracefully handle raw JSON without the code fence.
name = ""
args_str = ""
# Try to split on first newline to get name, then find JSON.
newline_pos = after_sep_text.find("\n")
if newline_pos != -1:
name = after_sep_text[:newline_pos].strip()
rest = after_sep_text[newline_pos + 1 :].strip()
# Strip optional ```json ... ``` fence.
fence_match = re.match(r"```(?:json)?\s*([\s\S]*?)\s*```$", rest)
if fence_match:
args_str = fence_match.group(1).strip()
else:
args_str = rest
else:
# No newline — treat entire text as name, no args.
name = after_sep_text
# Parse arguments as JSON.
try:
arguments = json.loads(args_str) if args_str else {}
except json.JSONDecodeError:
arguments = args_str # preserve raw string on failure
tool_calls.append({"function": {"name": name, "arguments": arguments}})
i = end + 1
else:
i += 1
return tool_calls if tool_calls else None
# ── MiniMax: <minimax:tool_call> ... </minimax:tool_call> ────────────
def parse_minimax(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
think_id: int,
think_end_id: int,
tool_call_id: int,
tool_call_end_id: int,
) -> ParsedResponse:
"""Parse MiniMax M2 completion tokens."""
ids = _strip_stop_tokens(token_ids, stop_ids)
# Thinking: </think> by token ID. MiniMax doesn't generate <think> start.
reasoning = None
think_end = _find(ids, think_end_id)
if think_end != -1:
reasoning_ids = ids[:think_end]
reasoning_ids = [t for t in reasoning_ids if t != think_id]
reasoning = _decode(tokenizer, reasoning_ids).strip()
ids = ids[think_end + 1 :]
elif think_id in set(ids):
think_start = _find(ids, think_id)
reasoning = _decode(tokenizer, ids[think_start + 1 :]).strip()
return ParsedResponse(
content="", reasoning_content=reasoning or None, tool_calls=None
)
# Tool calls by token ID
tc_start = _find(ids, tool_call_id)
if tc_start != -1:
content_text = _decode(tokenizer, ids[:tc_start]).strip()
# Decode the tool call blocks and parse with regex (invoke/parameter are text, not tokens)
tool_calls = []
i = tc_start
while i < len(ids):
if ids[i] == tool_call_id:
end = _find(ids, tool_call_end_id, i + 1)
if end == -1:
break
block_text = _decode(tokenizer, ids[i + 1 : end])
import re
for invoke_match in re.finditer(
r'<invoke name="([^"]+)">(.*?)</invoke>', block_text, re.DOTALL
):
name = invoke_match.group(1)
body = invoke_match.group(2)
arguments = {}
for pm in re.finditer(
r'<parameter name="([^"]+)">(.*?)</parameter>', body, re.DOTALL
):
pname = pm.group(1)
pval = pm.group(2).strip()
try:
arguments[pname] = json.loads(pval)
except (json.JSONDecodeError, ValueError):
arguments[pname] = pval
tool_calls.append(
{"function": {"name": name, "arguments": arguments}}
)
i = end + 1
else:
i += 1
else:
content_text = _decode(tokenizer, ids).strip()
tool_calls = None
return ParsedResponse(
content=content_text,
reasoning_content=reasoning or None,
tool_calls=tool_calls or None,
)
# ── Kimi K2: <|tool_calls_section_begin|> ... <|tool_calls_section_end|> ────
def parse_kimi_k2(
tokenizer,
token_ids: list[int],
*,
stop_ids: set[int],
tool_calls_section_begin_id: int,
tool_calls_section_end_id: int,
tool_call_begin_id: int,
tool_call_argument_begin_id: int,
tool_call_end_id: int,
) -> ParsedResponse:
"""Parse Kimi K2 completion tokens.
Thinking is encoded as text tags <think>...</think>.
Tool calls use section/call-level special tokens.
Tool call IDs are in format ``functions.name:index``.
"""
ids = _strip_stop_tokens(token_ids, stop_ids)
# ── Tool calls ────────────────────────────────────────────────
section_start = _find(ids, tool_calls_section_begin_id)
if section_start != -1:
content_ids = ids[:section_start]
section_end = _find(ids, tool_calls_section_end_id, section_start + 1)
if section_end == -1:
section_end = len(ids)
section_ids = ids[section_start + 1 : section_end]
tool_calls = _parse_kimi_k2_tool_calls(
tokenizer,
section_ids,
tool_call_begin_id,
tool_call_argument_begin_id,
tool_call_end_id,
)
else:
content_ids = ids
tool_calls = None
# ── Thinking from text tags ───────────────────────────────────
text = _decode(tokenizer, content_ids)
reasoning: str | None = None
if "</think>" in text:
before, _, after = text.partition("</think>")
raw_think = before.replace("<think>", "", 1)
reasoning = raw_think.strip("\n").strip() or None
text = after.strip("\n")
elif "<think>" in text:
# Truncated thinking (no closing tag)
raw_think = text.split("<think>", 1)[1]
reasoning = raw_think.strip("\n").strip() or None
return ParsedResponse(
content="",
reasoning_content=reasoning,
tool_calls=None,
)
return ParsedResponse(
content=text.strip(),
reasoning_content=reasoning,
tool_calls=tool_calls or None,
)
def _parse_kimi_k2_tool_calls(
tokenizer,
ids: list[int],
tc_begin_id: int,
tc_arg_begin_id: int,
tc_end_id: int,
) -> list[dict]:
"""Parse individual Kimi K2 tool calls from the section token IDs.
Format per call:
<|tool_call_begin|>{id}<|tool_call_argument_begin|>{json_args}<|tool_call_end|>
The ``id`` is in format ``functions.name:index``; the function name is
extracted by stripping the ``functions.`` prefix and ``:index`` suffix.
"""
tool_calls: list[dict] = []
i = 0
while i < len(ids):
if ids[i] == tc_begin_id:
# Find <|tool_call_argument_begin|>
arg_begin = _find(ids, tc_arg_begin_id, i + 1)
if arg_begin == -1:
break
# Find <|tool_call_end|>
tc_end = _find(ids, tc_end_id, arg_begin + 1)
if tc_end == -1:
tc_end = len(ids)
raw_id = _decode(tokenizer, ids[i + 1 : arg_begin]).strip()
args_str = _decode(tokenizer, ids[arg_begin + 1 : tc_end]).strip()
# Extract function name from "functions.name:index"
name_part = raw_id.split(":", 1)[0]
if "." in name_part:
_, func_name = name_part.split(".", 1)
else:
func_name = name_part
try:
arguments = json.loads(args_str)
except json.JSONDecodeError:
arguments = args_str
tool_calls.append(
{
"id": raw_id,
"type": "function",
"function": {
"name": func_name,
"arguments": arguments,
},
}
)
i = tc_end + 1
else:
i += 1
return tool_calls
# ── GptOss (Harmony): <|start|>role<|channel|>ch<|message|>content<|end|/return|/call|>
def parse_gpt_oss(
tokenizer,
token_ids: list[int],
*,
return_id: int,
call_id: int,
start_id: int,
end_id: int,
channel_id: int,
message_id: int,
constrain_id: int,
) -> ParsedResponse:
"""Parse GptOss (Harmony) completion tokens.
Finds the earliest terminal token (<|return|> or <|call|>), then walks the
token stream block-by-block to extract:
- analysis channel → reasoning_content
- final channel → content
- commentary with to=functions.* → tool_calls (JSON arguments)
- commentary without recipient → content (preamble text)
"""
import re
# Only <|return|> terminates the whole turn. <|call|> closes an
# individual tool-call commentary block — a single turn may contain
# several, so we must NOT truncate at the first <|call|>.
return_pos = _find(token_ids, return_id)
if return_pos != -1:
ids = token_ids[:return_pos]
else:
ids = list(token_ids)
reasoning_parts: list[str] = []
content_parts: list[str] = []
tool_calls: list[dict] = []
i = 0
while i < len(ids):
if ids[i] != start_id:
i += 1
continue
# Find <|message|> that terminates this block's header
msg_pos = _find(ids, message_id, i + 1)
if msg_pos == -1:
break
# Header: tokens between <|start|> and <|message|>
header_ids = ids[i + 1 : msg_pos]
header_text = _decode(tokenizer, header_ids)
# Body: tokens from after <|message|> up to the next block boundary
# (<|start|>, <|end|>, or <|call|> — the last closes a tool-call
# commentary block within the same turn).
body_start = msg_pos + 1
candidates = [
pos
for pos in (
_find(ids, start_id, body_start),
_find(ids, end_id, body_start),
_find(ids, call_id, body_start),
)
if pos != -1
]
body_end = min(candidates) if candidates else len(ids)
body_text = _decode(tokenizer, ids[body_start:body_end])
# Extract channel: token after <|channel|> in header_ids
channel = _gptoss_extract_after_token(tokenizer, header_ids, channel_id)
# Extract recipient: "to=..." field in header text
recipient_match = re.search(r"to=([^\s<]+)", header_text)
recipient = recipient_match.group(1) if recipient_match else None
if recipient and recipient.startswith("functions."):
tool_name = recipient[len("functions.") :]
try:
arguments = json.loads(body_text)
except json.JSONDecodeError:
arguments = body_text # preserve raw string on failure
tool_calls.append(
{
"function": {
"name": tool_name,
"arguments": arguments,
}
}
)
elif channel == "analysis":
reasoning_parts.append(body_text)
elif channel == "final":
content_parts.append(body_text)
elif channel == "commentary":
# Commentary without a tool recipient is a user-visible preamble
content_parts.append(body_text)
# Advance: skip body + any trailing <|end|> / <|call|>
i = body_end
if i < len(ids) and ids[i] in (end_id, call_id):
i += 1
reasoning = "".join(reasoning_parts).strip() or None
content = "".join(content_parts).strip()
return ParsedResponse(
content=content,
reasoning_content=reasoning,
tool_calls=tool_calls or None,
)
def _gptoss_extract_after_token(
tokenizer,
header_ids: list[int],
marker_id: int,
) -> str | None:
"""Return the first decoded word appearing after marker_id in header_ids."""
pos = _find(header_ids, marker_id)
if pos == -1:
return None
after = _decode(tokenizer, header_ids[pos + 1 :]).strip()
# Take first whitespace-delimited word (channel name)
return after.split()[0] if after else None
+371
View File
@@ -0,0 +1,371 @@
"""Qwen3 Renderer — hard-coded Python mirroring the Qwen3 Jinja chat template.
Key differences from Qwen3.5:
- Content is always string (no list/multimodal support)
- Tool calls use JSON format: {"name": "...", "arguments": ...}
- Thinking blocks only inserted when loop.last OR reasoning_content present
- Generation prompt does NOT add <think> by default
"""
from __future__ import annotations
import json
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.parsing import parse_qwen3
_TOOLS_HEADER = (
"# Tools\n\n"
"You may call one or more functions to assist with the user query.\n\n"
"You are provided with function signatures within <tools></tools> XML tags:\n"
"<tools>"
)
_TOOLS_FOOTER = (
"\n</tools>\n\n"
"For each function call, return a json object with function name and arguments "
"within <tool_call></tool_call> XML tags:\n"
"<tool_call>\n"
'{"name": <function-name>, "arguments": <args-json-object>}\n'
"</tool_call>"
)
class Qwen3Renderer:
"""Deterministic message → token renderer for Qwen3 models."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
self._im_start = self._token_id("<|im_start|>")
self._im_end = self._token_id("<|im_end|>")
self._endoftext = self._token_id("<|endoftext|>")
self._tool_call = self._token_id("<tool_call>")
self._tool_call_end = self._token_id("</tool_call>")
self._tool_response = self._token_id("<tool_response>")
self._tool_response_end = self._token_id("</tool_response>")
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 _last_query_index(messages: list[Message]) -> int:
for i in range(len(messages) - 1, -1, -1):
msg = messages[i]
if msg.get("role") != "user":
continue
content = msg.get("content")
if not isinstance(content, str):
continue
if not (
content.startswith("<tool_response>")
and content.endswith("</tool_response>")
):
return i
return len(messages) - 1
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_ids(ids: list[int], msg_idx: int) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
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:
emit_ids(self._encode(text), msg_idx)
# ── 1. System + tools ───────────────────────────────────────
first_is_system = messages[0].get("role") == "system"
if tools:
sys_idx = 0 if first_is_system else -1
emit_special(self._im_start, sys_idx)
tool_text = "system\n"
if first_is_system:
tool_text += (messages[0].get("content") or "") + "\n\n"
tool_text += _TOOLS_HEADER
for tool in tools:
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
tool_text += _TOOLS_FOOTER
emit_text(tool_text, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
elif first_is_system:
emit_special(self._im_start, 0)
emit_text("system\n" + (messages[0].get("content") or ""), 0)
emit_special(self._im_end, 0)
emit_text("\n", 0)
# ── 2. Compute last_query_index ─────────────────────────────
last_qi = self._last_query_index(messages)
# ── 3. Iterate messages ─────────────────────────────────────
num_messages = len(messages)
for i, msg in enumerate(messages):
role = msg["role"]
content = msg.get("content") if isinstance(msg.get("content"), str) else ""
if role == "system":
if i == 0:
continue
emit_special(self._im_start, i)
emit_text(role + "\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "assistant":
self._render_assistant(
msg,
i,
content,
last_qi,
i == num_messages - 1,
emit_special=emit_special,
emit_text=emit_text,
)
elif role == "tool":
self._render_tool(
messages, i, content, emit_special=emit_special, emit_text=emit_text
)
# ── 4. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
if not self._enable_thinking:
emit_text("<think>\n\n</think>\n\n", -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]) -> ParsedResponse:
return parse_qwen3(
self._tokenizer,
token_ids,
stop_ids={self._im_end, self._endoftext},
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
)
def get_stop_token_ids(self) -> list[int]:
return [self._im_end, self._endoftext]
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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._im_end, self._endoftext},
synthesize_close=self._im_end,
)
if previous_ids is None:
return None
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))
# Trailing ``\n`` after the turn-close token. ``render()`` emits this
# as part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
# ``\n`` never lands in prev_completion.
emit_text("\n", -1)
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = msg.get("content") if isinstance(msg.get("content"), str) else ""
if role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "system":
emit_special(self._im_start, i)
emit_text("system\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "tool":
self._render_tool(
new_messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
)
else:
return None
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
if not self._enable_thinking:
emit_text("<think>\n\n</think>\n\n", -1)
return previous_ids + ext
def _render_assistant(
self,
msg,
msg_idx,
content,
last_query_index,
is_last,
*,
emit_special,
emit_text,
):
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
elif "</think>" in content:
before, after = content.split("</think>", 1)
if "<think>" in before:
reasoning_content = before.split("<think>")[-1].lstrip("\n")
else:
reasoning_content = before.lstrip("\n")
reasoning_content = reasoning_content.rstrip("\n")
content = after.lstrip("\n")
emit_special(self._im_start, msg_idx)
# Build the full text between <|im_start|> and <|im_end|> with tool call
# special tokens interspersed. We must keep text segments contiguous to
# preserve BPE merges (e.g., ".\n" is a single token in Qwen3).
tool_calls = msg.get("tool_calls") or []
if msg_idx > last_query_index and (is_last or reasoning_content):
prefix = (
"assistant\n<think>\n"
+ reasoning_content.strip("\n")
+ "\n</think>\n\n"
+ content.lstrip("\n")
)
else:
prefix = "assistant\n" + content
if not tool_calls:
emit_text(prefix, msg_idx)
else:
for tc_idx, tc in enumerate(tool_calls):
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
args_str = (
json.dumps(arguments, ensure_ascii=False)
if not isinstance(arguments, str)
else arguments
)
# Text before this tool_call (includes separator)
if tc_idx == 0:
separator = "\n" if content else ""
emit_text(prefix + separator, msg_idx)
else:
emit_text("\n", msg_idx)
emit_special(self._tool_call, msg_idx)
emit_text(
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
msg_idx,
)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
def _render_tool(
self,
messages: list[Message],
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
) -> None:
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"
)
if not prev_is_tool:
emit_special(self._im_start, msg_idx)
emit_text("user", msg_idx)
emit_text("\n", msg_idx)
emit_special(self._tool_response, msg_idx)
emit_text("\n" + content + "\n", msg_idx)
emit_special(self._tool_response_end, msg_idx)
if not next_is_tool:
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
+502
View File
@@ -0,0 +1,502 @@
"""Qwen3.5 Renderer — hard-coded Python that mirrors the Qwen3.5 Jinja chat template.
Produces token-for-token identical output to tokenizer.apply_chat_template() while
also tracking which message produced each token (for per-token loss masks).
"""
from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.parsing import parse_qwen35
# ---------------------------------------------------------------------------
# Tool system prompt constants (must match the Jinja template exactly)
# ---------------------------------------------------------------------------
_TOOLS_HEADER = "# Tools\n\nYou have access to the following functions:\n\n<tools>"
_TOOLS_FOOTER = "\n</tools>"
_TOOLS_INSTRUCTIONS = (
"\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:"
"\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1"
"\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter"
"\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>"
"\n\n<IMPORTANT>\nReminder:"
"\n- Function calls MUST follow the specified format:"
" an inner <function=...></function> block must be nested within"
" <tool_call></tool_call> XML tags"
"\n- Required parameters MUST be specified"
"\n- You may provide optional reasoning for your function call"
" in natural language BEFORE the function call, but NOT after"
"\n- If there is no function call available, answer the question like normal"
" with your current knowledge and do not tell the user about function calls"
"\n</IMPORTANT>"
)
class Qwen35Renderer:
"""Deterministic message → token renderer for Qwen3.5 models."""
def __init__(
self,
tokenizer: PreTrainedTokenizer,
*,
enable_thinking: bool = True,
):
self._tokenizer = tokenizer
self._enable_thinking = enable_thinking
# Look up special token IDs from the tokenizer (not hardcoded)
self._im_start = self._token_id("<|im_start|>")
self._im_end = self._token_id("<|im_end|>")
self._endoftext = self._token_id("<|endoftext|>")
self._think = self._token_id("<think>")
self._think_end = self._token_id("</think>")
self._tool_call = self._token_id("<tool_call>")
self._tool_call_end = self._token_id("</tool_call>")
self._tool_response = self._token_id("<tool_response>")
self._tool_response_end = self._token_id("</tool_response>")
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)
# ------------------------------------------------------------------
# Content rendering (mirrors the render_content Jinja macro)
# ------------------------------------------------------------------
@staticmethod
def _render_content(content: Any) -> str:
"""Render message content to a text string (before tokenization).
Handles string, list of text parts, and None.
"""
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
if "text" in item:
parts.append(item["text"])
else:
raise ValueError(f"Unexpected content item: {item}")
return "".join(parts)
raise TypeError(f"Unexpected content type: {type(content)}")
# ------------------------------------------------------------------
# last_query_index computation
# ------------------------------------------------------------------
@staticmethod
def _last_query_index(messages: list[Message]) -> int:
"""Find the index of the last 'real' user query (not a tool_response wrapper).
Returns ``len(messages)`` — an out-of-range sentinel — when no such
query exists. Callers compare ``msg_idx > last_query_index`` to
decide whether an assistant turn sits after the last user query
(and so keeps its thinking block). The sentinel makes that check
uniformly ``False``, which is the only reasonable default for
assistant-only inputs (e.g. the bridge's dummy-assistant render).
"""
for i in range(len(messages) - 1, -1, -1):
msg = messages[i]
if msg.get("role") != "user":
continue
content = Qwen35Renderer._render_content(msg.get("content")).strip()
if not (
content.startswith("<tool_response>")
and content.endswith("</tool_response>")
):
return i
return len(messages)
# ------------------------------------------------------------------
# Core render method
# ------------------------------------------------------------------
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_ids(ids: list[int], msg_idx: int) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
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:
emit_ids(self._encode(text), msg_idx)
# ── 1. System message + optional tools ──────────────────────
first_is_system = messages[0].get("role") == "system"
if tools:
# System message index for attribution
sys_idx = 0 if first_is_system else -1
emit_special(self._im_start, sys_idx)
emit_text("system\n", sys_idx)
# Tools header + JSON definitions
tool_text = _TOOLS_HEADER
for tool in tools:
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
tool_text += _TOOLS_FOOTER
tool_text += _TOOLS_INSTRUCTIONS
# Append user's system content if present
if first_is_system:
sys_content = self._render_content(messages[0].get("content")).strip()
if sys_content:
tool_text += "\n\n" + sys_content
emit_text(tool_text, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
elif first_is_system:
sys_content = self._render_content(messages[0].get("content")).strip()
emit_special(self._im_start, 0)
emit_text("system\n" + sys_content, 0)
emit_special(self._im_end, 0)
emit_text("\n", 0)
# ── 2. Compute last_query_index ─────────────────────────────
last_qi = self._last_query_index(messages)
# ── 3. Iterate messages ─────────────────────────────────────
for i, msg in enumerate(messages):
role = msg["role"]
content = self._render_content(msg.get("content")).strip()
if role == "system":
if i != 0:
raise ValueError("System message must be at the beginning.")
continue # Already handled above
elif role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "assistant":
self._render_assistant(
msg,
i,
content,
last_qi,
emit_special=emit_special,
emit_text=emit_text,
emit_ids=emit_ids,
)
elif role == "tool":
self._render_tool(
messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
)
else:
raise ValueError(f"Unexpected message role: {role}")
# ── 4. Generation prompt ────────────────────────────────────
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
if self._enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
else:
emit_special(self._think, -1)
emit_text("\n\n", -1)
emit_special(self._think_end, -1)
emit_text("\n\n", -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]) -> ParsedResponse:
return parse_qwen35(
self._tokenizer,
token_ids,
stop_ids={self._im_end, self._endoftext},
think_id=self._think,
think_end_id=self._think_end,
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
)
def get_stop_token_ids(self) -> list[int]:
return [self._im_end, self._endoftext]
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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._im_end, self._endoftext},
synthesize_close=self._im_end,
)
if previous_ids is None:
return None
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))
def emit_ids(ids: list[int], _msg_idx: int = -1) -> None:
ext.extend(ids)
# Trailing ``\n`` after ``<|im_end|>`` — ``render()`` emits it as
# part of the prior turn, but vLLM stops on ``<|im_end|>`` so the
# ``\n`` never makes it into prev_completion.
emit_text("\n", -1)
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._render_content(msg.get("content")).strip()
if role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "system":
emit_special(self._im_start, i)
emit_text("system\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "tool":
self._render_tool(
new_messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
)
else:
return None
# Generation prompt — matches the gen-prompt branch of ``render()``.
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
if self._enable_thinking:
emit_special(self._think, -1)
emit_text("\n", -1)
else:
emit_special(self._think, -1)
emit_text("\n\n", -1)
emit_special(self._think_end, -1)
emit_text("\n\n", -1)
return previous_ids + ext
# ------------------------------------------------------------------
# Assistant message rendering
# ------------------------------------------------------------------
def _should_render_thinking(self, msg_idx: int, last_query_index: int) -> bool:
"""Whether to emit a ``<think>`` block for the assistant message at ``msg_idx``.
Qwen3.5 only emits thinking for assistant turns that sit after the
last real user query. Subclasses (Qwen3.6) may override to mirror
the newer template's ``preserve_thinking`` knob.
"""
return msg_idx > last_query_index
@staticmethod
def _render_arg_value(arg_value: Any) -> str:
"""Serialise a single tool-call argument value to text.
Mirrors the Jinja args-value branch: dicts/lists → compact JSON;
everything else (including bool, int, None) → ``str(...)``. That
matches Qwen3.5's ``tojson`` for mapping/sequence / ``string`` for
the rest. Qwen3.6 overrides this to push non-strings through JSON
so bools round-trip as ``true``/``false`` instead of ``True``/``False``.
"""
if isinstance(arg_value, (dict, list)):
return json.dumps(arg_value, ensure_ascii=False)
return str(arg_value)
def _render_assistant(
self,
msg: Message,
msg_idx: int,
content: str,
last_query_index: int,
*,
emit_special,
emit_text,
emit_ids,
) -> None:
# Extract reasoning_content
reasoning_content = ""
if isinstance(msg.get("reasoning_content"), str):
reasoning_content = msg["reasoning_content"]
elif "</think>" in content:
# Split on </think> to separate reasoning from content
before_think_end, after_think_end = content.split("</think>", 1)
# Extract text after <think> (if present)
if "<think>" in before_think_end:
reasoning_content = before_think_end.split("<think>")[-1].lstrip("\n")
else:
reasoning_content = before_think_end.lstrip("\n")
reasoning_content = reasoning_content.rstrip("\n")
content = after_think_end.lstrip("\n")
reasoning_content = reasoning_content.strip()
emit_special(self._im_start, msg_idx)
if self._should_render_thinking(msg_idx, last_query_index):
# Include thinking block
emit_text("assistant\n", msg_idx)
emit_special(self._think, msg_idx)
emit_text("\n" + reasoning_content + "\n", msg_idx)
emit_special(self._think_end, msg_idx)
emit_text("\n\n" + content, msg_idx)
else:
emit_text("assistant\n" + content, msg_idx)
# Tool calls
tool_calls = msg.get("tool_calls") or []
if tool_calls:
for tc_idx, tc in enumerate(tool_calls):
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
# Separator before <tool_call>
if tc_idx == 0:
if content.strip():
emit_text("\n\n", msg_idx)
# else: no separator
else:
emit_text("\n", msg_idx)
emit_special(self._tool_call, msg_idx)
emit_text("\n<function=" + name + ">\n", msg_idx)
# Render arguments
# OpenAI canonical form: arguments is a JSON string. Parse it so the
# per-argument rendering below still works.
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except json.JSONDecodeError:
arguments = {}
if isinstance(arguments, dict):
for arg_name, arg_value in arguments.items():
value_str = self._render_arg_value(arg_value)
emit_text(
"<parameter="
+ arg_name
+ ">\n"
+ value_str
+ "\n</parameter>\n",
msg_idx,
)
emit_text("</function>\n", msg_idx)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
# ------------------------------------------------------------------
# Tool message rendering
# ------------------------------------------------------------------
def _render_tool(
self,
messages: list[Message],
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
) -> None:
# Consecutive tool messages are grouped under a single <|im_start|>user block
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"
)
if not prev_is_tool:
emit_special(self._im_start, msg_idx)
emit_text("user", msg_idx)
emit_text("\n", msg_idx)
emit_special(self._tool_response, msg_idx)
emit_text("\n" + content + "\n", msg_idx)
emit_special(self._tool_response_end, msg_idx)
if not next_is_tool:
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
+48
View File
@@ -0,0 +1,48 @@
"""Qwen3.6 Renderer — mirrors the Qwen3.6 Jinja chat template.
Delta vs Qwen3.5 (template lines 100 and 122):
1. Optional ``preserve_thinking`` flag retains historical ``<think>`` blocks
for assistant turns before the last user query. The template default
(flag unset) matches Qwen3.5's "thinking only after last query" behaviour,
so the renderer keeps that as the default.
2. Tool-call argument serialization changed to ``tojson`` for every non-string
value. Bools now render as ``true``/``false`` (not ``True``/``False``) and
``None`` as ``null`` (not ``None``), fixing the single-turn extension-break
mode where a boolean parameter's case drifted across a re-render.
Everything else — tool system prompt, tool-call XML structure, thinking
markers, bridge logic, parser — is identical to Qwen3.5.
"""
from __future__ import annotations
import json
from typing import Any
from renderers.qwen35 import Qwen35Renderer
class Qwen36Renderer(Qwen35Renderer):
"""Deterministic message → token renderer for Qwen3.6 models."""
def __init__(
self,
tokenizer,
*,
enable_thinking: bool = True,
preserve_thinking: bool = False,
):
super().__init__(tokenizer, enable_thinking=enable_thinking)
self._preserve_thinking = preserve_thinking
def _should_render_thinking(self, msg_idx: int, last_query_index: int) -> bool:
if self._preserve_thinking:
return True
return msg_idx > last_query_index
@staticmethod
def _render_arg_value(arg_value: Any) -> str:
if isinstance(arg_value, str):
return arg_value
return json.dumps(arg_value, ensure_ascii=False)
+326
View File
@@ -0,0 +1,326 @@
"""Qwen3-VL renderer (text-only).
Mirrors the Qwen3-VL chat template for text-only conversations. Image and
video content parts are not supported — the renderer pipeline does not
carry image payloads through to vLLM. Pass multimodal inputs through MITO
(server-side templating) instead.
"""
from __future__ import annotations
import json
from typing import Any
from transformers.tokenization_utils import PreTrainedTokenizer
from renderers.base import (
Message,
ParsedResponse,
RenderedTokens,
ToolSpec,
reject_assistant_in_extension,
trim_to_turn_close,
)
from renderers.parsing import parse_qwen3
_TOOLS_HEADER = (
"# Tools\n\n"
"You may call one or more functions to assist with the user query.\n\n"
"You are provided with function signatures within <tools></tools> XML tags:\n"
"<tools>"
)
_TOOLS_FOOTER = (
"\n</tools>\n\n"
"For each function call, return a json object with function name and arguments "
"within <tool_call></tool_call> XML tags:\n"
"<tool_call>\n"
'{"name": <function-name>, "arguments": <args-json-object>}\n'
"</tool_call>"
)
class Qwen3VLRenderer:
"""Deterministic message to token renderer for Qwen3-VL models (text-only)."""
def __init__(self, tokenizer: PreTrainedTokenizer):
self._tokenizer = tokenizer
self._im_start = self._token_id("<|im_start|>")
self._im_end = self._token_id("<|im_end|>")
self._endoftext = self._token_id("<|endoftext|>")
self._tool_call = self._token_id("<tool_call>")
self._tool_call_end = self._token_id("</tool_call>")
self._tool_response = self._token_id("<tool_response>")
self._tool_response_end = self._token_id("</tool_response>")
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 _render_text_content(content: Any) -> str:
if content is None:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict) and "text" in item:
parts.append(item["text"])
else:
raise ValueError(f"Unexpected content item: {item}")
return "".join(parts)
raise TypeError(f"Unexpected content type: {type(content)}")
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_ids(ids: list[int], msg_idx: int) -> None:
tokens.extend(ids)
indices.extend([msg_idx] * len(ids))
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:
emit_ids(self._encode(text), msg_idx)
first_is_system = messages[0].get("role") == "system"
if tools:
sys_idx = 0 if first_is_system else -1
emit_special(self._im_start, sys_idx)
tool_text = "system\n"
if first_is_system:
sys_content = self._render_text_content(messages[0].get("content"))
tool_text += sys_content + "\n\n"
tool_text += _TOOLS_HEADER
for tool in tools:
tool_text += "\n" + json.dumps(tool, ensure_ascii=False)
tool_text += _TOOLS_FOOTER
emit_text(tool_text, sys_idx)
emit_special(self._im_end, sys_idx)
emit_text("\n", sys_idx)
elif first_is_system:
emit_special(self._im_start, 0)
sys_content = self._render_text_content(messages[0].get("content"))
emit_text("system\n" + sys_content, 0)
emit_special(self._im_end, 0)
emit_text("\n", 0)
for i, msg in enumerate(messages):
role = msg["role"]
if role == "system":
continue
content = self._render_text_content(msg.get("content"))
if role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "assistant":
self._render_assistant(
msg, i, emit_special=emit_special, emit_text=emit_text
)
elif role == "tool":
self._render_tool(
messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
)
else:
raise ValueError(f"Unexpected message role: {role}")
if add_generation_prompt:
emit_special(self._im_start, -1)
emit_text("assistant\n", -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]) -> ParsedResponse:
return parse_qwen3(
self._tokenizer,
token_ids,
stop_ids={self._im_end, self._endoftext},
tool_call_id=self._tool_call,
tool_call_end_id=self._tool_call_end,
)
def get_stop_token_ids(self) -> list[int]:
return [self._im_end, self._endoftext]
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,
) -> list[int] | None:
if (
not previous_prompt_ids
or not new_messages
or reject_assistant_in_extension(new_messages)
):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._im_end, self._endoftext},
synthesize_close=self._im_end,
)
if previous_ids is None:
return None
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))
emit_text("\n", -1)
for i, msg in enumerate(new_messages):
role = msg.get("role")
content = self._render_text_content(msg.get("content"))
if role == "user":
emit_special(self._im_start, i)
emit_text("user\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "system":
emit_special(self._im_start, i)
emit_text("system\n" + content, i)
emit_special(self._im_end, i)
emit_text("\n", i)
elif role == "tool":
self._render_tool(
new_messages,
i,
content,
emit_special=emit_special,
emit_text=emit_text,
)
else:
return None
emit_special(self._im_start, -1)
emit_text("assistant\n", -1)
return previous_ids + ext
def _render_assistant(
self,
msg: Message,
msg_idx: int,
*,
emit_special,
emit_text,
) -> None:
content = self._render_text_content(msg.get("content"))
original_content = msg.get("content")
tool_calls = msg.get("tool_calls") or []
emit_special(self._im_start, msg_idx)
prefix = "assistant\n" + content
if not tool_calls:
emit_text(prefix, msg_idx)
else:
for tc_idx, tc in enumerate(tool_calls):
if tc_idx == 0:
separator = "\n" if original_content else ""
emit_text(prefix + separator, msg_idx)
else:
emit_text("\n", msg_idx)
func = tc.get("function") or tc
name = func.get("name", "")
arguments = func.get("arguments", {})
args_str = (
arguments
if isinstance(arguments, str)
else json.dumps(arguments, ensure_ascii=False)
)
emit_special(self._tool_call, msg_idx)
emit_text(
'\n{"name": "' + name + '", "arguments": ' + args_str + "}\n",
msg_idx,
)
emit_special(self._tool_call_end, msg_idx)
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
def _render_tool(
self,
messages: list[Message],
msg_idx: int,
content: str,
*,
emit_special,
emit_text,
) -> None:
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"
)
if not prev_is_tool:
emit_special(self._im_start, msg_idx)
emit_text("user", msg_idx)
emit_text("\n", msg_idx)
emit_special(self._tool_response, msg_idx)
emit_text("\n" + content + "\n", msg_idx)
emit_special(self._tool_response_end, msg_idx)
if not next_is_tool:
emit_special(self._im_end, msg_idx)
emit_text("\n", msg_idx)
+103
View File
@@ -0,0 +1,103 @@
"""Shared fixtures for renderer tests.
Each (model_name, renderer_name) pair gets a tokenizer + renderer.
The same barrage of tests runs against every pair.
"""
import os
import pytest
from transformers import AutoTokenizer
from renderers import create_renderer
# (HuggingFace model name, renderer name or "auto")
#
# Baseline matrix for render-parity, parse, and per-token-attribution
# tests. Models here are exercised by every shared test in this folder.
# Additional models for narrower tests (e.g. roundtrip) live with their
# own parametrization in the test file.
RENDERER_MODELS = [
("Qwen/Qwen3-8B", "auto"),
("Qwen/Qwen3.5-9B", "auto"),
("Qwen/Qwen3.6-35B-A3B", "auto"),
("Qwen/Qwen3-VL-4B-Instruct", "auto"),
("zai-org/GLM-5", "auto"),
("zai-org/GLM-5.1", "auto"),
("zai-org/GLM-4.7-Flash", "auto"),
("THUDM/GLM-4.5-Air", "auto"),
("MiniMaxAI/MiniMax-M2.5", "auto"),
("moonshotai/Kimi-K2-Instruct", "auto"),
("moonshotai/Kimi-K2.5", "auto"),
("moonshotai/Kimi-K2.6", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
("openai/gpt-oss-20b", "gpt_oss"),
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
]
_cache: dict[str, tuple] = {}
def _load(model_name: str, renderer_name: str):
key = f"{model_name}:{renderer_name}"
if key not in _cache:
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
renderer = create_renderer(tokenizer, renderer=renderer_name)
_cache[key] = (tokenizer, renderer)
return _cache[key]
def pytest_generate_tests(metafunc):
if "model_name" in metafunc.fixturenames:
metafunc.parametrize(
"model_name,renderer_name",
RENDERER_MODELS,
ids=[m for m, _ in RENDERER_MODELS],
)
@pytest.fixture
def tokenizer(model_name, renderer_name):
t, _ = _load(model_name, renderer_name)
return t
@pytest.fixture
def renderer(model_name, renderer_name):
_, r = _load(model_name, renderer_name)
return r
# Tests that compare the renderer output (or downstream tokens) against
# HF's ``apply_chat_template`` — or that feed plain text through the
# parser expecting a non-empty content. Both fail for gpt-oss because:
# 1. Our GptOssRenderer matches openai-harmony / vLLM, not HF's Jinja
# (they disagree on a trailing ``\n\n`` and the function-tools
# layout). Harmony parity is covered separately in
# ``test_gpt_oss_harmony_parity.py``.
# 2. The harmony parser only emits content from messages bracketed by
# ``<|start|>...<|message|>...<|end|>`` channel markers; plain text
# never matches a block, so the test's "Hello there!" probe
# trivially returns empty content. The parsing-test fixtures aren't
# designed for harmony format.
_GPT_OSS_HF_PARITY_TEST_FILES = {
"test_render_ids.py",
"test_build_helpers.py",
"test_parse_response.py",
"test_parse_response_robustness.py",
}
@pytest.fixture(autouse=True)
def _skip_gpt_oss_for_hf_parity_tests(request):
callspec = getattr(request.node, "callspec", None)
model_name = callspec.params.get("model_name") if callspec else None
if model_name != "openai/gpt-oss-20b":
return
test_file = os.path.basename(str(request.node.fspath))
if test_file in _GPT_OSS_HF_PARITY_TEST_FILES:
pytest.skip(
f"{model_name}: renderer matches openai-harmony / vLLM, not HF "
"apply_chat_template — see test_gpt_oss_harmony_parity.py"
)
+189
View File
@@ -0,0 +1,189 @@
"""Cross-renderer bridge contract tests.
Verifies for every hand-coded renderer that ``bridge_to_next_turn``:
1. Extends ``prev_prompt_ids + prev_completion_ids`` verbatim.
2. Refuses assistant-role messages in ``new_messages``.
3. Synthesises the canonical turn close on truncation.
4. On clean stop, the extension is compatible with a fresh render:
decoding the extension should contain the new-message content and a
generation-prompt-looking tail.
DefaultRenderer is excluded because it intentionally returns None (it
doesn't know its template's close). That path is exercised by the caller
fallback in ``test_renderer_e2e.py``.
"""
from __future__ import annotations
from functools import lru_cache
import pytest
# (HF model name, renderer name) — one representative per renderer class.
_BRIDGE_MODELS = [
("Qwen/Qwen3-8B", "auto"),
("Qwen/Qwen3.5-9B", "auto"),
("Qwen/Qwen3.6-35B-A3B", "auto"),
("zai-org/GLM-5", "auto"),
("zai-org/GLM-5.1", "auto"),
("THUDM/GLM-4.5-Air", "auto"),
("MiniMaxAI/MiniMax-M2.5", "auto"),
("moonshotai/Kimi-K2-Instruct", "auto"),
("moonshotai/Kimi-K2.5", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("openai/gpt-oss-20b", "gpt_oss"),
]
@lru_cache(maxsize=None)
def _load(model_name: str, renderer_name: str):
from transformers import AutoTokenizer
from renderers import create_renderer
tok = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
return tok, create_renderer(tok, renderer=renderer_name)
def pytest_generate_tests(metafunc):
if "br_model" in metafunc.fixturenames:
metafunc.parametrize(
"br_model,br_renderer_name",
_BRIDGE_MODELS,
ids=[m for m, _ in _BRIDGE_MODELS],
)
@pytest.fixture
def br_tokenizer(br_model, br_renderer_name):
return _load(br_model, br_renderer_name)[0]
@pytest.fixture
def br_renderer(br_model, br_renderer_name):
return _load(br_model, br_renderer_name)[1]
def _simulate_prior_turn(renderer):
"""Build a (prev_prompt, prev_completion) pair that a real rollout
would produce for a one-turn prior with a clean stop.
Strategy: render ``[system, user]`` with gen_prompt=True to get
prev_prompt, then render ``[system, user, assistant]`` without
gen_prompt, and take the diff as prev_completion. We then trim
prev_completion to the last close token so it matches what vLLM
actually hands back (vLLM stops at the close token and excludes the
trailing template scaffolding).
"""
prior = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi."},
]
assistant = [{"role": "assistant", "content": "Hello!"}]
prev_prompt = renderer.render_ids(prior, add_generation_prompt=True)
full_with_assistant = renderer.render_ids(
prior + assistant, add_generation_prompt=False
)
prev_completion = list(full_with_assistant[len(prev_prompt) :])
# Trim past any trailing scaffolding the template emits AFTER the
# close (e.g. chatml's trailing ``\n``). vLLM only returns tokens up
# to and including the close itself.
stop_ids = set(renderer.get_stop_token_ids())
last_close = -1
for i in range(len(prev_completion) - 1, -1, -1):
if prev_completion[i] in stop_ids:
last_close = i
break
if last_close >= 0:
prev_completion = prev_completion[: last_close + 1]
return prev_prompt, prev_completion
def test_bridge_extends_prev_verbatim_on_clean_stop(br_renderer, br_model):
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
new_messages = [{"role": "user", "content": "What's 2+2?"}]
bridged = br_renderer.bridge_to_next_turn(
prev_prompt, prev_completion, new_messages
)
assert bridged is not None, f"{br_model}: bridge returned None on clean stop"
prev = prev_prompt + prev_completion
assert bridged[: len(prev)] == prev, (
f"{br_model}: bridged does NOT extend prev_prompt + prev_completion"
)
assert len(bridged) > len(prev), (
f"{br_model}: bridge did not emit any extension tokens"
)
def test_bridge_rejects_assistant_in_extension(br_renderer):
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
assert (
br_renderer.bridge_to_next_turn(
prev_prompt,
prev_completion,
[{"role": "assistant", "content": "forbidden"}],
)
is None
)
def test_bridge_rejects_empty_prev_or_new(br_renderer):
_, prev_completion = _simulate_prior_turn(br_renderer)
assert (
br_renderer.bridge_to_next_turn(
[], prev_completion, [{"role": "user", "content": "x"}]
)
is None
)
prev_prompt, _ = _simulate_prior_turn(br_renderer)
assert br_renderer.bridge_to_next_turn(prev_prompt, prev_completion, []) is None
def test_bridge_synthesises_close_on_truncation(br_renderer, br_model):
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
# Drop the final close token to simulate a max_tokens truncation.
prev_completion_trunc = prev_completion[:-1] if prev_completion else prev_completion
if len(prev_completion_trunc) == 0:
pytest.skip(
f"{br_model}: simulated prior had no completion tokens — can't truncate"
)
bridged = br_renderer.bridge_to_next_turn(
prev_prompt,
prev_completion_trunc,
[{"role": "user", "content": "What's 2+2?"}],
)
assert bridged is not None, (
f"{br_model}: bridge returned None on truncation; expected synth-close"
)
prev_trunc = prev_prompt + prev_completion_trunc
assert bridged[: len(prev_trunc)] == prev_trunc, (
f"{br_model}: truncated-prior bridge did not keep prev tokens verbatim"
)
assert len(bridged) > len(prev_trunc), (
f"{br_model}: synth-close produced no extra tokens"
)
def test_bridge_extension_includes_new_message_text(
br_renderer, br_tokenizer, br_model
):
prev_prompt, prev_completion = _simulate_prior_turn(br_renderer)
new_messages = [{"role": "user", "content": "HELLO_SENTINEL_XYZ"}]
bridged = br_renderer.bridge_to_next_turn(
prev_prompt, prev_completion, new_messages
)
assert bridged is not None
ext = bridged[len(prev_prompt) + len(prev_completion) :]
decoded = br_tokenizer.decode(ext, skip_special_tokens=False)
assert "HELLO_SENTINEL_XYZ" in decoded, (
f"{br_model}: new-message content missing from extension; got {decoded!r}"
)
+70
View File
@@ -0,0 +1,70 @@
"""Barrage test: build_training_sample and build_trajectory_step.
Runs against every (model, renderer) pair.
"""
from renderers import build_training_sample, build_trajectory_step
def _expected(tokenizer, messages, **kwargs):
# Match the Renderer Protocol's default for add_generation_prompt
# (False); some tokenizers default it to True in their config
# (e.g. Kimi) which would otherwise flip the parity check on the flag
# alone. Callers wanting the gen prompt still pass it through.
kwargs.setdefault("add_generation_prompt", False)
result = tokenizer.apply_chat_template(
messages, tokenize=True, return_dict=False, **kwargs
)
if isinstance(result, dict):
return list(result["input_ids"])
if isinstance(result, str):
return list(tokenizer.encode(result, add_special_tokens=False))
return list(result)
def test_build_training_sample_ids_match(model_name, tokenizer, renderer):
"""Token IDs must match apply_chat_template."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
ids, mask = build_training_sample(
renderer, msgs, role_to_mask=lambda m: m["role"] == "assistant"
)
assert ids == _expected(tokenizer, msgs)
def test_build_training_sample_has_trainable_tokens(model_name, tokenizer, renderer):
"""At least some tokens should be marked for training."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
ids, mask = build_training_sample(
renderer, msgs, role_to_mask=lambda m: m["role"] == "assistant"
)
assert sum(mask) > 0
assert len(mask) == len(ids)
def test_build_trajectory_step_reconstructs_full(model_name, tokenizer, renderer):
"""prompt_ids + completion_ids must equal the full rendered sequence."""
prompt = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hi"},
]
completion = [{"role": "assistant", "content": "Hello!"}]
step = build_trajectory_step(renderer, prompt, completion)
full_ids = renderer.render_ids(prompt + completion)
assert step["prompt_ids"] + step["completion_ids"] == full_ids
def test_build_trajectory_step_masks(model_name, tokenizer, renderer):
"""Prompt mask all False, completion mask all True."""
prompt = [{"role": "user", "content": "Hi"}]
completion = [{"role": "assistant", "content": "Hello!"}]
step = build_trajectory_step(renderer, prompt, completion)
assert all(m is False for m in step["prompt_mask"])
assert all(m is True for m in step["completion_mask"])
assert len(step["completion_logprobs"]) == len(step["completion_ids"])
+129
View File
@@ -0,0 +1,129 @@
import base64
import numpy as np
import pytest
from renderers.base import ParsedResponse
from renderers.client import completions_request
class _FakeRenderer:
supports_tools = True
def render_ids(self, messages, *, tools=None, add_generation_prompt=False):
assert messages == [{"role": "user", "content": "hi"}]
assert tools == [{"type": "function", "function": {"name": "echo"}}]
assert add_generation_prompt is True
return [1, 2, 3]
def get_stop_token_ids(self):
return [99]
def parse_response(self, completion_ids: list[int]) -> ParsedResponse:
assert completion_ids == [7, 8]
return ParsedResponse(
content="done",
reasoning_content="think",
tool_calls=[
{
"function": {
"name": "echo",
"arguments": {"text": "hello"},
}
}
],
)
class _FakeClient:
def __init__(self):
self.calls = []
async def post(self, path, *, cast_to=dict, body=None):
self.calls.append({"path": path, "cast_to": cast_to, "body": body})
routed_experts = np.array([[[1]], [[2]]], dtype=np.int32)
return {
"usage": {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5},
"choices": [
{
"token_ids": [7, 8],
"logprobs": [-0.1, -0.2],
"finish_reason": "tool_calls",
"routed_experts": {
"data": base64.b85encode(routed_experts.tobytes()).decode(
"ascii"
),
"shape": list(routed_experts.shape),
},
}
],
}
@pytest.mark.asyncio
async def test_completions_request_builds_generate_body_and_parses_response():
client = _FakeClient()
result = await completions_request(
client=client,
renderer=_FakeRenderer(),
messages=[{"role": "user", "content": "hi"}],
model="test-model",
tools=[{"type": "function", "function": {"name": "echo"}}],
temperature=0.3,
max_completion_tokens=7,
extra_body={"min_tokens": 2},
)
assert len(client.calls) == 1
assert client.calls[0]["path"] == "/generate"
assert client.calls[0]["body"] == {
"model": "test-model",
"prompt_token_ids": [1, 2, 3],
"stop_token_ids": [99],
"temperature": 0.3,
"max_tokens": 7,
"min_tokens": 2,
}
assert result == {
"id": "",
"created": 0,
"model": "",
"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",
"usage": {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5},
"routed_experts": [[[1]], [[2]]],
}
class _NoRenderRenderer(_FakeRenderer):
def render_ids(self, messages, *, tools=None, add_generation_prompt=False):
raise AssertionError("prebuilt prompt ids should skip render_ids")
@pytest.mark.asyncio
async def test_completions_request_uses_prebuilt_prompt_ids_without_rendering():
client = _FakeClient()
result = await completions_request(
client=client,
renderer=_NoRenderRenderer(),
messages=[{"role": "user", "content": "hi"}],
model="test-model",
prompt_ids=[11, 12, 13],
)
assert client.calls[0]["body"]["prompt_token_ids"] == [11, 12, 13]
assert result["prompt_ids"] == [11, 12, 13]
+268
View File
@@ -0,0 +1,268 @@
"""GptOssRenderer parity vs ``openai-harmony``'s reference encoder.
Why this file exists
--------------------
HF's ``apply_chat_template`` for gpt-oss diverges from the model's
canonical wire format in small ways (trailing ``\\n\\n`` after developer
instructions; different layout for function-tool declarations). The
canonical format is what ``openai-harmony`` produces — vLLM uses that
encoder directly when serving gpt-oss, and it's what the model was
trained on.
So our ``GptOssRenderer`` matches harmony, not HF Jinja, and this file
checks that. ``test_render_ids`` skips gpt-oss for the same reason.
Each test mirrors the corresponding case in ``test_render_ids`` but
uses ``HarmonyEncoding.render_conversation_for_training`` as the
oracle.
"""
from __future__ import annotations
from datetime import datetime
import pytest
from openai_harmony import (
Conversation,
DeveloperContent,
HarmonyEncodingName,
Message as HarmonyMessage,
ReasoningEffort,
Role,
SystemContent,
ToolDescription,
load_harmony_encoding,
)
from renderers.gpt_oss import GptOssRenderer
from transformers import AutoTokenizer
GPT_OSS_MODEL = "openai/gpt-oss-20b"
DATE_FOR_PARITY = datetime.now().strftime("%Y-%m-%d")
@pytest.fixture(scope="module")
def tokenizer():
return AutoTokenizer.from_pretrained(GPT_OSS_MODEL)
@pytest.fixture(scope="module")
def renderer(tokenizer):
# Pin the date so the rendered preamble matches the harmony oracle
# built with the same fixed date.
return GptOssRenderer(tokenizer, conversation_start_date=DATE_FOR_PARITY)
@pytest.fixture(scope="module")
def encoder():
return load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
def _system_content() -> SystemContent:
return (
SystemContent.new()
.with_reasoning_effort(ReasoningEffort.MEDIUM)
.with_conversation_start_date(DATE_FOR_PARITY)
)
def _tool_description() -> ToolDescription:
return ToolDescription.new(
name="get_weather",
description="Get the current weather for a city",
parameters={
"type": "object",
"properties": {
"city": {"type": "string", "description": "The city name"},
},
"required": ["city"],
},
)
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "The city name"},
},
"required": ["city"],
},
},
}
]
def test_no_system_message(renderer, encoder):
"""A user-only conversation: only the auto-injected system preamble + user."""
msgs = [{"role": "user", "content": "Hello!"}]
got = renderer.render_ids(msgs, add_generation_prompt=False)
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.USER, "Hello!"),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_system_and_user(renderer, encoder):
"""The caller's first system message becomes the developer Instructions block."""
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hello!"},
]
got = renderer.render_ids(msgs, add_generation_prompt=False)
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(
Role.DEVELOPER,
DeveloperContent.new().with_instructions("You are helpful."),
),
HarmonyMessage.from_role_and_content(Role.USER, "Hello!"),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_terminal_assistant_uses_return(renderer, encoder):
"""Terminal assistant turn (no follow-up) closes with ``<|return|>``."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
got = renderer.render_ids(msgs, add_generation_prompt=False)
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.USER, "Hi"),
HarmonyMessage.from_role_and_content(Role.ASSISTANT, "Hello!").with_channel(
"final"
),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_tools_with_system(renderer, encoder):
"""Tools attach to the developer message alongside the instructions."""
msgs = [
{"role": "system", "content": "You are a weather assistant."},
{"role": "user", "content": "Weather?"},
]
got = renderer.render_ids(msgs, tools=TOOLS, add_generation_prompt=False)
dev = (
DeveloperContent.new()
.with_instructions("You are a weather assistant.")
.with_function_tools([_tool_description()])
)
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev),
HarmonyMessage.from_role_and_content(Role.USER, "Weather?"),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_tool_call_and_response(renderer, encoder):
"""Tool call → tool result → final assistant: each in its own harmony message."""
msgs = [
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "c1",
"function": {
"name": "get_weather",
"arguments": '{"city": "Paris"}',
},
}
],
},
{
"role": "tool",
"content": '{"temp": 20}',
"tool_call_id": "c1",
"name": "get_weather",
},
{"role": "assistant", "content": "It's 20 degrees in Paris."},
]
got = renderer.render_ids(msgs, tools=TOOLS, add_generation_prompt=False)
dev = DeveloperContent.new().with_function_tools([_tool_description()])
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.DEVELOPER, dev),
HarmonyMessage.from_role_and_content(Role.USER, "Weather in Paris?"),
HarmonyMessage.from_role_and_content(Role.ASSISTANT, '{"city": "Paris"}')
.with_channel("commentary")
.with_recipient("functions.get_weather"),
HarmonyMessage.from_author_and_content(
{"role": "tool", "name": "functions.get_weather"}, '{"temp": 20}'
)
.with_recipient("assistant")
.with_channel("commentary"),
HarmonyMessage.from_role_and_content(
Role.ASSISTANT, "It's 20 degrees in Paris."
).with_channel("final"),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_assistant_with_reasoning_content_strips_analysis(renderer, encoder):
"""Historical reasoning_content is stripped — harmony drops
analysis-channel messages from rendered history. The renderer matches
that behaviour, emitting only the final-channel text."""
msgs = [
{"role": "user", "content": "2+2?"},
{
"role": "assistant",
"content": "Four.",
"reasoning_content": "Two plus two is four.",
},
]
got = renderer.render_ids(msgs, add_generation_prompt=False)
# Oracle has no analysis message — it would be stripped anyway.
conv = Conversation.from_messages(
[
HarmonyMessage.from_role_and_content(Role.SYSTEM, _system_content()),
HarmonyMessage.from_role_and_content(Role.USER, "2+2?"),
HarmonyMessage.from_role_and_content(Role.ASSISTANT, "Four.").with_channel(
"final"
),
]
)
expected = encoder.render_conversation_for_training(conv)
assert got == expected
def test_generation_prompt(renderer):
"""``add_generation_prompt=True`` appends the analysis-channel start."""
msgs = [{"role": "user", "content": "Hi"}]
got = renderer.render_ids(msgs, add_generation_prompt=True)
no_genprompt = renderer.render_ids(msgs, add_generation_prompt=False)
# The trailing tokens should be: <|start|>assistant<|channel|>analysis<|message|>
suffix = got[len(no_genprompt) :]
decoded = renderer._tokenizer.decode(suffix) # noqa: SLF001
assert decoded == "<|start|>assistant<|channel|>analysis<|message|>", decoded
+173
View File
@@ -0,0 +1,173 @@
"""Unit tests for ``trim_to_turn_close`` and the bridge contract invariants
that every renderer's ``bridge_to_next_turn`` must uphold.
Cross-renderer parity is validated in test_render_ids.py and test_roundtrip.py;
this file exercises the shared primitive + protocol-level guarantees with a
fake renderer so we get fast, deterministic coverage of the tricky corners
(truncation opt-in, assistant-in-extension rejection, empty inputs).
"""
from renderers.base import (
ParsedResponse,
RenderedConversation,
reject_assistant_in_extension,
trim_to_turn_close,
)
def test_rendered_conversation_keeps_exact_token_tape():
parsed = ParsedResponse(content="done")
conv = RenderedConversation(
prompt_ids=[1, 2], messages=[{"role": "user", "content": "hi"}]
)
next_conv = conv.with_completion(
[3, 99], completion_logprobs=[-0.1, -0.2], parsed_completion=parsed
)
assert next_conv.token_ids == [1, 2, 3, 99]
assert next_conv.completion_logprobs == [-0.1, -0.2]
assert next_conv.parsed_completion is parsed
assert conv.completion_ids == []
# ---------------------------------------------------------------------------
# trim_to_turn_close
# ---------------------------------------------------------------------------
def test_trim_to_turn_close_trims_to_last_close_in_completion():
# prev = [1, 2] + [3, 99, 30] (stop token 99). Trim to the 99 boundary,
# drop the [30] that the model sampled after the stop token.
result = trim_to_turn_close([1, 2], [3, 99, 30], {99})
assert result == [1, 2, 3, 99]
def test_trim_to_turn_close_ignores_close_in_prompt():
# A stop-token id that happens to appear in prev_prompt (as structural
# template scaffolding) must not be treated as a turn boundary.
result = trim_to_turn_close([99, 1], [3, 4, 5], {99})
assert result is None
def test_trim_to_turn_close_synthesises_when_truncated():
# Truncation: no stop token in completion. With synthesize_close=99,
# append the synthetic close and return prev + [99].
result = trim_to_turn_close([1, 2], [3, 4, 5], {99}, synthesize_close=99)
assert result == [1, 2, 3, 4, 5, 99]
def test_trim_to_turn_close_returns_none_on_truncation_without_synth():
# Truncation without synth opt-in → caller falls back to fresh render.
result = trim_to_turn_close([1, 2], [3, 4, 5], {99})
assert result is None
def test_trim_to_turn_close_accepts_multiple_close_tokens():
# Multiple close tokens: pick the LAST one that appears in completion.
result = trim_to_turn_close([1], [3, 50, 4, 99, 30], {50, 99})
assert result == [1, 3, 50, 4, 99]
# ---------------------------------------------------------------------------
# reject_assistant_in_extension
# ---------------------------------------------------------------------------
def test_reject_assistant_in_extension_true_when_assistant_present():
assert reject_assistant_in_extension(
[{"role": "user", "content": "hi"}, {"role": "assistant", "content": "x"}]
)
def test_reject_assistant_in_extension_false_for_tool_user_only():
assert not reject_assistant_in_extension(
[{"role": "tool", "content": "result"}, {"role": "user", "content": "next"}]
)
# ---------------------------------------------------------------------------
# Contract tests against a minimal fake renderer
# ---------------------------------------------------------------------------
class _FakeRenderer:
"""Minimal Renderer whose bridge exercises the contract:
- Extension token is a single sentinel ID 42.
- ``<|im_end|>`` ≡ 99 is the canonical close.
"""
def __init__(self):
self._im_end = 99
def render_ids(self, messages, *, tools=None, add_generation_prompt=False):
raise NotImplementedError
def parse_response(self, token_ids):
return ParsedResponse(content="")
def get_stop_token_ids(self):
return [self._im_end]
def bridge_to_next_turn(
self,
previous_prompt_ids,
previous_completion_ids,
new_messages,
*,
tools=None,
):
if not previous_prompt_ids or not new_messages:
return None
if reject_assistant_in_extension(new_messages):
return None
previous_ids = trim_to_turn_close(
previous_prompt_ids,
previous_completion_ids,
{self._im_end},
synthesize_close=self._im_end,
)
if previous_ids is None:
return None
return previous_ids + [42]
def test_fake_bridge_extends_verbatim_on_clean_stop():
renderer = _FakeRenderer()
prev_prompt = [1, 2]
prev_completion = [3, 99]
result = renderer.bridge_to_next_turn(
prev_prompt, prev_completion, [{"role": "user", "content": "next"}]
)
assert result == [1, 2, 3, 99, 42]
assert (
result[: len(prev_prompt) + len(prev_completion)]
== prev_prompt + prev_completion
)
def test_fake_bridge_synthesises_on_truncation():
renderer = _FakeRenderer()
result = renderer.bridge_to_next_turn(
[1, 2], [3, 4, 5], [{"role": "user", "content": "next"}]
)
# Truncated prev; synth-close appends 99 then extension 42.
assert result == [1, 2, 3, 4, 5, 99, 42]
def test_fake_bridge_rejects_assistant_in_extension():
renderer = _FakeRenderer()
result = renderer.bridge_to_next_turn(
[1], [99], [{"role": "assistant", "content": "x"}]
)
assert result is None
def test_fake_bridge_rejects_empty_inputs():
renderer = _FakeRenderer()
assert (
renderer.bridge_to_next_turn([], [99], [{"role": "user", "content": "x"}])
is None
)
assert renderer.bridge_to_next_turn([1], [99], []) is None
+123
View File
@@ -0,0 +1,123 @@
"""Per-token attribution invariants for ``RenderedTokens.message_indices``.
Why this file exists
--------------------
The test barrage in ``test_render_ids`` checks token-id parity against
``apply_chat_template`` — useful, but only for token *bytes*. The
per-token attribution (``RenderedTokens.message_indices``) was never
covered, even though it directly drives the loss mask in
``build_training_sample``.
That gap surfaced through two real bugs:
- ``KimiK2Renderer.render``'s unknown-role fallback emitted the closing
``<|im_end|>`` with the post-normalisation index ``i`` instead of the
caller-relative ``oi``.
- ``KimiK25Renderer.render`` used the raw post-normalisation index
everywhere, shifting *every* index by one whenever auto-system
injection happened.
In both cases token IDs were unchanged (so render-parity still passed),
but ``message_indices`` pointed at wrong (or out-of-range) messages.
Tests in this file:
1. ``test_message_indices_in_range`` — parametrised via the conftest
matrix. Renders a no-system multi-role conversation and asserts the
contract: every entry in ``message_indices`` is either ``-1``
(structural scaffolding) or a valid caller-relative index, and every
caller message contributes at least one token. The no-system input
forces renderers that auto-inject default system messages
(Kimi K2 / K2.5 / K2.6) into the injection path — the path where the
post-normalisation index can shift away from the caller-relative one.
2. ``test_kimi_k2_unknown_role_message_indices`` — Kimi-K2-specific
regression: triggers auto-system injection plus an unknown role,
which is exactly the path the original bug was on. Without the fix
this test catches a stray index that points past the caller's last
message.
"""
from __future__ import annotations
def test_message_indices_in_range(model_name, renderer):
"""Every emitted token's ``message_indices`` must be in
``[-1, len(messages))``. ``-1`` is the documented sentinel for
structural scaffolding (e.g. trailing generation prompt).
Uses a no-system input so renderers that auto-inject default system
messages (Kimi K2 / K2.5 / K2.6) actually take the injection path —
that's the path where the post-normalisation index can shift away
from the caller-relative one and the bug surfaces."""
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
rendered = renderer.render(msgs, add_generation_prompt=True)
n = len(msgs)
assert len(rendered.token_ids) == len(rendered.message_indices), (
f"{model_name}: token_ids and message_indices length mismatch"
)
bad = [
(k, idx)
for k, idx in enumerate(rendered.message_indices)
if not (idx == -1 or 0 <= idx < n)
]
assert not bad, (
f"{model_name}: out-of-range message_indices entries (k, idx): {bad[:8]}"
)
# Every caller message must contribute at least one token.
seen = set(rendered.message_indices)
missing = [k for k in range(n) if k not in seen]
assert not missing, (
f"{model_name}: messages not represented in message_indices: {missing}"
)
def test_kimi_k2_unknown_role_message_indices():
"""Regression for the ``i`` vs ``oi`` mistake in
``KimiK2Renderer.render``'s unknown-role fallback. To surface, we
need (a) auto-system injection (no system in the input) and (b) an
unknown role hitting the fallback, and (c) the unknown role at the
*last* caller position so the post-normalisation index points past
the caller's input length.
Layout under test (caller indices on the right):
normalized[0] = auto-injected system (oi = -1)
normalized[1] = user (oi = 0)
normalized[2] = developer (unknown) (oi = 1) ← bug emits i=2
With the bug, ``<|im_end|>`` on the developer message is emitted
with the post-normalisation index ``i=2`` — out of range for a
caller list of length 2.
"""
from transformers import AutoTokenizer
from renderers import create_renderer
tok = AutoTokenizer.from_pretrained(
"moonshotai/Kimi-K2-Instruct", trust_remote_code=True
)
renderer = create_renderer(tok, renderer="auto")
msgs = [
{"role": "user", "content": "hi"},
# Unknown role hits the system-style fallback in KimiK2Renderer.render.
{"role": "developer", "content": "internal note"},
]
rendered = renderer.render(msgs)
n = len(msgs)
bad = [
(k, idx)
for k, idx in enumerate(rendered.message_indices)
if not (idx == -1 or 0 <= idx < n)
]
assert not bad, (
f"out-of-range message_indices on Kimi K2 unknown-role fallback "
f"(k, idx): {bad[:8]}"
)
+97
View File
@@ -0,0 +1,97 @@
"""Barrage test: renderer.parse_response() must correctly extract
content, reasoning_content, and tool_calls from completion tokens.
Runs against every (model, renderer) pair.
"""
from functools import lru_cache
from renderers import create_renderer
from transformers import AutoTokenizer
@lru_cache
def _qwen3_vl():
tokenizer = AutoTokenizer.from_pretrained(
"Qwen/Qwen3-VL-4B-Instruct", trust_remote_code=True
)
renderer = create_renderer(tokenizer, renderer="auto")
return tokenizer, renderer
def test_parse_simple_content(model_name, tokenizer, renderer):
"""Plain content, no thinking."""
text = "Hello there!"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert "Hello" in parsed.content
def test_parse_thinking_and_content(model_name, tokenizer, renderer):
"""Content with <think>reasoning</think> block."""
text = "Let me think about this.\n</think>\n\nThe answer is 42."
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
# Should extract reasoning or at least not crash
assert (
"42" in parsed.content
or "think" in (parsed.reasoning_content or "").lower()
or parsed.content
)
def test_parse_empty_completion(model_name, tokenizer, renderer):
"""Empty completion should not crash."""
parsed = renderer.parse_response([])
assert parsed.content is not None
def test_parse_response_returns_parsed_response(model_name, tokenizer, renderer):
"""Return type must have content, reasoning_content, tool_calls."""
ids = tokenizer.encode("Hello!", add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert hasattr(parsed, "content")
assert hasattr(parsed, "reasoning_content")
assert hasattr(parsed, "tool_calls")
def test_qwen3_vl_parse_json_tool_call():
tokenizer, renderer = _qwen3_vl()
text = (
'Need a tool.\n<tool_call>\n{"name": "get_weather", '
'"arguments": {"city": "Paris"}}\n</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"}}}
]
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.).
"""
tokenizer, renderer = _qwen3_vl()
# Note the trailing comma — malformed JSON
text = (
'<tool_call>\n{"name": "get_weather", '
'"arguments": {"city": "Paris",}}\n</tool_call>'
)
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 "get_weather" in parsed.content
+138
View File
@@ -0,0 +1,138 @@
"""Robustness tests for parse_response — edge cases, truncation, malformed output.
These test that parse_response never crashes and returns sensible results
even with adversarial or truncated model output.
"""
from renderers.base import ParsedResponse
# ── Truncation ───────────────────────────────────────────────────────
def test_truncated_mid_thinking(model_name, tokenizer, renderer):
"""Model was cut off mid-thinking (no </think> found)."""
text = "Let me think about this carefully. The problem requires"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert isinstance(parsed, ParsedResponse)
# Content or reasoning should contain the text
assert parsed.content or parsed.reasoning_content
def test_truncated_after_think_tag(model_name, tokenizer, renderer):
"""Model emitted <think> but was cut off before </think>."""
text = "<think>Let me reason about"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert isinstance(parsed, ParsedResponse)
def test_truncated_mid_tool_call(model_name, tokenizer, renderer):
"""Model started a tool call but was cut off."""
text = 'Checking the weather.\n<tool_call>\n{"name": "get'
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert isinstance(parsed, ParsedResponse)
# Should recover content before the tool call
assert "Checking" in parsed.content or parsed.content == ""
def test_empty_completion(model_name, tokenizer, renderer):
"""Empty token list."""
parsed = renderer.parse_response([])
assert isinstance(parsed, ParsedResponse)
assert parsed.content is not None
def test_single_eos_token(model_name, tokenizer, renderer):
"""Just an EOS token."""
stop_ids = renderer.get_stop_token_ids()
if stop_ids:
parsed = renderer.parse_response(stop_ids[:1])
assert isinstance(parsed, ParsedResponse)
# ── Thinking edge cases ──────────────────────────────────────────────
def test_empty_thinking_block(model_name, tokenizer, renderer):
"""<think></think> with no content (common pattern)."""
text = "<think></think>Hello!"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert "Hello" in parsed.content
def test_thinking_with_newlines(model_name, tokenizer, renderer):
"""Thinking block with various newline patterns."""
text = "Step 1: Calculate\nStep 2: Verify\n</think>\n\nThe answer is 42."
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert "42" in parsed.content
def test_content_only_no_thinking(model_name, tokenizer, renderer):
"""Plain content with no thinking markers."""
text = "Hello! How can I help you today?"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert "Hello" in parsed.content
assert parsed.tool_calls is None
# ── Tool call edge cases ─────────────────────────────────────────────
def test_tool_call_with_complex_json(model_name, tokenizer, renderer):
"""Tool call with nested JSON arguments."""
# This is a generic test — the exact format varies per model
text = "Here are the results."
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert isinstance(parsed, ParsedResponse)
def test_content_with_special_chars(model_name, tokenizer, renderer):
"""Content containing angle brackets, quotes, etc."""
text = 'The formula is x < y and a > b. Use "quotes" freely.'
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert parsed.content # Should not crash on angle brackets
def test_very_long_content(model_name, tokenizer, renderer):
"""Long content string."""
text = "word " * 500
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
assert len(parsed.content) > 100
# ── Return type guarantees ───────────────────────────────────────────
def test_content_is_always_string(model_name, tokenizer, renderer):
"""content must always be a string, never None."""
for text in ["Hello", "", "<think></think>", "<think>x</think>"]:
ids = tokenizer.encode(text, add_special_tokens=False) if text else []
parsed = renderer.parse_response(ids)
assert isinstance(parsed.content, str)
def test_reasoning_is_string_or_none(model_name, tokenizer, renderer):
"""reasoning_content must be str or None."""
text = "Some text"
ids = tokenizer.encode(text, add_special_tokens=False)
parsed = renderer.parse_response(ids)
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."""
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
)
+109
View File
@@ -0,0 +1,109 @@
"""Tests for the pluggable ToolParser / ReasoningParser registry."""
from __future__ import annotations
import pytest
from transformers import AutoTokenizer
from renderers.parsers import (
REASONING_PARSERS,
TOOL_PARSERS,
Qwen3ToolParser,
ThinkTextReasoningParser,
get_reasoning_parser,
get_tool_parser,
)
def test_registries_nonempty():
assert "qwen3" in TOOL_PARSERS
assert "qwen3.5" in TOOL_PARSERS
assert "glm" in TOOL_PARSERS
assert "deepseek_v3" in TOOL_PARSERS
assert "think" in REASONING_PARSERS
def test_unknown_parser_errors():
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B", trust_remote_code=True)
with pytest.raises(ValueError, match="Unknown tool_parser"):
get_tool_parser("does-not-exist", tok)
with pytest.raises(ValueError, match="Unknown reasoning_parser"):
get_reasoning_parser("does-not-exist", tok)
def test_qwen3_tool_parser_roundtrip():
"""Tokenize a Hermes-style tool call, parse it back out."""
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B", trust_remote_code=True)
parser = get_tool_parser("qwen3", tok)
assert isinstance(parser, Qwen3ToolParser)
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"}
# 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
assert "<tool_call>" not in content_text
def test_qwen3_tool_parser_no_tool_call():
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B", trust_remote_code=True)
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 content_ids == list(ids)
def test_think_reasoning_parser_extracts_block():
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B", trust_remote_code=True)
parser = get_reasoning_parser("think", tok)
assert isinstance(parser, ThinkTextReasoningParser)
reasoning, content = parser.extract("<think>let me think</think>the answer")
assert reasoning == "let me think"
assert content == "the answer"
def test_think_reasoning_parser_no_block():
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B", trust_remote_code=True)
parser = get_reasoning_parser("think", tok)
reasoning, content = parser.extract("no reasoning here")
assert reasoning is None
assert content == "no reasoning here"
def test_default_renderer_uses_parsers():
"""DefaultRenderer + parsers should extract tool calls and reasoning."""
from renderers import create_renderer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B", trust_remote_code=True)
renderer = create_renderer(
tok, renderer="default", tool_parser="qwen3", reasoning_parser="think"
)
assert renderer.supports_tools is True
completion = '<think>think</think>ok\n<tool_call>\n{"name": "f", "arguments": {}}\n</tool_call>'
ids = tok.encode(completion, add_special_tokens=False)
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"
def test_default_renderer_without_parsers_is_backward_compatible():
"""Without parsers, DefaultRenderer still does basic <think> extraction."""
from renderers import create_renderer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B", trust_remote_code=True)
renderer = create_renderer(tok, renderer="default")
assert renderer.supports_tools is False
ids = tok.encode("<think>r</think>a", add_special_tokens=False)
parsed = renderer.parse_response(list(ids))
assert parsed.reasoning_content == "r"
assert parsed.content == "a"
assert parsed.tool_calls is None
+397
View File
@@ -0,0 +1,397 @@
"""Barrage test: renderer.render_ids() must match tokenizer.apply_chat_template().
Every test case runs against every (model, renderer) pair from conftest.
If a test passes, the renderer is token-for-token correct for that case.
GPT-OSS is auto-skipped here by ``conftest._skip_gpt_oss_for_hf_parity_tests``
since our GptOssRenderer matches openai-harmony / vLLM, not the HF Jinja
template. See ``test_gpt_oss_harmony_parity.py`` for harmony parity coverage.
"""
from functools import lru_cache
from renderers import create_renderer
from transformers import AutoTokenizer
def _expected(tokenizer, messages, **kwargs):
# Match the Renderer Protocol's default for add_generation_prompt (False)
# — some tokenizers (e.g. Kimi's) default it to True in their config,
# which would otherwise make this parity check fail on the flag alone.
# Callers that explicitly want the gen prompt still pass it through.
kwargs.setdefault("add_generation_prompt", False)
result = tokenizer.apply_chat_template(
messages, tokenize=True, return_dict=False, **kwargs
)
if isinstance(result, dict):
return list(result["input_ids"])
if isinstance(result, str):
# Some tokenizers return str even with tokenize=True; force encode
return list(tokenizer.encode(result, add_special_tokens=False))
return list(result)
# ── Basic messages ───────────────────────────────────────────────────
def test_system_and_user(model_name, tokenizer, renderer):
msgs = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hello!"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_single_turn(model_name, tokenizer, renderer):
msgs = [
{"role": "system", "content": "You are a math tutor."},
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_no_system_message(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Hello!"},
{"role": "assistant", "content": "Hi there!"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_multi_turn(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "A"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "C"},
{"role": "assistant", "content": "D"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_multi_turn_many_rounds(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "A"},
{"role": "assistant", "content": "B"},
{"role": "user", "content": "C"},
{"role": "assistant", "content": "D"},
{"role": "user", "content": "E"},
{"role": "assistant", "content": "F"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_empty_assistant_content(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": ""},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
# ── Thinking / reasoning ────────────────────────────────────────────
def test_reasoning_content_field(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "reasoning_content": "Simple arithmetic", "content": "4"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_thinking_multi_turn(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "reasoning_content": "greeting", "content": "Hi!"},
{"role": "user", "content": "Bye"},
{"role": "assistant", "reasoning_content": "farewell", "content": "Goodbye!"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
# ── Tool definitions ─────────────────────────────────────────────────
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "The city name"},
},
"required": ["city"],
},
},
}
]
def test_tools_with_system(model_name, tokenizer, renderer):
msgs = [
{"role": "system", "content": "You are a weather assistant."},
{"role": "user", "content": "Weather?"},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_tools_without_system(model_name, tokenizer, renderer):
msgs = [{"role": "user", "content": "Weather?"}]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
# ── Tool calls ───────────────────────────────────────────────────────
def test_tool_call_with_content(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "Let me check.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_tool_call_no_content(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
]
try:
expected = _expected(tokenizer, msgs, tools=TOOLS)
except TypeError as exc:
# Qwen3-VL upstream chat-template bug. The assistant branch only
# checks `is string` and then unconditionally iterates the else,
# so `content=None` raises TypeError on `for x in None`:
#
# {%- if message.content is string %}
# {{- message.content }}
# {%- else %}
# {%- for content_item in message.content %} ← crash
# {%- if 'text' in content_item %}
# {{- content_item.text }}
# ...
#
# Same pattern in the user-role branch. The fix upstream would be
# `{%- elif message.content %}` to skip iteration on falsy content.
# Until Qwen ships a fixed template this is xfail; the imperative
# xfail auto-promotes to xpass when upstream is fixed.
import pytest
pytest.xfail(f"{model_name}: apply_chat_template raised {exc!r}")
assert renderer.render_ids(msgs, tools=TOOLS) == expected
def test_multiple_tool_calls(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Weather in Paris and London?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}},
{"function": {"name": "get_weather", "arguments": {"city": "London"}}},
],
},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
# ── Tool responses ───────────────────────────────────────────────────
def test_single_tool_response(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Weather?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
{"role": "tool", "content": '{"temp": 20}'},
{"role": "assistant", "content": "It's 20 degrees."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_tool_response_with_name(model_name, tokenizer, renderer):
"""Tool message carries `name` (function name). Pins the renderer contract
that if `name` is supplied it gets rendered (e.g., GPT-OSS Harmony emits
`<|start|>functions.{name} to=assistant`). Catches regressions where a
renderer silently drops the field."""
msgs = [
{"role": "user", "content": "Weather in Paris?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
{"role": "tool", "name": "get_weather", "content": '{"temp": 20}'},
{"role": "assistant", "content": "It's 20 degrees."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_consecutive_tool_responses(model_name, tokenizer, renderer):
msgs = [
{"role": "user", "content": "Weather in Paris and London?"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}},
{"function": {"name": "get_weather", "arguments": {"city": "London"}}},
],
},
{"role": "tool", "content": '{"temp": 20}'},
{"role": "tool", "content": '{"temp": 15}'},
{"role": "assistant", "content": "Paris: 20, London: 15."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
# ── Full tool cycle ──────────────────────────────────────────────────
def test_full_tool_cycle(model_name, tokenizer, renderer):
msgs = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the weather in Paris?"},
{
"role": "assistant",
"content": "Let me check.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
{"role": "tool", "content": '{"temp": 20, "condition": "sunny"}'},
{"role": "assistant", "content": "It is 20 degrees and sunny."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
def test_multi_step_tool_cycle(model_name, tokenizer, renderer):
"""Two rounds of tool calling."""
msgs = [
{"role": "user", "content": "Compare weather in Paris and London"},
{
"role": "assistant",
"content": "Let me check Paris.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}
],
},
{"role": "tool", "content": '{"temp": 20}'},
{
"role": "assistant",
"content": "Now London.",
"tool_calls": [
{"function": {"name": "get_weather", "arguments": {"city": "London"}}}
],
},
{"role": "tool", "content": '{"temp": 15}'},
{"role": "assistant", "content": "Paris: 20, London: 15."},
]
assert renderer.render_ids(msgs, tools=TOOLS) == _expected(
tokenizer, msgs, tools=TOOLS
)
# ── Qwen3-VL routing ────────────────────────────────────────────────────
@lru_cache
def _qwen3_vl():
tokenizer = AutoTokenizer.from_pretrained(
"Qwen/Qwen3-VL-4B-Instruct", trust_remote_code=True
)
renderer = create_renderer(tokenizer, renderer="auto")
return tokenizer, renderer
def test_qwen3_vl_auto_renderer():
_, renderer = _qwen3_vl()
assert type(renderer).__name__ == "Qwen3VLRenderer"
# ── Kimi K2.5: tool_declare message handling ──────────────────────────
@lru_cache
def _kimi_k25():
tokenizer = AutoTokenizer.from_pretrained(
"moonshotai/Kimi-K2.5", trust_remote_code=True
)
renderer = create_renderer(tokenizer, renderer="auto")
return tokenizer, renderer
def test_kimi_k2_inline_think_tags_render_verbatim():
"""Kimi K2's chat template emits assistant ``content`` verbatim — including
any inline ``<think>...</think>`` tags. The renderer must not strip them.
Regression for a bug where ``_extract_thinking`` mutated content by
splitting out ``<think>...</think>`` and then discarded the extracted
reasoning, producing tokens that disagreed with ``apply_chat_template``.
"""
tokenizer = AutoTokenizer.from_pretrained(
"moonshotai/Kimi-K2-Instruct", trust_remote_code=True
)
renderer = create_renderer(tokenizer, renderer="auto")
msgs = [
{"role": "user", "content": "hi"},
{"role": "assistant", "content": "<think>secret</think>visible"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
def test_kimi_k25_tool_declare_message_without_tools_param():
"""``role=tool_declare`` messages must be emitted from their content when
no ``tools=`` arg is passed — not silently dropped.
Regression for the Kimi K2.5 chat template: the template's per-message loop
sends every message (including ``tool_declare``) through ``set_roles`` +
``render_content``, regardless of the ``tools`` parameter. The renderer
used to ``continue`` past ``tool_declare`` messages, dropping them.
"""
tokenizer, renderer = _kimi_k25()
msgs = [
{"role": "tool_declare", "content": "function calc(x: number): number;"},
{"role": "user", "content": "use the calc tool"},
]
assert renderer.render_ids(msgs) == _expected(tokenizer, msgs)
+343
View File
@@ -0,0 +1,343 @@
"""Render → parse round-trip.
Core renderer invariant: if you render
``[user, assistant(content=X, reasoning=Y, tool_calls=[T])]`` to tokens,
extract the assistant's completion slice, and feed it through
``parse_response``, you should get back an equivalent structured message.
Catches asymmetries between a renderer's emit path and its parse path —
bugs that slip past render-parity tests (which only check vs
apply_chat_template) and parse-robustness tests (which feed crafted text,
not rendered output).
Parametrizes over a wider model list than the shared conftest barrage
(which is kept conservative because several newer renderers still
disagree with apply_chat_template in complex tool-cycle edge cases).
The roundtrip invariant is renderer-self-consistent so it can tolerate
those gaps while still giving per-renderer coverage of the emit/parse
pair.
"""
from __future__ import annotations
import json
from functools import lru_cache
from typing import Any
import pytest
# (HuggingFace model name, renderer name or "auto"). These are the
# renderers we actively rely on; expand as new ones get hand-coded.
_ROUNDTRIP_MODELS = [
("Qwen/Qwen3-8B", "auto"),
("Qwen/Qwen3.5-9B", "auto"),
("Qwen/Qwen3.6-35B-A3B", "auto"),
("Qwen/Qwen3-VL-4B-Instruct", "auto"),
("zai-org/GLM-5", "auto"),
("zai-org/GLM-5.1", "auto"),
("zai-org/GLM-4.7-Flash", "auto"),
("THUDM/GLM-4.5-Air", "auto"),
("MiniMaxAI/MiniMax-M2.5", "auto"),
("moonshotai/Kimi-K2-Instruct", "auto"),
("moonshotai/Kimi-K2.5", "auto"),
("moonshotai/Kimi-K2.6", "auto"),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "auto"),
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "auto"),
("openai/gpt-oss-20b", "gpt_oss"),
("Qwen/Qwen2.5-0.5B-Instruct", "default"),
]
@lru_cache(maxsize=None)
def _load_renderer(model_name: str, renderer_name: str):
from transformers import AutoTokenizer
from renderers import create_renderer
tok = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
return tok, create_renderer(tok, renderer=renderer_name)
def pytest_generate_tests(metafunc):
# Local parametrization only takes effect for tests in this file that
# declare these fixture names — conftest-level parametrization still
# applies to every other test module.
if "rt_model" in metafunc.fixturenames:
metafunc.parametrize(
"rt_model,rt_renderer_name",
_ROUNDTRIP_MODELS,
ids=[m for m, _ in _ROUNDTRIP_MODELS],
)
@pytest.fixture
def rt_tokenizer(rt_model, rt_renderer_name):
return _load_renderer(rt_model, rt_renderer_name)[0]
@pytest.fixture
def rt_renderer(rt_model, rt_renderer_name):
return _load_renderer(rt_model, rt_renderer_name)[1]
PROMPT = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is 2+2?"},
]
def _extract_assistant_tokens(renderer, prompt, assistant_msg):
"""Return the tokens the assistant turn contributes to the full render.
We slice at ``len(render(prompt, add_generation_prompt=False))`` rather
than walking the common prefix against ``add_generation_prompt=True``:
for chatml the two agree, but harmony's gen-prompt opens channel
``analysis`` while the same assistant rendered in-sequence uses
channel ``final``, so common-prefix walking would land inside the
channel name and drop the ``<|start|>assistant<|channel|>``
scaffolding the parser relies on.
"""
prompt_ids = renderer.render_ids(prompt, add_generation_prompt=False)
full_ids = renderer.render_ids(prompt + [assistant_msg])
return full_ids[len(prompt_ids) :]
def _normalize_args(args: Any) -> Any:
"""Normalize tool-call arguments to a dict for cross-renderer comparison.
Some parsers hand back 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
# ── content-only ──────────────────────────────────────────────────────
def test_roundtrip_content_only(rt_model, rt_tokenizer, rt_renderer):
"""Plain response, no thinking, no tool calls."""
msg = {"role": "assistant", "content": "Four."}
completion_ids = _extract_assistant_tokens(rt_renderer, PROMPT, msg)
parsed = rt_renderer.parse_response(completion_ids)
assert "Four" in parsed.content, f"{rt_model}: lost content, got {parsed.content!r}"
assert not parsed.tool_calls, (
f"{rt_model}: spurious tool_calls={parsed.tool_calls!r}"
)
# ── reasoning ─────────────────────────────────────────────────────────
def test_roundtrip_reasoning_and_content(rt_model, rt_tokenizer, rt_renderer):
"""Assistant with reasoning_content + visible content — reasoning must
survive the round trip for templates that emit reasoning blocks."""
msg = {
"role": "assistant",
"content": "The answer is four.",
"reasoning_content": "Two plus two equals four.",
}
completion_ids = _extract_assistant_tokens(rt_renderer, PROMPT, msg)
parsed = rt_renderer.parse_response(completion_ids)
assert "four" in parsed.content.lower(), (
f"{rt_model}: lost content, got {parsed.content!r}"
)
# DefaultRenderer may not carry reasoning unless the template explicitly
# emits a <think> block; hand-coded renderers always should.
if parsed.reasoning_content is not None:
assert "equals four" in parsed.reasoning_content.lower(), (
f"{rt_model}: reasoning mangled, got {parsed.reasoning_content!r}"
)
# ── tool calls ────────────────────────────────────────────────────────
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."""
if renderer_name == "default":
pytest.skip(
"DefaultRenderer requires an explicit tool_parser to parse tool "
"calls; not exercised in the round-trip matrix."
)
def test_roundtrip_single_tool_call(
rt_model, rt_renderer_name, rt_tokenizer, rt_renderer
):
_maybe_skip_tool_calls(rt_renderer_name)
msg = {
"role": "assistant",
"content": "",
"tool_calls": [
{
# Kimi's parser extracts the function name from the id
# field ("functions.{name}:{idx}") — other renderers ignore
# the id shape, so this form is compatible across the matrix.
"id": "functions.get_weather:0",
"function": {
"name": "get_weather",
"arguments": '{"city": "Tokyo"}',
},
}
],
}
completion_ids = _extract_assistant_tokens(rt_renderer, PROMPT, msg)
parsed = rt_renderer.parse_response(completion_ids)
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}"
)
def test_roundtrip_multiple_tool_calls(
rt_model, rt_renderer_name, rt_tokenizer, rt_renderer
):
"""Parsers that loop over ``<tool_call>…</tool_call>`` blocks can
silently drop the second one; this test catches that."""
_maybe_skip_tool_calls(rt_renderer_name)
msg = {
"role": "assistant",
"content": "",
"tool_calls": [
{
# Kimi's parser extracts the function name from the id
# field ("functions.{name}:{idx}") — other renderers ignore
# the id shape, so this form is compatible across the matrix.
"id": "functions.get_weather:0",
"function": {
"name": "get_weather",
"arguments": '{"city": "Tokyo"}',
},
},
{
"id": "functions.get_time:1",
"function": {
"name": "get_time",
"arguments": '{"zone": "JST"}',
},
},
],
}
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, (
f"{rt_model}: expected 2 tool_calls, got {parsed.tool_calls!r}"
)
names = [tc["function"]["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"
}
# ── byte-exact re-render invariant ─────────────────────────────────────
#
# When the chat template round-trips content/reasoning verbatim (no
# separator between `</think>` and content), the parser MUST preserve
# whitespace at the `</think>` boundary. Otherwise parse→re-render
# drops a `\n` token, the rendered assistant message BPE-realigns by
# ~O(tens of tokens), and multi-turn RL's extension property breaks at
# step 2+ on every rollout.
#
# Narrow scope: exercise the parser contract directly so this test
# surfaces only the strip-whitespace regression, not any of the pre-
# existing hand-coded-renderer round-trip quirks.
def test_think_reasoning_parser_preserves_boundary_whitespace():
"""ThinkTextReasoningParser (used when `reasoning_parser='think'`) must
preserve whitespace directly on either side of `</think>` for
byte-exact round-trip through templates like GLM-4.5 that emit
reasoning and content back-to-back with no separator.
Regression: the parser used to call `.strip()` and `.lstrip('\\n')`,
which drops the newline the model naturally emits after `</think>`,
breaking multi-turn trajectory token extension.
"""
from renderers.parsers import ThinkTextReasoningParser
parser = ThinkTextReasoningParser(tokenizer=None)
# Model naturally emits `\n<think>...</think>\nCONTENT` — the \n on
# each side of `</think>` is load-bearing.
reasoning, content = parser.extract(
"\n<think>Reason text</think>\nThe answer is four."
)
assert reasoning == "Reason text", f"reasoning boundary stripped: {reasoning!r}"
assert content.startswith("\n"), (
f"content lost leading '\\n' after </think>: {content!r}"
)
assert content == "\nThe answer is four.", f"content mangled: {content!r}"
def test_think_reasoning_parser_preserves_trailing_reasoning_whitespace():
"""If the model put a `\\n` BEFORE `</think>`, that belongs in
reasoning_content — the template renders it as part of the `<think>`
block and dropping it shifts downstream tokens.
"""
from renderers.parsers import ThinkTextReasoningParser
parser = ThinkTextReasoningParser(tokenizer=None)
reasoning, content = parser.extract(
"<think>Line one\nLine two\n</think>Final answer."
)
assert reasoning == "Line one\nLine two\n", (
f"lost trailing '\\n' inside <think>: {reasoning!r}"
)
assert content == "Final answer.", f"content mangled: {content!r}"
def test_default_renderer_fallback_parser_preserves_boundary_whitespace(
rt_tokenizer,
):
"""DefaultRenderer's built-in fallback (when no explicit reasoning
parser is configured) must apply the same whitespace-preservation
rule so models with `<think>`-emitting templates round-trip.
Uses whatever `rt_tokenizer` is available but skips if the tokenizer
can't round-trip `<think>` tags cleanly — we only care about the
parser's text handling here.
"""
from renderers.default import DefaultRenderer
renderer = DefaultRenderer(rt_tokenizer, tool_parser=None, reasoning_parser=None)
# Encode `<think>reason</think>\nvisible` as text and run through
# parse_response. We don't need the template to emit `<think>` here
# — we only exercise the parser's text-splitting logic.
text = "<think>reason</think>\nvisible"
ids = rt_tokenizer.encode(text, add_special_tokens=False)
# If decoding doesn't round-trip the `\n`, the test is N/A for this
# tokenizer — this is a parser-level invariant, not a tokenizer one.
if rt_tokenizer.decode(ids, skip_special_tokens=False) != text:
pytest.skip("tokenizer decode does not round-trip the fixture text")
parsed = renderer.parse_response(ids)
assert parsed.reasoning_content == "reason", (
f"reasoning stripped beyond `</think>`: {parsed.reasoning_content!r}"
)
assert (parsed.content or "").startswith("\n"), (
f"content lost leading '\\n' after `</think>`: {parsed.content!r}"
)
Generated
+1231
View File
File diff suppressed because it is too large Load Diff