Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server): parse and force GLM tool calls on the queued route (#328)

Krisztian Gajdar84b1a7f8c6eb
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index 8547f3a6b..45a265981 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -1152,7 +1152,7 @@ class StreamingProcessor:
``--tool-call-parser`` launch flag) — instead of guessing per
block from the model output. ``qwen3_coder`` (and any other
``qwen*`` parser) → ``qwen_xml``; ``hermes`` → ``hermes_json``;
- anything unknown / missing → ``auto`` (keep the runtime
+ ``glm*`` → ``glm_xml``; anything unknown / missing → ``auto`` (keep the runtime
heuristic so out-of-tree models still work).
"""
try:
@@ -1171,6 +1171,8 @@ class StreamingProcessor:
return "qwen_xml"
if "hermes" in parser_l:
return "hermes_json"
+ if parser_l.startswith("glm"):
+ return "glm_xml"
return "auto"
@staticmethod
diff --git a/packages/sie_server/src/sie_server/processors/tool_call_grammar.py b/packages/sie_server/src/sie_server/processors/tool_call_grammar.py
index bda1cf15b..2a5efd7bd 100644
--- a/packages/sie_server/src/sie_server/processors/tool_call_grammar.py
+++ b/packages/sie_server/src/sie_server/processors/tool_call_grammar.py
@@ -117,6 +117,8 @@ def build_tool_choice_grammar(
pattern = _qwen_xml_force_regex(allowed)
elif tool_call_format == "hermes_json":
pattern = _hermes_json_force_regex(allowed)
+ elif tool_call_format == "glm_xml":
+ pattern = _glm_xml_force_regex(allowed)
elif tool_call_format == "auto":
# ``auto`` means the model's on-wire tool-call format could not be
# confidently resolved from config. Guessing Qwen XML here would
@@ -188,3 +190,18 @@ def _hermes_json_force_regex(names: list[str]) -> str:
+ r"\}\s*</tool_call>"
)
return r"\s*(?:" + block + r"\s*)+"
+
+
+def _glm_xml_force_regex(names: list[str]) -> str:
+ """Force one-or-more GLM tool-call blocks.
+
+ A single block looks like::
+
+ <tool_call>NAME<arg_key>KEY</arg_key><arg_value>VALUE</arg_value></tool_call>
+
+ The name ends at the first ``<arg_key>`` or at ``</tool_call>`` for a call
+ without arguments, which pins it to the allowed set; the arguments stay
+ free, as in the other formats.
+ """
+ block = r"<tool_call>\s*" + _name_alternation(names) + r"\s*(?:<arg_key>" + _INNER + r")?</tool_call>"
+ return r"\s*(?:" + block + r"\s*)+"
diff --git a/packages/sie_server/src/sie_server/processors/tool_call_parser.py b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
index 196de35d3..9f15ba55a 100644
--- a/packages/sie_server/src/sie_server/processors/tool_call_parser.py
+++ b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
@@ -47,6 +47,7 @@ _PARALLEL_TOOL_CALLS_VIOLATED = "parallel_tool_calls_violated"
# ``<tool_call>…</tool_call>``:
# - ``qwen_xml`` — Qwen3(-Coder): ``<function=NAME><parameter=K>V</parameter>…</function>``
# - ``hermes_json`` — Hermes: ``{"name": "...", "arguments": {...}}``
+# - ``glm_xml`` — GLM: ``NAME<arg_key>K</arg_key><arg_value>V</arg_value>…``
# - ``auto`` — runtime heuristic (XML if the block starts with
# ``<function=``, else JSON). Kept as a fallback for
# callers that cannot resolve the model's configured
@@ -54,7 +55,7 @@ _PARALLEL_TOOL_CALLS_VIOLATED = "parallel_tool_calls_violated"
# model config (``tasks.generate`` → adapter
# ``tool_call_parser``) so production traffic uses an
# explicit format rather than guessing per block.
-ToolCallFormat = Literal["auto", "qwen_xml", "hermes_json"]
+ToolCallFormat = Literal["auto", "qwen_xml", "hermes_json", "glm_xml"]
# A model that emits ``<tool_call>`` and never closes it would let
# ``tool_buffer`` grow without bound (same for free-form prose with no
@@ -595,6 +596,8 @@ def _tool_call_deltas(raw: str, index: int, tool_call_format: ToolCallFormat = "
name, arguments = _parse_xml_tool_call(raw)
elif tool_call_format == "hermes_json":
name, arguments = _parse_hermes_tool_call(raw)
+ elif tool_call_format == "glm_xml":
+ name, arguments = _parse_glm_tool_call(raw)
elif raw.startswith("<function="):
name, arguments = _parse_xml_tool_call(raw)
else:
@@ -691,6 +694,65 @@ def _parse_xml_tool_call(raw: str) -> tuple[str, dict[str, object]]:
return name, arguments
+_GLM_KEY_OPEN = "<arg_key>"
+_GLM_KEY_CLOSE = "</arg_key>"
+_GLM_VALUE_OPEN = "<arg_value>"
+_GLM_VALUE_CLOSE = "</arg_value>"
+
+
+def _skip_whitespace(raw: str, pos: int) -> int:
+ while pos < len(raw) and raw[pos].isspace():
+ pos += 1
+ return pos
+
+
+def _parse_glm_tool_call(raw: str) -> tuple[str, dict[str, object]]:
+ """Parse the GLM tool-call form.
+
+ Example::
+
+ get_weather<arg_key>city</arg_key><arg_value>Tokyo</arg_value>
+
+ Returns ``(name, arguments)``; the name is the text before the first
+ ``<arg_key>``. Only whitespace may separate the name and the argument
+ pairs, and a name or key carrying a tag is rejected, so an unpaired or
+ misplaced tag is a parse error rather than part of the call. The chat
+ template writes string values raw and every other value as JSON, so values
+ are coerced as in the Qwen XML form. The scan is linear and parses at most
+ ``_MAX_XML_PARAMS`` pairs.
+ """
+ first_key = raw.find(_GLM_KEY_OPEN)
+ name = (raw if first_key == -1 else raw[:first_key]).strip()
+ if not name or any(char.isspace() or char in "<>" for char in name):
+ raise ValueError("malformed GLM tool-call: invalid function name")
+ arguments: dict[str, object] = {}
+ pos = len(raw) if first_key == -1 else first_key
+ count = 0
+ while (pos := _skip_whitespace(raw, pos)) < len(raw) and count < _MAX_XML_PARAMS:
+ if not raw.startswith(_GLM_KEY_OPEN, pos):
+ raise ValueError("malformed GLM tool-call: expected <arg_key>")
+ key_close = raw.find(_GLM_KEY_CLOSE, pos)
+ if key_close == -1:
+ raise ValueError("malformed GLM tool-call: unterminated argument")
+ value_open = _skip_whitespace(raw, key_close + len(_GLM_KEY_CLOSE))
+ if not raw.startswith(_GLM_VALUE_OPEN, value_open):
+ raise ValueError("malformed GLM tool-call: expected <arg_value>")
+ value_close = raw.find(_GLM_VALUE_CLOSE, value_open)
+ if value_close == -1:
+ raise ValueError("malformed GLM tool-call: unterminated argument")
+ key = raw[pos + len(_GLM_KEY_OPEN) : key_close].strip()
+ if "<" in key or ">" in key:
+ raise ValueError("malformed GLM tool-call: invalid argument key")
+ value = raw[value_open + len(_GLM_VALUE_OPEN) : value_close].strip()
+ try:
+ arguments[key] = json.loads(value)
+ except (json.JSONDecodeError, ValueError):
+ arguments[key] = value
+ pos = value_close + len(_GLM_VALUE_CLOSE)
+ count += 1
+ return name, arguments
+
+
def _parse_error_chunk(message: str) -> GenerationChunk:
return GenerationChunk(
text_delta="",
diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.py
index f4dc8743c..03f0b7c9c 100644
--- a/packages/sie_server/tests/processors/test_streaming.py
+++ b/packages/sie_server/tests/processors/test_streaming.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import asyncio
import base64
+import re
import threading
import time
from collections.abc import AsyncIterator, Mapping
@@ -2806,6 +2807,49 @@ async def test_streaming_tool_choice_required_forwards_forcing_grammar() -> None
assert "get_weather" in grammar.value
+async def test_streaming_glm_tool_call_is_forced_and_parsed_in_its_own_format() -> None:
+ nc = AsyncMock()
+ call = "<tool_call>get_weather<arg_key>city</arg_key><arg_value>Tokyo</arg_value></tool_call>"
+ adapter = _FakeGenAdapter(
+ [
+ GenerationChunk(text_delta=call, is_first=True),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=5, completion_tokens=9),
+ ]
+ )
+ adapter._grammar_backend = "xgrammar" # type: ignore[attr-defined]
+ captured: dict[str, Any] = {}
+ original = adapter.generate
+
+ async def _capture(prompt, *, max_new_tokens, temperature=1.0, top_p=1.0, stop=None, **kwargs):
+ captured.update(kwargs)
+ async for chunk in original(
+ prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p, stop=stop
+ ):
+ yield chunk
+
+ adapter.generate = _capture # type: ignore[method-assign]
+ registry = _make_registry(adapter)
+ resolved = MagicMock()
+ resolved.loadtime = {"tool_call_parser": "glm47"}
+ registry.get_config.return_value.resolve_profile.return_value = resolved
+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")
+ wi = _make_work_item(
+ generate={"prompt": "weather?", "max_new_tokens": 64, "tools": _WEATHER_TOOLS, "tool_choice": "required"}
+ )
+
+ await proc.process(_make_msg(wi), "test/model")
+
+ grammar = captured.get("grammar")
+ assert grammar is not None
+ assert re.fullmatch(grammar.value, call)
+ decoded = _decode_chunks(nc)
+ tcs = _tool_call_deltas(decoded)
+ assert tcs[0]["function"]["name"] == "get_weather"
+ assert tcs[1]["function"]["arguments"] == '{"city":"Tokyo"}'
+ assert decoded[-1]["finish_reason"] == "tool_calls"
+
+
@pytest.mark.asyncio
async def test_streaming_tool_choice_none_hides_tools_from_chat_template(monkeypatch) -> None:
"""``tool_choice='none'`` must prevent the model from ever seeing the
diff --git a/packages/sie_server/tests/processors/test_tool_call_grammar.py b/packages/sie_server/tests/processors/test_tool_call_grammar.py
index 353e8f462..781e87861 100644
--- a/packages/sie_server/tests/processors/test_tool_call_grammar.py
+++ b/packages/sie_server/tests/processors/test_tool_call_grammar.py
@@ -114,6 +114,37 @@ def test_required_hermes_json_regex() -> None:
assert not pat.fullmatch(bad)
+# ── build_tool_choice_grammar: regex shape (glm_xml) ───────────────
+
+
+def test_required_glm_xml_regex_matches_any_tool() -> None:
+ spec = build_tool_choice_grammar(_TOOLS, "required", "glm_xml")
+ assert spec is not None
+ assert spec.kind == "regex"
+ pat = re.compile(spec.value)
+ weather = "<tool_call>get_weather<arg_key>city</arg_key><arg_value>Tokyo</arg_value></tool_call>"
+ spaced = "<tool_call>get_weather\n<arg_key>city</arg_key>\n<arg_value>Tokyo</arg_value>\n</tool_call>"
+ assert pat.fullmatch(weather)
+ assert pat.fullmatch(spaced)
+ assert pat.fullmatch("<tool_call>get_time</tool_call>")
+ assert pat.fullmatch(weather + "\n<tool_call>get_time</tool_call>")
+ assert not pat.fullmatch("<tool_call>delete_everything</tool_call>")
+ assert not pat.fullmatch("I cannot help with that.")
+
+
+def test_named_glm_xml_regex_pins_the_whole_name() -> None:
+ tools = (
+ {"type": "function", "function": {"name": "get"}},
+ {"type": "function", "function": {"name": "get_weather"}},
+ )
+ spec = build_tool_choice_grammar(tools, {"type": "function", "function": {"name": "get"}}, "glm_xml")
+ assert spec is not None
+ pat = re.compile(spec.value)
+ assert pat.fullmatch("<tool_call>get<arg_key>x</arg_key><arg_value>1</arg_value></tool_call>")
+ assert not pat.fullmatch("<tool_call>get_weather<arg_key>x</arg_key><arg_value>1</arg_value></tool_call>")
+ assert not pat.fullmatch("<tool_call>get_weather</tool_call>")
+
+
def test_auto_format_refuses_to_force_instead_of_guessing_qwen_xml() -> None:
# Regression (fix #7): when the format is unresolved ("auto"), forcing a
# tool_choice must NOT silently assume Qwen XML — a non-Qwen model would
diff --git a/packages/sie_server/tests/processors/test_tool_call_parser.py b/packages/sie_server/tests/processors/test_tool_call_parser.py
index 2f20ecc9d..6cf865985 100644
--- a/packages/sie_server/tests/processors/test_tool_call_parser.py
+++ b/packages/sie_server/tests/processors/test_tool_call_parser.py
@@ -526,6 +526,115 @@ def test_xml_param_scan_garbled_openers_no_close_is_fast() -> None:
assert elapsed < 2.0
+# ── GLM argument tags ──────────────────────────────────────────────────
+
+
+ "raw",
+ [
+ "<tool_call>get_weather<arg_key>city</arg_key><arg_value>Tokyo</arg_value>"
+ "<arg_key>days</arg_key><arg_value>3</arg_value></tool_call>",
+ "<tool_call>get_weather\n<arg_key>city</arg_key>\n<arg_value>Tokyo</arg_value>\n"
+ "<arg_key>days</arg_key>\n<arg_value>3</arg_value>\n</tool_call>",
+ ],
+)
+async def test_explicit_glm_xml_format(raw: str) -> None:
+ import json
+
+ out = await _collect("Checking. " + raw, tool_call_format="glm_xml")
+
+ assert out[0].text_delta == "Checking. "
+ assert _deltas(out)[0].function_name == "get_weather"
+ assert json.loads(_args_for(out)) == {"city": "Tokyo", "days": 3}
+ assert out[-1].finish_reason == "tool_calls"
+
+
+async def test_glm_xml_call_without_arguments() -> None:
+ out = await _collect("<tool_call>get_time</tool_call>", tool_call_format="glm_xml")
+
+ assert _deltas(out)[0].function_name == "get_time"
+ assert _args_for(out) == "{}"
+
+
+async def test_glm_xml_argument_values_coerce_like_qwen_xml() -> None:
+ import json
+
+ raw = (
+ "<tool_call>f"
+ "<arg_key>num</arg_key><arg_value>5</arg_value>"
+ "<arg_key>flag</arg_key><arg_value>true</arg_value>"
+ '<arg_key>nested</arg_key><arg_value>{"a": [1, 2]}</arg_value>'
+ "<arg_key>text</arg_key><arg_value>café ☕</arg_value>"
+ "<arg_key>multiline</arg_key><arg_value>line1\nline2</arg_value>"
+ "</tool_call>"
+ )
+ out = await _collect(raw, tool_call_format="glm_xml")
+
+ assert json.loads(_args_for(out)) == {
+ "num": 5,
+ "flag": True,
+ "nested": {"a": [1, 2]},
+ "text": "café ☕",
+ "multiline": "line1\nline2",
+ }
+
+
+async def test_glm_xml_unterminated_argument_is_terminal_parse_error() -> None:
+ out = await _collect(
+ "<tool_call>f<arg_key>a</arg_key><arg_value>1</tool_call>",
+ tool_call_format="glm_xml",
+ )
+
+ assert out[-1].done is True
+ assert out[-1].error_code == "MODEL_OUTPUT_PARSE_ERROR"
+ assert "unterminated argument" in (out[-1].error_message or "")
+
+
+ ("raw", "reason"),
+ [
+ ("<tool_call>f<arg_value>1</arg_value></tool_call>", "invalid function name"),
+ ("<tool_call>get weather</tool_call>", "invalid function name"),
+ (
+ "<tool_call>f<arg_key>a</arg_key><arg_value>1</arg_value><arg_value>2</arg_value></tool_call>",
+ "expected <arg_key>",
+ ),
+ ("<tool_call>f<arg_key>a</arg_key>junk<arg_value>1</arg_value></tool_call>", "expected <arg_value>"),
+ (
+ "<tool_call>f<arg_key>a<arg_value>1</arg_value><arg_key>b</arg_key><arg_value>2</arg_value></tool_call>",
+ "invalid argument key",
+ ),
+ ],
+)
+async def test_glm_xml_misplaced_tags_are_terminal_parse_errors(raw: str, reason: str) -> None:
+ out = await _collect(raw, tool_call_format="glm_xml")
+
+ assert _deltas(out) == []
+ assert out[-1].error_code == "MODEL_OUTPUT_PARSE_ERROR"
+ assert reason in (out[-1].error_message or "")
+
+
+def test_glm_argument_scan_bounds_argument_count() -> None:
+ import time
+
+ from sie_server.processors.tool_call_parser import _MAX_XML_PARAMS, _parse_glm_tool_call
+
+ n = _MAX_XML_PARAMS + 5_000
+ raw = "f" + "".join(f"<arg_key>p{i}</arg_key><arg_value>{i}</arg_value>" for i in range(n))
+ t0 = time.monotonic()
+ name, args = _parse_glm_tool_call(raw)
+ elapsed = time.monotonic() - t0
+
+ assert name == "f"
+ assert len(args) == _MAX_XML_PARAMS
+ assert elapsed < 2.0
+
+
# ── Per-choice (n>1) streaming (H5) ──────────────────────────────────────