Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix GLM-5.3 chats breaking after a tool runs (#9938)

Nilay4ba4bf200e5c
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.py
index 42078966303..58006c63117 100644
--- a/studio/backend/core/inference/chat_template_helpers.py
+++ b/studio/backend/core/inference/chat_template_helpers.py
@@ -1714,6 +1714,110 @@ def _within(spans, index: int) -> bool:
return any(start <= index < end for start, end in spans)
+_ENDRAW = re.compile(r"\{%-?\s*endraw\s*-?%\}")
+
+
+def _evaluated_spans(template: str) -> tuple:
+ """The ranges Jinja evaluates, walked quote-aware, with string literals taken out.
+
+ ``_jinja_expression_spans`` ends a block at the first ``}}``, so a template printing
+ literal Jinja -- ``{{ "{{ example.0 }}" }}`` -- reads as code. That scanner is shared
+ with ``model_markup`` (#7066) and stays as it is; this repair edits the template
+ llama-server launches with, so it walks the blocks itself.
+
+ A comment and a ``{% raw %}`` body are both skipped. Raw is tracked through this same
+ walk rather than matched in the source, so tag text that only appears inside a comment
+ or a literal cannot make a real expression between two of them look verbatim. Inside a
+ raw body nothing is interpreted at all, the way Jinja reads it: the walk runs to the
+ terminator, so a comment marker there stays text.
+ """
+ spans: list = []
+ index, end = 0, len(template)
+ verbatim = False
+ while index < end - 1:
+ if verbatim:
+ terminator = _ENDRAW.search(template, index)
+ if not terminator:
+ break
+ index = terminator.end()
+ verbatim = False
+ continue
+ if template[index] != "{" or template[index + 1] not in "{%#":
+ index += 1
+ continue
+ if template[index + 1] == "#":
+ closed = template.find("#}", index + 2)
+ index = end if closed < 0 else closed + 2
+ continue
+ closer = "}}" if template[index + 1] == "{" else "%}"
+ block: list = []
+ cursor = index + 2
+ run = cursor
+ quote = ""
+ closed = False
+ while cursor < end:
+ char = template[cursor]
+ if quote:
+ if char == "\\":
+ cursor += 2
+ continue
+ if char == quote:
+ quote = ""
+ run = cursor + 1
+ elif char in "'\"":
+ block.append((run, cursor))
+ quote = char
+ elif template.startswith(closer, cursor):
+ block.append((run, cursor))
+ closed = True
+ break
+ cursor += 1
+ if not closed:
+ # An unterminated block is text, not code, so nothing in it is rewritten.
+ break
+ tag = template[index + 2 : cursor].strip().strip("-").strip()
+ if closer == "%}" and tag == "raw":
+ verbatim = True
+ else:
+ spans.extend(block)
+ index = cursor + 2
+ return tuple(spans)
+
+
+_NUMERIC_MEMBER = re.compile(r"([A-Za-z_]\w*|\)|\])((?:\s*\.\s*\d+)+)")
+
+
+def repair_numeric_member_access(template) -> Optional[str]:
+ """Rewrite ``x.0`` as ``x[0]`` in evaluated code, or None when nothing needs it.
+
+ llama.cpp's Jinja rejects a numeric member property. The throw lands inside its
+ capability probe, which swallows it, so ``supports_object_arguments`` stays false and a
+ replayed tool call's arguments are never decoded back into an object -- the template's
+ own ``arguments.items()`` then dies on the JSON string (GLM-5.3).
+
+ Only the ranges Jinja evaluates are rewritten, never prompt text, a quoted literal, a
+ raw block, or Jinja syntax a template prints as an example.
+ A chain rewrites whole ("x.0.1" -> "x[0][1]"): leaving the tail behind still throws.
+ Jinja lets whitespace sit around each dot, and llama.cpp throws on that spelling too.
+ """
+ if not isinstance(template, str) or not template:
+ return None
+ spans = _evaluated_spans(template)
+ out: list = []
+ cursor = 0
+ for match in _NUMERIC_MEMBER.finditer(template):
+ if not _within(spans, match.start()):
+ continue
+ out.append(template[cursor : match.start()])
+ indices = "".join(f"[{n}]" for n in re.findall(r"\d+", match.group(2)))
+ out.append(f"{match.group(1)}{indices}")
+ cursor = match.end()
+ if not out:
+ return None
+ out.append(template[cursor:])
+ return "".join(out)
+
+
def _reads_tools_variable(body: str) -> bool:
"""True when *body* evaluates the ``tools`` variable, rather than printing the word."""
return any(_TOOLS_VARIABLE.search(_JINJA_STRING.sub("", code)) for code in _jinja_code(body))
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index e29740dc84f..691e70b1410 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -6358,6 +6358,26 @@ class LlamaCppBackend:
def chat_template_override(self) -> Optional[str]:
return self._chat_template_override
+ def _effective_chat_template(self, chat_template_override: Optional[str]) -> Optional[str]:
+ """The template to launch with: the caller's override, else a repaired copy of the
+ GGUF's own when llama-server's Jinja cannot parse it.
+
+ The repair stays out of ``_chat_template_override``, which the reload check
+ compares against the request's intent -- a value no request sends would reload the
+ model on every Apply.
+ """
+ if chat_template_override:
+ return chat_template_override
+ from core.inference.chat_template_helpers import repair_numeric_member_access
+
+ repaired = repair_numeric_member_access(self._chat_template)
+ if repaired:
+ logger.warning(
+ "The GGUF's chat template indexes with numeric member access, which "
+ "llama-server's Jinja rejects; launching with a repaired copy"
+ )
+ return repaired
+
@property
def supports_reasoning(self) -> bool:
return self._supports_reasoning
@@ -21421,15 +21441,19 @@ class LlamaCppBackend:
if _paravirtual_cpu_forced:
_pv_split_mode_pin = _paravirtual_split_mode_pin(extra_args)
- # Apply custom chat template override if provided.
self._chat_template_override = chat_template_override
- if chat_template_override:
+ _effective_template = self._effective_chat_template(chat_template_override)
+ if _effective_template:
import tempfile
flags = detect_reasoning_flags(
- chat_template_override,
+ _effective_template,
self._model_identifier,
- log_source = "GGUF chat template override",
+ log_source = (
+ "GGUF chat template override"
+ if chat_template_override
+ else "repaired GGUF chat template"
+ ),
)
self._supports_reasoning = flags["supports_reasoning"]
self._reasoning_style = flags["reasoning_style"]
@@ -21446,7 +21470,7 @@ class LlamaCppBackend:
delete = False,
prefix = "unsloth_chat_template_",
)
- self._chat_template_file.write(chat_template_override)
+ self._chat_template_file.write(_effective_template)
self._chat_template_file.close()
cmd.extend(["--chat-template-file", self._chat_template_file.name])
logger.info(f"Using custom chat template file: {self._chat_template_file.name}")
diff --git a/studio/backend/tests/test_chat_template_numeric_member_repair.py b/studio/backend/tests/test_chat_template_numeric_member_repair.py
new file mode 100644
index 00000000000..867d49c7d81
--- /dev/null
+++ b/studio/backend/tests/test_chat_template_numeric_member_repair.py
@@ -0,0 +1,167 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A GGUF whose chat template uses numeric member access ("m.content.0.output", which
+zai-org/GLM-5.3 and its re-quants ship) launches with a repaired copy: llama-server's
+Jinja rejects that form, and the throw leaves replayed tool calls unrenderable.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+_BACKEND = Path(__file__).resolve().parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import core.inference.llama_cpp as llama_cpp # noqa: E402
+from core.inference.chat_template_helpers import repair_numeric_member_access # noqa: E402
+
+
+_GLM53_PROBE_BREAKER = "{%- if m.content and m.content.0.output is defined -%}1{%- endif -%}"
+
+
+def test_the_probe_breaking_access_is_rewritten():
+ assert repair_numeric_member_access(_GLM53_PROBE_BREAKER) == (
+ "{%- if m.content and m.content[0].output is defined -%}1{%- endif -%}"
+ )
+
+
+def test_a_chained_lookup_keeps_the_rest_of_the_expression():
+ assert repair_numeric_member_access("{{ entry.output.0.type == 'tool_reference' }}") == (
+ "{{ entry.output[0].type == 'tool_reference' }}"
+ )
+
+
+def test_a_subscript_result_is_rewritten_too():
+ assert repair_numeric_member_access("{{ messages[i].0.role }}") == "{{ messages[i][0].role }}"
+
+
+def test_a_chain_of_numeric_lookups_is_rewritten_whole():
+ # Repairing only the head leaves "[0].1", which llama-server still throws on.
+ assert repair_numeric_member_access("{{ rows.0.1 }}") == "{{ rows[0][1] }}"
+ assert repair_numeric_member_access("{{ a.0.b.10 }}") == "{{ a[0].b[10] }}"
+
+
+def test_whitespace_around_the_dot_is_still_numeric_member_access():
+ # llama.cpp's lexer skips the spaces and throws on "x . 0" exactly as on "x.0".
+ assert repair_numeric_member_access("{{ messages[i] . 0.role }}") == "{{ messages[i][0].role }}"
+ assert repair_numeric_member_access("{{ m.content .0.type }}") == "{{ m.content[0].type }}"
+ assert repair_numeric_member_access("{{ rows . 0 . 1 }}") == "{{ rows[0][1] }}"
+
+
+def test_every_site_in_one_template_is_rewritten():
+ template = (
+ "{{ m.content.0.type }}{{ tr.output.0.type }}"
+ + _GLM53_PROBE_BREAKER
+ + "{{ entry.output.0.type }}"
+ )
+ assert ".0" not in repair_numeric_member_access(template)
+
+
+def test_a_raw_block_keeps_the_braces_it_prints():
+ # {% raw %} emits its body verbatim, so rewriting there edits the prompt, not code.
+ assert repair_numeric_member_access("{% raw %}{{ example.0 }}{% endraw %}") is None
+ assert repair_numeric_member_access("{%- raw -%}{{ example.0 }}{%- endraw -%}") is None
+
+
+def test_a_raw_body_is_literal_all_the_way_to_its_terminator():
+ # Jinja interprets nothing inside raw, so the "{#" here is text and the {% endraw %}
+ # it appears to wrap really does close the block.
+ assert repair_numeric_member_access("{% raw %}{# {% endraw %} #}{{ m.content.0 }}") == (
+ "{% raw %}{# {% endraw %} #}{{ m.content[0] }}"
+ )
+
+
+def test_a_raw_block_that_never_closes_repairs_nothing_after_it():
+ assert repair_numeric_member_access("{% raw %}{{ e.0 }}") is None
+
+
+def test_raw_tags_that_are_only_comment_text_do_not_open_a_raw_block():
+ # Matching the tags in the source would read the middle expression as verbatim and
+ # leave llama-server the numeric member it rejects.
+ assert repair_numeric_member_access("{# {% raw %} #}{{ m.content.0 }}{# {% endraw %} #}") == (
+ "{# {% raw %} #}{{ m.content[0] }}{# {% endraw %} #}"
+ )
+
+
+def test_a_real_site_outside_a_raw_block_is_still_repaired():
+ assert (
+ repair_numeric_member_access("{% raw %}{{ example.0 }}{% endraw %}{{ m.content.0.output }}")
+ == "{% raw %}{{ example.0 }}{% endraw %}{{ m.content[0].output }}"
+ )
+
+
+def test_jinja_syntax_a_template_prints_as_an_example_is_left_alone():
+ # The quoted "}}" ends the literal, not the expression, so example.0 is prompt text.
+ assert repair_numeric_member_access('{{ "{{ example.0 }}" }}') is None
+ assert repair_numeric_member_access("{{ '{% if x.0 %}' }}") is None
+
+
+def test_a_literal_brace_does_not_hide_a_later_real_site():
+ assert repair_numeric_member_access('{{ "a }} b" }}{{ m.content.0.type }}') == (
+ '{{ "a }} b" }}{{ m.content[0].type }}'
+ )
+
+
+def test_a_comment_is_not_worth_a_relaunch():
+ # Nothing in a comment is rendered, so repairing it would only force the model through
+ # --chat-template-file for a template that needed nothing.
+ assert repair_numeric_member_access("{# {{ a.0 }} #}") is None
+
+
+def test_an_unterminated_block_is_not_treated_as_code():
+ assert repair_numeric_member_access('{{ "unterminated.0 ') is None
+
+
+def test_a_renderable_template_is_left_alone():
+ clean = "{% for m in messages %}{{ m.content }}{% endfor %}"
+ assert repair_numeric_member_access(clean) is None
+
+
+def test_a_float_literal_is_not_indexing():
+ assert repair_numeric_member_access("{% if temperature > 0.5 %}{{ 1.0 }}{% endif %}") is None
+
+
+def test_quoted_text_the_template_prints_is_untouched():
+ assert repair_numeric_member_access('{{ "see step.0 below" }}') is None
+
+
+def test_prompt_text_outside_jinja_is_untouched():
+ prose = "Rate this v1.0 release{{ m.content }}"
+ assert repair_numeric_member_access(prose) is None
+
+
+def test_empty_and_non_string_templates():
+ assert repair_numeric_member_access("") is None
+ assert repair_numeric_member_access(None) is None
+
+
+def _backend(embedded):
+ backend = llama_cpp.LlamaCppBackend.__new__(llama_cpp.LlamaCppBackend)
+ backend._chat_template = embedded
+ backend._model_identifier = "unsloth/GLM-5.3-GGUF"
+ return backend
+
+
+_BROKEN_EMBEDDED = "{% for m in messages %}" + _GLM53_PROBE_BREAKER + "{% endfor %}"
+
+
+def test_a_broken_embedded_template_launches_as_a_repaired_copy():
+ effective = _backend(_BROKEN_EMBEDDED)._effective_chat_template(None)
+ assert "m.content[0].output" in effective
+ assert "m.content.0.output" not in effective
+
+
+def test_a_renderable_embedded_template_launches_untouched():
+ assert _backend("{{ m.content }}")._effective_chat_template(None) is None
+
+
+def test_an_explicit_override_wins_and_is_never_repaired():
+ override = "{{ m.content.0.output }}"
+ assert _backend(_BROKEN_EMBEDDED)._effective_chat_template(override) == override
+
+
+def test_a_gguf_with_no_embedded_template_is_not_a_failure():
+ assert _backend(None)._effective_chat_template(None) is None