Image-Text-to-Text
Transformers
Safetensors
qwen4_moe
autoround
rtn
gptq
w4a16
Mixture of Experts
qwen4
vllm
4-bit precision
Run this model with HF Jobs
Run OpenTensorLab/Qwen4-35B-A3B-GPTQ on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/OpenTensorLab/Qwen4-35B-A3B-GPTQ. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/OpenTensorLab/Qwen4-35B-A3B-GPTQ on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/OpenTensorLab/Qwen4-35B-A3B-GPTQ. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Instructions to use OpenTensorLab/Qwen4-35B-A3B-GPTQ with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenTensorLab/Qwen4-35B-A3B-GPTQ with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="OpenTensorLab/Qwen4-35B-A3B-GPTQ")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("OpenTensorLab/Qwen4-35B-A3B-GPTQ") model = AutoModelForMultimodalLM.from_pretrained("OpenTensorLab/Qwen4-35B-A3B-GPTQ", device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use OpenTensorLab/Qwen4-35B-A3B-GPTQ with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "OpenTensorLab/Qwen4-35B-A3B-GPTQ" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenTensorLab/Qwen4-35B-A3B-GPTQ", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/OpenTensorLab/Qwen4-35B-A3B-GPTQ
- SGLang
How to use OpenTensorLab/Qwen4-35B-A3B-GPTQ with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "OpenTensorLab/Qwen4-35B-A3B-GPTQ" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenTensorLab/Qwen4-35B-A3B-GPTQ", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "OpenTensorLab/Qwen4-35B-A3B-GPTQ" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenTensorLab/Qwen4-35B-A3B-GPTQ", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use OpenTensorLab/Qwen4-35B-A3B-GPTQ with Docker Model Runner:
docker model run hf.co/OpenTensorLab/Qwen4-35B-A3B-GPTQ
File size: 32,745 Bytes
fb012f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 | """Qwen4 chat protocol encoder.
Input : OpenAI-compatible messages (+ optional ``tools``).
Output : an ordered list of ``EncodeSegment`` -- each a chunk of text tagged
with ``allow_special``. Concatenating the segment
texts yields the string; tokenizing each segment
with its own ``allow_special`` flag yields the training token ids with
exact control-token control.
Why segments instead of a flat string + ``allowed_special="all"``?
Only protocol delimiters use ``allow_special=True``; data cannot inject
control tokens.
The module has no hard dependency on the tokenizer: segment construction is
pure Python. Tokenization is done lazily through any object exposing
``tokenize_segment(text, allow_special=bool)`` (see
``tokenization_qwen4.Qwen4Tokenizer``).
"""
from __future__ import annotations
import copy
import json
import re
from collections.abc import Iterable
from dataclasses import dataclass
from typing import Any, ClassVar, Literal, Protocol, TypeAlias, runtime_checkable
# PUBLIC API (stable).
#
# Construct:
# enc = Qwen4ChatEncoder(tokenizer)
#
# Encode (OpenAI-compatible messages + tools -> ...):
# enc.encode(msgs, tools, *, add_generation_prompt=False)
# -> list[EncodeSegment] # the IR
# enc.render_tokens(msgs, tools, **opts) -> list[int] # for inference
# enc.render_tokens_and_labels(msgs, tools, **opts) -> (ids, labels) # for training
# enc.render_string(msgs, tools, **opts) -> str # for debug
#
# From the IR (when you already hold segments, e.g. after inspection):
# enc.to_tokens(segments) -> list[int]
# enc.to_tokens_and_labels(segments) -> (ids, labels)
#
# Parse an assistant body:
# parse_assistant_response_ids(token_ids, tokenizer)
# -> {reasoning_content, content, tool_calls}
#
# Labels use IGNORE_INDEX on non-trainable (context) tokens.
# The tokenizer is any object satisfying `TokenizerProtocol`.
__all__ = [
"IGNORE_INDEX",
"EncodeSegment",
"Qwen4ChatEncoder",
"TokenizerProtocol",
"parse_assistant_response_ids",
]
# canonical control-token strings
IM_START = "<|im_start|>"
IM_END = "<|im_end|>"
TOOL_CALL_O, TOOL_CALL_C = "<tool_call>", "</tool_call>"
TOOL_RESP_O, TOOL_RESP_C = "<tool_response>", "</tool_response>" # no longer in use
THINK_O, THINK_C = "<think>", "</think>"
# vision / audio delimiters
VISION_START, VISION_END, IMAGE_PAD, VIDEO_PAD = (
"<|vision_start|>",
"<|vision_end|>",
"<|image_pad|>",
"<|video_pad|>",
)
AUDIO_START, AUDIO_END, AUDIO_PAD = "<|audio_start|>", "<|audio_end|>", "<|audio_pad|>"
IGNORE_INDEX = -100 # this is used in pytorch by default
@runtime_checkable
class TokenizerProtocol(Protocol):
"""Contract the encoder needs from a tokenizer.
`allow_special=True` -> recognize special-token strings (scaffolding).
`allow_special=False` -> encode ordinarily; special-looking substrings stay
plain bytes and are never treated as control tokens.
(`tokenization_qwen4.Qwen4Tokenizer` satisfies this.)
"""
def tokenize_segment(
self, text: str, *, allow_special: bool = False
) -> list[int]: ...
def decode(self, token_ids: int | list[int], **kwargs) -> str: ...
ReasoningEffortType: TypeAlias = (
Literal["xhigh", "high", "low", "off"] | None
) # allowd reasoning effort values
@dataclass
class EncodeSegment:
"""One contiguous chunk of the rendered conversation.
text : the raw string.
allow_special: recognize control tokens; False for data.
trainable : whether these tokens contribute to the training loss.
tag : provenance label, for debugging / visualization.
"""
text: str
allow_special: bool
trainable: bool = False
tag: str = ""
def __repr__(self) -> str:
flag = "S" if self.allow_special else "."
tr = "T" if self.trainable else "."
return f"Seg[{flag}{tr} {self.tag}]{self.text!r}"
class Qwen4ChatEncoder:
DEFAULT_TOOL_SYSTEM = "" # default empty message
SUPPORTED_ROLES = ("system", "user", "assistant", "tool")
SUPPORTED_REASONING_EFFORTS = ("xhigh", "high", "low", "off")
REASONING_INSTRUCTIONS: ClassVar[dict[ReasoningEffortType, str]] = {
effort_level: f"Reasoning effort is set to {effort_level}."
for effort_level in SUPPORTED_REASONING_EFFORTS
}
# (enable_thinking, reasoning_effort) -> effective_reasoning_effort
THINKING_MAPPING: ClassVar[
dict[
tuple[bool | None, ReasoningEffortType],
ReasoningEffortType | None,
]
] = {
(None, None): "high",
(None, "off"): "off",
(None, "low"): "low",
(None, "high"): "high",
(None, "xhigh"): "xhigh",
(False, None): "off",
(False, "off"): "off",
(False, "low"): None,
(False, "high"): None,
(False, "xhigh"): None,
(True, None): "high",
(True, "off"): None,
(True, "low"): "low",
(True, "high"): "high",
(True, "xhigh"): "xhigh",
}
def __init__(
self,
tokenizer: TokenizerProtocol,
):
"""
tokenizer: object with ``tokenize_segment(text, allow_special=bool)``.
Assistant bodies (including tool calls) and closing ``<|im_end|>``
are trainable, except for prefilled think tags; all other segments are masked.
"""
self.tok = tokenizer
self.strict_arguments = (
True # raise on un-parseable tool arguments instead of silently degrading
)
self.reorder_tool_results = (
True # reorder tool response to match tool call ids if tool call ids exist
)
@classmethod
def normalize_thinking_controls(
cls,
enable_thinking: bool | None = None,
reasoning_effort: ReasoningEffortType = "high",
) -> ReasoningEffortType:
"""Validate and normalize the thinking control values."""
if enable_thinking is not None and not isinstance(enable_thinking, bool):
raise ValueError(
f"unsupported enable_thinking value: {enable_thinking!r}, expected True, False, or None"
)
if (
reasoning_effort is not None
and reasoning_effort not in cls.SUPPORTED_REASONING_EFFORTS
):
raise ValueError(
f"unsupported reasoning_effort value: {reasoning_effort!r}, expected one of {cls.SUPPORTED_REASONING_EFFORTS}"
)
effective_reasoning_effort = cls.THINKING_MAPPING.get(
(enable_thinking, reasoning_effort), None
)
if effective_reasoning_effort is None:
raise ValueError(
f"conflict thinking settings: {enable_thinking=} {reasoning_effort=} "
)
return effective_reasoning_effort
def normalize_messages(
self,
messages: list[dict],
*,
preserve_thinking: bool | None = True,
) -> list[dict]:
"""Return the message view shared by rendering and media extraction.
Apply reasoning/role normalization, then align tool results. The input
is not mutated; nested content may be shared. Prompt-only system instructions
and generation prefixes are not added.
"""
if preserve_thinking is not None and not isinstance(preserve_thinking, bool):
raise ValueError(
f"unsupported preserve_thinking value: {preserve_thinking!r}, expected True, False, or None"
)
if preserve_thinking is None:
preserve_thinking = True
msgs = copy.deepcopy(messages)
for m in msgs:
# `developer` role is rendered as a system turn
if m.get("role") == "developer":
m["role"] = "system"
if m["role"] not in self.SUPPORTED_ROLES:
raise ValueError(
f"unsupported message role: {m['role']!r}, expected {self.SUPPORTED_ROLES}"
)
# reasoning content could be passed as `reasoning`
if "reasoning_content" not in m and "reasoning" in m:
m["reasoning_content"] = m["reasoning"]
del m["reasoning"]
if not preserve_thinking:
# A tool or system message does not begin a new user task. With no user turn,
# retain all reasoning rather than guessing a history boundary.
last_user = next(
(
i
for i in range(len(msgs) - 1, -1, -1)
if msgs[i].get("role") == "user"
),
-1,
)
for i, m in enumerate(msgs):
if i < last_user and m.get("role") == "assistant":
m["reasoning_content"] = []
if self.reorder_tool_results:
msgs = self._reorder_tool_results(msgs)
return msgs
def encode(
self,
messages: list[dict],
tools: list[dict] | None = None,
*,
add_generation_prompt: bool = False,
enable_thinking: bool | None = None,
reasoning_effort: ReasoningEffortType = None,
preserve_thinking: bool | None = True,
) -> list[EncodeSegment]:
"""Build the segment list for a whole conversation."""
reasoning_effort = self.normalize_thinking_controls(
enable_thinking, reasoning_effort
)
msgs = self.normalize_messages(messages, preserve_thinking=preserve_thinking)
segs: list[EncodeSegment] = []
tools_norm = self._normalize_tools(tools)
# reasoning effort instructions in system messages
effort_instructions = self.REASONING_INSTRUCTIONS.get(reasoning_effort)
if effort_instructions is not None:
msgs.insert(0, {"role": "system", "content": effort_instructions})
# decide where tools go, synthesising a leading system turn if needed.
tools_target = None
if tools_norm:
if msgs and msgs[0].get("role") == "system":
tools_target = 0
else:
msgs.insert(0, {"role": "system", "content": self.DEFAULT_TOOL_SYSTEM})
tools_target = 0
for i, m in enumerate(msgs):
role = m.get("role")
if role == "system":
self._render_system(
segs,
m,
tools_norm if i == tools_target else None,
)
elif role == "user":
self._render_user(segs, m)
elif role == "assistant":
self._render_assistant(segs, m, thinking_off=reasoning_effort == "off")
elif role == "tool":
self._render_tool(segs, m)
else:
# this is already checked in normalize_messages; kept here since no harm
raise ValueError(
f"unsupported message role: {role!r}, expected {self.SUPPORTED_ROLES}"
)
if add_generation_prompt:
self._sp(segs, f"{IM_START}assistant\n", "gen", trainable=False)
# Adaptive mode: the next token may be </think> (no reasoning) or
# ordinary reasoning content. With thinking off (reasoning_effort ==
# "off"), pre-fill the empty think block. There is deliberately no
# padding newline.
self._sp(segs, THINK_O, "gen", trainable=False)
if reasoning_effort == "off":
self._sp(segs, THINK_C, "gen", trainable=False)
return segs
def render_string(self, messages, tools=None, **kw) -> str:
"""messages -> rendered string"""
return "".join(s.text for s in self.encode(messages, tools, **kw))
def to_tokens(self, segments: list[EncodeSegment]) -> list[int]:
"""segments -> token ids"""
ids: list[int] = []
for s in segments:
ids.extend(self.tok.tokenize_segment(s.text, allow_special=s.allow_special))
return ids
def to_tokens_and_labels(
self, segments: list[EncodeSegment]
) -> tuple[list[int], list[int]]:
"""segments -> (token ids, label token ids) with IGNORE_INDEX on non-trainable tokens"""
ids: list[int] = []
labels: list[int] = []
for s in segments:
toks = self.tok.tokenize_segment(s.text, allow_special=s.allow_special)
ids.extend(toks)
labels.extend(toks if s.trainable else [IGNORE_INDEX] * len(toks))
return ids, labels
def render_tokens(self, messages, tools=None, **kw) -> list[int]:
"""messages -> token ids"""
return self.to_tokens(self.encode(messages, tools, **kw))
def render_tokens_and_labels(
self, messages, tools=None, **kw
) -> tuple[list[int], list[int]]:
"""messages -> (token ids, label token ids) with IGNORE_INDEX on non-trainable tokens"""
return self.to_tokens_and_labels(self.encode(messages, tools, **kw))
def _sp(self, segs, text, tag, trainable=False):
"""scaffolding (special tokens recognized)."""
if not text:
return
segs.append(
EncodeSegment(text, allow_special=True, trainable=trainable, tag=tag)
)
def _dt(self, segs, text, tag, trainable=False):
"""data (special tokens NOT recognized -> anti-injection)."""
if not text:
return
segs.append(
EncodeSegment(text, allow_special=False, trainable=trainable, tag=tag)
)
def _render_system(self, segs, m, tools_norm):
self._sp(segs, f"{IM_START}system\n", "sys/role")
content = m.get("content")
content_segs: list[EncodeSegment] = []
self._render_content(content_segs, content, "sys/content", trainable=False)
segs.extend(content_segs)
if tools_norm:
# Zero-text cache anchors must not introduce a separator.
if any(s.text for s in content_segs):
self._sp(segs, "\n\n", "sys/sep")
self._render_tools_block(segs, tools_norm)
self._sp(segs, f"{IM_END}\n", "sys/role")
def _render_user(self, segs, m):
self._sp(segs, f"{IM_START}user\n", "user/role")
self._render_content(segs, m.get("content"), "user/content", trainable=False)
self._sp(segs, f"{IM_END}\n", "user/role")
def _render_tool(self, segs, m):
self._sp(segs, f"{IM_START}tool\n", "tool/role")
self._render_content(segs, m.get("content"), "tool/content", trainable=False)
# Association IDs and legacy <tool_response> wrappers are not rendered.
self._sp(segs, f"\n{IM_END}\n", "tool/role")
def _render_assistant(self, segs, m, *, thinking_off=False):
self._sp(segs, f"{IM_START}assistant\n", "asst/role", trainable=False)
content = m.get("content")
reasoning = m.get("reasoning_content")
tool_calls = m.get("tool_calls") or []
# render the content block (text and/or images) into its own segment list
content_block: list[EncodeSegment] = []
self._render_content(content_block, content, "asst/content", trainable=True)
# Canonicalize only the outer data-text boundaries of the content field,
# stopping at the first media/control segment. Generation-time trailing
# or leading whitespace on a historical turn would otherwise re-encode to
# a different token run and drift the prefix the cache keyed on.
# Internal whitespace, media and tool arguments are untouched. Emptied
# segments are kept: there may be cache boundary/breakpoint flags which still
# describe real content-part boundaries at the trimmed offsets.
for segment in content_block:
if not segment.text:
continue
if segment.allow_special:
break
segment.text = segment.text.lstrip()
if segment.text:
break
for segment in reversed(content_block):
if not segment.text:
continue
if segment.allow_special:
break
segment.text = segment.text.rstrip()
if segment.text:
break
# Every historical assistant turn has exactly one tight think block.
# Empty reasoning is ``<think></think>``. Normalize the reasoning's outer
# whitespace just as for content, so the think block is stable across
# re-encodes of the same history.
reasoning_text = self._reasoning_to_text(reasoning).strip()
# Match compat's generation region: prefilled think tags carry no loss.
self._sp(segs, THINK_O, "asst/think", trainable=False)
self._dt(
segs,
reasoning_text,
"asst/think",
trainable=True,
)
self._sp(
segs, THINK_C, "asst/think",
trainable=not (thinking_off and not reasoning_text),
)
# Append calls directly after the normalized content. Internal content
# whitespace and tool-argument values remain unchanged.
if content_block:
segs.extend(content_block)
for tc in tool_calls:
segs.extend(self._tool_call_segments(tc, trainable=True))
self._sp(segs, IM_END, "asst/role", trainable=True)
self._sp(segs, "\n", "asst/role", trainable=False)
def _tool_call_segments(self, tc: dict, *, trainable: bool) -> list[EncodeSegment]:
name, arguments = self._tc_fields(tc)
pairs = self._normalize_arguments(arguments)
# TOOL_CALL_O / TOOL_CALL_C are real control tokens and therefore hard
# tokenizer boundaries. Everything between them is ordinary XML-ish text.
# Keep that whole body in one data segment so its token IDs are exactly
# those obtained by continuously tokenizing the rendered text. Splitting
# ``<function=``, ``name`` and ``>`` into separate data segments creates
# impossible-to-reproduce BPE boundaries, e.g. ``=`` + ``bash`` instead
# of ``=b`` + ``ash`` for ``<function=bash>``.
# Tool call content is ordinary data without protocol-level anti-injection.
body = ["<function=", name, ">\n"]
for k, v in pairs:
body.extend(
(
"<parameter=",
self._as_text(k),
">\n",
self._as_text(v),
"\n</parameter>\n",
)
)
body.append("</function>\n")
return [
EncodeSegment(f"{TOOL_CALL_O}\n", True, trainable, "tc/open"),
EncodeSegment("".join(body), False, trainable, "tc/body"),
EncodeSegment(TOOL_CALL_C, True, trainable, "tc/close"),
]
@staticmethod
def _tool_call_id_index(tool_calls: Any) -> dict[str, tuple[int, Any]]:
"""Map opaque call ids to rendered position and function name.
Every list entry advances the 1-based position, malformed/id-less
entries are skipped, and duplicate ids retain their first occurrence.
"""
index: dict[str, tuple[int, Any]] = {}
if not isinstance(tool_calls, list):
return index
for position, tool_call in enumerate(tool_calls, start=1):
if not isinstance(tool_call, dict):
continue
call_id = tool_call.get("id")
if call_id is None:
continue
key = str(call_id)
if key in index:
continue
function = tool_call.get("function")
name = (
function.get("name")
if isinstance(function, dict)
else tool_call.get("name")
)
index[key] = (position, name)
return index
def _reorder_tool_results(self, messages: list[dict]) -> list[dict]:
"""Reorder each run of consecutive ``tool`` messages to match the
preceding assistant's ``tool_calls`` order, matched by
``tool_call_id == tool_calls[].id`` (explicit tool_call_id association).
Side-effect free; a run that can't be fully
matched (missing/unknown ids) is left untouched; idempotent.
"""
out: list[dict] = []
id_index: dict[str, tuple[int, Any]] = {}
i, n = 0, len(messages)
while i < n:
m = messages[i]
role = m.get("role")
if role == "assistant":
id_index = self._tool_call_id_index(m.get("tool_calls"))
out.append(m)
i += 1
continue
if role != "tool":
out.append(m)
i += 1
continue
run, off, unresolved = [], 0, False
while i < n and messages[i].get("role") == "tool":
tm = messages[i]
cid = tm.get("tool_call_id", tm.get("id"))
matched = id_index.get(str(cid)) if cid is not None else None
if matched is None:
unresolved = True
run.append((None, off, tm, None))
else:
pos, name = matched
run.append((pos, off, tm, name))
off += 1
i += 1
if unresolved:
out.extend(t[2] for t in run)
else:
run.sort(key=lambda t: (t[0], t[1]))
for _, _, tool_message, name in run:
# The matched call is authoritative. These metadata fields
# are useful to callers but are not rendered by
# _render_tool.
resolved = dict(tool_message)
if name is not None:
resolved["tool"] = name
if "name" in resolved:
resolved["name"] = name
out.append(resolved)
return out
@staticmethod
def _tc_fields(tc: dict) -> tuple[str, Any]:
if "function" in tc and isinstance(tc["function"], dict):
fn = tc["function"]
return fn.get("name", ""), fn.get("arguments")
return tc.get("name", ""), tc.get("arguments")
def _normalize_arguments(self, arguments: Any) -> list[tuple[str, Any]]:
"""Normalize arguments -> ordered list of (key, value).
Accepts:
- JSON string: OpenAI-compatibile
- dict: Hugging Face transformers
- list-of-dict (each dict's items expanded in order; duplicate / ordered keys preserved).
"""
if arguments is None:
return []
if isinstance(arguments, str):
s = arguments.strip()
if s == "":
return []
try:
arguments = json.loads(s)
except json.JSONDecodeError:
if self.strict_arguments:
raise ValueError(f"tool arguments not valid JSON: {arguments!r}")
return [("", arguments)]
if isinstance(arguments, dict):
return list(arguments.items())
if isinstance(arguments, list):
pairs: list[tuple[str, Any]] = []
for item in arguments:
if isinstance(item, dict):
pairs.extend(item.items())
else:
if self.strict_arguments:
raise ValueError(
f"list argument element must be dict, got {item!r}"
)
return pairs
if self.strict_arguments:
raise ValueError(f"unsupported arguments type: {type(arguments)}")
return [("", arguments)]
@staticmethod
def _as_text(v: Any) -> str:
if isinstance(v, str):
return v
return json.dumps(v, ensure_ascii=False)
@classmethod
def _reasoning_to_text(cls, reasoning: Any) -> str:
"""Collapse ``reasoning_content`` to the inner text of the think block.
Accepts a str (used verbatim) or a list of parts. The think block is
plain text, so only text parts carry meaning; a text part's ``text`` is
concatenated, and any other part is stringified defensively as data
(same fallback as ``_render_content``). ``None`` -> "" (empty think).
Both ``"foo"`` and ``[{"type": "text", "text": "foo"}]`` yield ``"foo"``,
so str and parts forms render to identical tokens.
"""
if reasoning is None:
return ""
if isinstance(reasoning, str):
return reasoning
if isinstance(reasoning, list):
out: list[str] = []
for part in reasoning:
if isinstance(part, str):
out.append(part)
elif isinstance(part, dict) and part.get("type") in (None, "text"):
out.append(part.get("text", ""))
else:
out.append(cls._as_text(part))
return "".join(out)
return cls._as_text(reasoning)
def _render_tools_block(self, segs, tools_norm: list[dict]):
self._sp(
segs,
"# 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/prose",
)
for t in tools_norm:
self._dt(segs, json.dumps(t, ensure_ascii=False), "tools/schema")
self._sp(segs, "\n", "tools/sep")
self._sp(
segs,
"</tools>\n\nIf you choose to call a function, use exactly this format:\n",
"tools/prose2",
)
# Only <tool_call> has dedicated boundary tokens. Dynamic function and
# parameter names intentionally follow Qwen's plaintext XML-ish form.
self._sp(segs, f"{TOOL_CALL_O}\n", "tools/ex")
self._dt(
segs,
"<function={function-name}>\n"
"<parameter={parameter-name}>\n"
"{parameter-value}\n"
"</parameter>\n"
"</function>\n",
"tools/ex",
)
self._sp(segs, TOOL_CALL_C, "tools/ex")
@staticmethod
def _normalize_tools(tools) -> list[dict]:
if not tools:
return []
out = []
for t in tools:
if isinstance(t, dict) and t.get("type") == "function" and "function" in t:
out.append(t)
elif isinstance(t, dict) and "function" in t:
out.append({"type": "function", "function": t["function"]})
elif isinstance(t, dict): # bare function schema
out.append({"type": "function", "function": t})
else:
raise ValueError(f"unsupported tool spec: {t!r}")
return out
# ---- content (text + multimodal passthrough) -------------------------
def _render_content(self, segs, content, tag, *, trainable):
if content is None:
return
if isinstance(content, str):
self._dt(segs, content, tag, trainable=trainable)
return
if isinstance(content, list):
for part in content:
if isinstance(part, str):
self._dt(segs, part, tag, trainable=trainable)
continue
ptype = part.get("type")
if ptype == "text":
self._dt(segs, part.get("text", ""), tag, trainable=trainable)
elif ptype in ("image", "image_url"):
self._sp(
segs, f"{VISION_START}{IMAGE_PAD}{VISION_END}", f"{tag}/image"
)
elif ptype in ("video", "video_url"):
self._sp(
segs, f"{VISION_START}{VIDEO_PAD}{VISION_END}", f"{tag}/video"
)
elif ptype in ("audio", "audio_url"):
self._sp(
segs, f"{AUDIO_START}{AUDIO_PAD}{AUDIO_END}", f"{tag}/audio"
)
else: # unknown part -> stringify defensively as data
raise ValueError(f"unsupported content part type: {ptype!r}")
return
self._dt(segs, self._as_text(content), tag, trainable=trainable)
_TOOLCALL_RE = re.compile(
rf"{re.escape(TOOL_CALL_O)}\r?\n<function=(?P<name>.*?)>\r?\n"
rf"(?P<body>.*?)</function>\r?\n{re.escape(TOOL_CALL_C)}",
re.DOTALL,
)
_PARAMETER_RE = re.compile(
r"(?:^|\r?\n)<parameter=(?P<key>.*?)>\r?\n"
r"(?P<value>.*?)\r?\n</parameter>",
re.DOTALL,
)
def _parse_parameters(body: str) -> dict:
args: dict = {}
for parameter in _PARAMETER_RE.finditer(body):
key, value = parameter.group("key"), parameter.group("value")
try:
args[key] = json.loads(value)
except (json.JSONDecodeError, ValueError):
args[key] = value
return args
def parse_assistant_response_ids(
token_ids: Iterable[int], tokenizer: TokenizerProtocol
) -> dict:
"""Parse original body IDs, including think prefill, without a ChatML header.
Boundaries are control token IDs; incomplete think/tool blocks raise ValueError.
Returns :func:`parse_assistant_response` fields. Requires ``tokenize_segment``
and lossless ``decode``; never re-encode text. Terminal ``<|im_end|>`` is optional.
"""
controls: dict[str, int] = {}
for tag in (THINK_O, THINK_C, TOOL_CALL_O, TOOL_CALL_C, IM_END):
encoded = tokenizer.tokenize_segment(tag, allow_special=True)
if len(encoded) != 1:
raise ValueError(f"{tag!r} must encode to one control token ID")
controls[tag] = encoded[0]
if len(set(controls.values())) != len(controls):
raise ValueError("protocol control token IDs must be distinct")
ids = list(token_ids)
if controls[IM_END] in ids:
ids = ids[: ids.index(controls[IM_END])]
def decode(start: int, end: int) -> str:
return tokenizer.decode(ids[start:end])
def close_after(tag: str, start: int) -> int:
try:
return ids.index(controls[tag], start)
except ValueError:
raise ValueError(
f"incomplete assistant block: missing {tag} control ID"
) from None
reasoning = None
start = 0
if ids and ids[0] == controls[THINK_O]:
close = close_after(THINK_C, 1)
reasoning = decode(1, close)
start = close + 1
first = next(
(i for i in range(start, len(ids)) if ids[i] == controls[TOOL_CALL_O]), len(ids)
)
prefix = decode(start, first)
result = {
"reasoning_content": reasoning,
"content": prefix or None,
"tool_calls": [],
}
if first == len(ids):
return result
pos = first
while pos < len(ids):
close = close_after(TOOL_CALL_C, pos + 1)
# IDs delimit the call; the inner function/parameter markup is XML-ish.
match = _TOOLCALL_RE.fullmatch(
TOOL_CALL_O + decode(pos + 1, close) + TOOL_CALL_C
)
if match is None:
raise ValueError("invalid tool-call function/parameter markup")
result["tool_calls"].append(
{
"name": match.group("name"),
"arguments": _parse_parameters(match.group("body")),
}
)
pos = next(
(i for i in range(close + 1, len(ids)) if ids[i] == controls[TOOL_CALL_O]),
len(ids),
)
return result
|