Compare commits

...
Author SHA1 Message Date
carsten e9619bf8f0 Add text-level Hermes tool-call parser for Trinity
Trinity's tokenizer has no <tool_call> special token, so token-id based
parsers never detect calls. Adds a reasoning- and Markdown-aware
text-level parser selected with tool_parser = "hermes".
2026-10-14 12:23:49 +00:00
4 changed files with 290 additions and 0 deletions
+3
View File
@@ -22,6 +22,7 @@ from renderers.base import (
resolve_thinking_retention,
)
from renderers.configs import DefaultRendererConfig
from renderers.hermes import HermesToolParser
from renderers.parsers import (
get_reasoning_parser,
get_tool_parser,
@@ -109,6 +110,8 @@ class DefaultRenderer:
self._tokenizer = tokenizer
self.config = cfg
self._tool_parser = _resolve_parser(cfg.tool_parser, tokenizer, get_tool_parser)
if isinstance(self._tool_parser, HermesToolParser):
self._tool_parser.configure_prefill(dict(cfg.model_extra or {}))
self._reasoning_parser = _resolve_parser(
cfg.reasoning_parser, tokenizer, get_reasoning_parser
)
+149
View File
@@ -0,0 +1,149 @@
"""Text-level Hermes calls, excluding reasoning and Markdown code examples."""
from __future__ import annotations
import json
import re
from typing import Any
from renderers.base import ParsedToolCall, ToolCallParseStatus
_THINK = re.compile(r"</?think>", re.IGNORECASE)
_OPEN = "<tool_call>"
_CLOSE = "</tool_call>"
def _reject_constant(value: str) -> None:
raise ValueError(f"Non-JSON numeric constant: {value}")
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result = {}
for key, value in pairs:
if key in result:
raise ValueError(f"Duplicate JSON key: {key}")
result[key] = value
return result
_JSON = json.JSONDecoder(parse_constant=_reject_constant, object_pairs_hook=_unique_object)
def _token_boundary(tokenizer, ids: list[int], offset: int, *, end: bool) -> int:
"""Cover every token overlapping the character span, including boundary merges."""
low, high = 0, len(ids)
while low < high:
mid = (low + high) // 2
if len(tokenizer.decode(ids[:mid], skip_special_tokens=False)) < offset:
low = mid + 1
else:
high = mid
if not end and len(tokenizer.decode(ids[:low], skip_special_tokens=False)) > offset:
return max(0, low - 1)
return low
def _skip_reasoning(text: str, start: int) -> int:
depth = 0
for match in _THINK.finditer(text, start):
depth += -1 if match.group().startswith("</") else 1
if depth == 0:
return match.end()
return len(text)
def _read_block(text: str, start: int) -> tuple[int, str, Any, ToolCallParseStatus]:
body = start + len(_OPEN)
while body < len(text) and text[body].isspace():
body += 1
try:
payload, json_end = _JSON.raw_decode(text, body)
except ValueError:
close = text.find(_CLOSE, body)
if close < 0:
return len(text), text[body:].strip(), None, ToolCallParseStatus.UNCLOSED_BLOCK
return close + len(_CLOSE), text[body:close].strip(), None, ToolCallParseStatus.INVALID_JSON
close = json_end
while close < len(text) and text[close].isspace():
close += 1
if not text.startswith(_CLOSE, close):
closing = text.find(_CLOSE, close)
if closing < 0:
return len(text), text[body:].strip(), None, ToolCallParseStatus.UNCLOSED_BLOCK
return closing + len(_CLOSE), text[body:closing].strip(), None, ToolCallParseStatus.MALFORMED_STRUCTURE
status = ToolCallParseStatus.OK
if (
not isinstance(payload, dict)
or not isinstance(payload.get("name"), str)
or not payload["name"].strip()
or not isinstance(payload.get("arguments"), dict)
):
status = ToolCallParseStatus.MALFORMED_STRUCTURE
return close + len(_CLOSE), text[body:json_end], payload, status
class HermesToolParser:
"""Parse native Hermes envelopes without promoting quoted examples into actions."""
def __init__(self, tokenizer):
self._tokenizer = tokenizer
self._starts_in_reasoning = False
def configure_prefill(self, template_kwargs: dict[str, Any]) -> None:
"""Honor templates that put the opening reasoning tag in the prompt."""
if not hasattr(self._tokenizer, "apply_chat_template"):
return
kwargs = {**template_kwargs, "add_generation_prompt": True, "tokenize": False, "return_dict": False}
prompt = self._tokenizer.apply_chat_template([{"role": "user", "content": "Hello"}], **kwargs)
self._starts_in_reasoning = bool(re.search(r"<think>\s*$", prompt, re.IGNORECASE))
def extract(self, ids: list[int]) -> tuple[list[int], list[ParsedToolCall]]:
text = self._tokenizer.decode(ids, skip_special_tokens=False)
if _OPEN not in text:
return ids, []
# Some chat templates prefill <think>; the generated tokens then start
# inside reasoning and contain only its closing delimiter.
first_think = _THINK.search(text)
if self._starts_in_reasoning and first_think is None:
return ids, []
cursor = first_think.end() if first_think and first_think.group().startswith("</") else 0
kept, calls = [], []
previous = 0
while cursor < len(text):
if text[cursor : cursor + 7].lower() == "<think>":
cursor = _skip_reasoning(text, cursor)
continue
if text[cursor] == "`" or text.startswith("~~~", cursor):
end = cursor + 1
while end < len(text) and text[end] == text[cursor]:
end += 1
marker = text[cursor:end]
close = text.find(marker, end)
cursor = len(text) if close < 0 else close + len(marker)
continue
if not text.startswith(_OPEN, cursor):
cursor += 1
continue
end, raw, payload, status = _read_block(text, cursor)
span = (
_token_boundary(self._tokenizer, ids, cursor, end=False),
_token_boundary(self._tokenizer, ids, end, end=True),
)
calls.append(
ParsedToolCall(
raw=raw,
token_span=span,
status=status,
name=payload["name"] if status == ToolCallParseStatus.OK else None,
arguments=payload["arguments"] if status == ToolCallParseStatus.OK else None,
)
)
kept.append(text[previous:cursor])
previous = cursor = end
if not calls:
return ids, []
kept.append(text[previous:])
# Re-encode retained text so BPE tokens crossing envelope boundaries do
# not swallow adjacent text. Spans above always refer to the original ids.
content_ids = self._tokenizer.encode("".join(kept), add_special_tokens=False)
return content_ids, calls
+2
View File
@@ -20,6 +20,7 @@ import re
from typing import Protocol, runtime_checkable
from renderers.base import ParsedToolCall, ToolCallParseStatus
from renderers.hermes import HermesToolParser
# ── Shared helpers ───────────────────────────────────────────────────
@@ -458,6 +459,7 @@ class ThinkTextReasoningParser:
TOOL_PARSERS: dict[str, type] = {
"hermes": HermesToolParser,
"qwen3": Qwen3ToolParser,
"qwen3.5": Qwen35ToolParser,
"glm": GlmToolParser,
+136
View File
@@ -0,0 +1,136 @@
"""Hermes regressions on Trinity's real multi-token tool delimiters."""
import json
import pytest
from renderers.base import ToolCallParseStatus
from renderers.configs import DefaultRendererConfig
from renderers.default import DefaultRenderer
from transformers import AutoTokenizer
@pytest.fixture(scope="module")
def trinity_tokenizer():
return AutoTokenizer.from_pretrained(
"arcee-ai/Trinity-Mini",
revision="cdb81e8130815fec299cccc8f8700004b8366e1e",
trust_remote_code=False,
)
@pytest.fixture
def hermes_renderer(trinity_tokenizer):
return DefaultRenderer(
trinity_tokenizer,
DefaultRendererConfig(tool_parser="hermes", reasoning_parser="think"),
)
CALL = '<tool_call>{"name":"book_flight","arguments":{"dest":"Paris"}}</tool_call>'
@pytest.mark.parametrize(
"text",
[
f"<think>Consider {CALL}, but do not book.</think>No.",
f"Consider {CALL}, but do not book.</think>No.",
f"<think>Unclosed reasoning containing {CALL}",
f"Unclosed prefilled reasoning containing {CALL}",
f"Finished reasoning.</think>```json\n{CALL}\n```",
f"Finished reasoning.</think>~~~json\n{CALL}\n~~~",
f"Finished reasoning.</think>Example: `{CALL}`.",
'Finished reasoning.</think>```json\n{"name":"book_flight","arguments":{"dest":"Paris"}}\n```',
'Finished reasoning.</think>{"name":"book_flight","arguments":{"dest":"Paris"}}',
],
)
def test_examples_are_not_actions(trinity_tokenizer, hermes_renderer, text):
ids = trinity_tokenizer.encode(text, add_special_tokens=False)
remaining, calls = hermes_renderer._tool_parser.extract(ids)
assert remaining == ids
assert calls == []
assert hermes_renderer.parse_response(ids).tool_calls == []
def test_native_calls_preserve_reasoning_content_and_original_spans(trinity_tokenizer, hermes_renderer):
text = f"Consider the destination.</think>é🙂 before{CALL}between{CALL}after"
ids = trinity_tokenizer.encode(text, add_special_tokens=False)
parsed = hermes_renderer.parse_response(ids)
assert parsed.reasoning_content == "Consider the destination."
assert parsed.content == "é🙂 beforebetweenafter"
assert len(parsed.tool_calls) == 2
for call in parsed.tool_calls:
assert call.status == ToolCallParseStatus.OK
assert call.name == "book_flight" and call.arguments == {"dest": "Paris"}
start, end = call.token_span
assert 0 <= start < end <= len(ids)
covered = trinity_tokenizer.decode(ids[start:end], skip_special_tokens=False)
assert CALL in covered
@pytest.mark.parametrize(
"body,status",
[
('{"name":"f","arguments":{}}', ToolCallParseStatus.OK),
('{"name":"f","arguments":[]}', ToolCallParseStatus.MALFORMED_STRUCTURE),
('{"name":"f","arguments":null}', ToolCallParseStatus.MALFORMED_STRUCTURE),
('{"name":"f","arguments":"{}"}', ToolCallParseStatus.MALFORMED_STRUCTURE),
('{"name":"f"}', ToolCallParseStatus.MALFORMED_STRUCTURE),
('{"name":42,"arguments":{}}', ToolCallParseStatus.MALFORMED_STRUCTURE),
('{"name":" ","arguments":{}}', ToolCallParseStatus.MALFORMED_STRUCTURE),
("[]", ToolCallParseStatus.MALFORMED_STRUCTURE),
("{'name':'f','arguments':{}}", ToolCallParseStatus.INVALID_JSON),
('{"name":"f","arguments":{"x":NaN}}', ToolCallParseStatus.INVALID_JSON),
('{"name":"f","arguments":{"x":Infinity}}', ToolCallParseStatus.INVALID_JSON),
('{"name":"f","name":"g","arguments":{}}', ToolCallParseStatus.INVALID_JSON),
('{"name":"f","arguments":{}} trailing', ToolCallParseStatus.MALFORMED_STRUCTURE),
],
)
def test_strict_native_envelopes(trinity_tokenizer, hermes_renderer, body, status):
ids = trinity_tokenizer.encode(f"Use the tool.</think><tool_call>{body}</tool_call>", add_special_tokens=False)
parsed = hermes_renderer.parse_response(ids)
assert len(parsed.tool_calls) == 1
assert parsed.tool_calls[0].status == status
if status != ToolCallParseStatus.OK:
assert parsed.tool_calls[0].name is None
def test_tag_strings_in_arguments_do_not_close_a_call(trinity_tokenizer, hermes_renderer):
args = {"text": '</tool_call> <think> ``` <tool_call> " café🙂'}
body = json.dumps({"name": "f", "arguments": args}, ensure_ascii=False)
ids = trinity_tokenizer.encode(
f"Use the tool.</think><tool_call>{body}</tool_call>suffix", add_special_tokens=False
)
parsed = hermes_renderer.parse_response(ids)
assert parsed.content == "suffix"
assert parsed.tool_calls[0].arguments == args
assert parsed.tool_calls[0].status == ToolCallParseStatus.OK
def test_unclosed_call_remains_a_parse_error(trinity_tokenizer, hermes_renderer):
ids = trinity_tokenizer.encode(
'Use the tool.</think><tool_call>{"name":"f","arguments":{}}', add_special_tokens=False
)
parsed = hermes_renderer.parse_response(ids)
assert parsed.tool_calls[0].status == ToolCallParseStatus.UNCLOSED_BLOCK
assert parsed.tool_calls[0].name is None
def test_real_schema_uses_native_chat_template(trinity_tokenizer, hermes_renderer):
tool = {
"type": "function",
"function": {
"name": "book_flight",
"description": "Book a flight.",
"parameters": {"type": "object", "properties": {"dest": {"type": "string"}}},
},
}
result = hermes_renderer.render(
[{"role": "user", "content": "Book a flight to Paris."}],
tools=[tool],
add_generation_prompt=True,
)
text = trinity_tokenizer.decode(result.token_ids, skip_special_tokens=False)
assert "book_flight" in text and "<tools>" in text and "<tool_call>" in text
assert "available_actions" not in text
assert "```json" not in text
assert text.endswith("<think>\n")