Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

feat(qwen38): tool calling, and a tools flag that stops lying

JustVugg1bcd5f29b37a
diff --git a/c/family_registry.py b/c/family_registry.py
index f96ebed4..9b86e030 100644
--- a/c/family_registry.py
+++ b/c/family_registry.py
@@ -908,7 +908,11 @@ FAMILIES = (
# esperti dalla RAM disponibile, quindi "nessuna scelta esplicita"
# deve arrivargli come 0 e non come otto slot per layer.
limits=FamilyLimits(8192, 1048576, 1024, 1024, 1, 0, "GLM53_MAXT"),
- capabilities=COMMON_CAP,
+ # tools=True: this family DOES render and parse tool calls. It used to
+ # share COMMON_CAP, which says otherwise -- the flag is descriptive
+ # (it only feeds the capability dict) so nothing broke, but a client
+ # reading it programmatically was told the opposite of the truth.
+ capabilities=FamilyCapabilities(True, False, False, True),
has_gateway_adapter=True,
has_cli_adapter=True,
# Dal chat_template.jinja del checkpoint: nessun a capo, e <think>
@@ -988,7 +992,11 @@ FAMILIES = (
expert_inventory=_individual_expert_inventory(_KIMI_EXPERT),
config_section="text_config",
limits=FamilyLimits(8192, 1048576, 1024, 1024, 1, 8, "K3_MAXT"),
- capabilities=COMMON_CAP,
+ # tools=True: this family DOES render and parse tool calls. It used to
+ # share COMMON_CAP, which says otherwise -- the flag is descriptive
+ # (it only feeds the capability dict) so nothing broke, but a client
+ # reading it programmatically was told the opposite of the truth.
+ capabilities=FamilyCapabilities(True, False, False, True),
has_gateway_adapter=True,
tune_prompt_template="K3CHAT1\nM user {prompt_len}\n{prompt}G 0\n\n",
),
@@ -1070,7 +1078,7 @@ FAMILIES = (
fixed_resident_inventory=_qwen38_fixed_resident_inventory,
config_section="text_config",
limits=FamilyLimits(8192, 262144, 1024, 8192, 1, 1, "Q38_MAXT"),
- capabilities=FamilyCapabilities(False, False, False, True),
+ capabilities=FamilyCapabilities(True, False, False, True),
has_gateway_adapter=True,
# Like Qwen3.6, direct `coli run` is intentionally not exposed until
# an engine-specific CLI prompt path exists; chat/serve use the gateway.
diff --git a/c/openai_server.py b/c/openai_server.py
index 5997022d..fd8bf4e9 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -529,6 +529,8 @@ def parse_arch_tool_calls(reply, tools, tool_reply=None):
_sideband_text, calls = parse_k3_tool_calls(tool_reply, tools)
return reply.strip(), calls
return parse_k3_tool_calls(reply, tools) # compatibility with pre-#1147 engines
+ if ARCH == "qwen38":
+ return parse_qwen38_tool_calls(reply, tools)
return parse_tool_calls(reply, tools)
@@ -1201,14 +1203,127 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, too
return "".join(parts)
+# Qwen3.8 declares and emits tool calls in an XML-ish form of its own, not the
+# JSON block GLM uses and not DeepSeek's DSML -- so it needs its own renderer and
+# its own parser. Both sides are transcribed from chat_template.jinja rather than
+# paraphrased, because a tool preamble the model has not seen verbatim is a
+# different prompt: the declaration is what teaches it the syntax it must emit.
+#
+# <tool_call>
+# <function=NAME>
+# <parameter=KEY>
+# VALUE
+# </parameter>
+# </function>
+# </tool_call>
+QWEN38_TOOL_PREAMBLE = ("\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 _qwen38_tool_block(tools):
+ """The `# Tools` system section, byte-identical to the template's."""
+ lines = ["# Tools\n\nYou have access to the following functions:\n\n<tools>"]
+ for tool in tools:
+ lines.append("\n" + json.dumps(tool, ensure_ascii=False, separators=(", ", ": ")))
+ lines.append("\n</tools>")
+ lines.append(QWEN38_TOOL_PREAMBLE)
+ return "".join(lines)
+
+
+def _qwen38_tool_calls(tool_calls, has_content, index):
+ """Render assistant tool_calls. The template separates the FIRST call from
+ preceding content with a blank line only when that content is non-empty, and
+ every later call with a single newline; getting that wrong changes the prompt
+ the model is conditioned on."""
+ out = []
+ for position, call in enumerate(tool_calls or []):
+ if not isinstance(call, dict):
+ raise APIError(400, "Each tool call must be an object.",
+ f"messages.{index}.tool_calls.{position}")
+ fn = call.get("function", call)
+ if not isinstance(fn, dict):
+ raise APIError(400, "`function` must be an object.",
+ f"messages.{index}.tool_calls.{position}.function")
+ name = fn.get("name")
+ if not isinstance(name, str) or not name:
+ raise APIError(400, "`function.name` must be a non-empty string.",
+ f"messages.{index}.tool_calls.{position}.function.name")
+ lead = ("\n\n" if has_content else "") if position == 0 else "\n"
+ out.append(f"{lead}<tool_call>\n<function={name}>\n")
+ args = fn.get("arguments", "")
+ if isinstance(args, str) and args:
+ try:
+ args = json.loads(args)
+ except (TypeError, ValueError):
+ raise APIError(400, "`function.arguments` must be a JSON object.",
+ f"messages.{index}.tool_calls.{position}.function.arguments")
+ if isinstance(args, dict):
+ for key, value in args.items():
+ # The template stringifies a str as-is and tojson's everything
+ # else, so a string argument must NOT gain quotes here.
+ rendered = value if isinstance(value, str) else json.dumps(
+ value, ensure_ascii=False, separators=(", ", ": "))
+ out.append(f"<parameter={key}>\n{rendered}\n</parameter>\n")
+ out.append("</function>\n</tool_call>")
+ return "".join(out)
+
+
+QWEN38_CALL_RE = re.compile(
+ r"<tool_call>\s*<function=([^>\n]+)>\s*(.*?)</function>\s*</tool_call>", re.S)
+QWEN38_PARAM_RE = re.compile(r"<parameter=([^>\n]+)>\n(.*?)\n</parameter>", re.S)
+
+
+def parse_qwen38_tool_calls(reply, tools=None):
+ """Parse Qwen3.8's XML-ish calls back into OpenAI `tool_calls`.
+
+ Values are returned as strings, which is what the template feeds in: it
+ writes a str argument unquoted, so the original type is not recoverable from
+ the text alone. Where the declared schema says a parameter is not a string we
+ re-read it as JSON, which restores numbers and booleans without guessing at
+ anything the schema did not promise."""
+ schema = {}
+ for tool in (tools or []):
+ fn = tool.get("function", tool) if isinstance(tool, dict) else {}
+ params = (fn.get("parameters") or {}).get("properties") or {}
+ if isinstance(params, dict):
+ schema[fn.get("name")] = params
+ calls = []
+ for match in QWEN38_CALL_RE.finditer(reply or ""):
+ name = match.group(1).strip()
+ args = {}
+ for key, raw in QWEN38_PARAM_RE.findall(match.group(2)):
+ key = key.strip()
+ declared = (schema.get(name) or {}).get(key) or {}
+ kind = declared.get("type") if isinstance(declared, dict) else None
+ if kind in (None, "string"):
+ args[key] = raw
+ else:
+ try:
+ args[key] = json.loads(raw)
+ except (TypeError, ValueError):
+ args[key] = raw
+ calls.append({
+ "id": f"call_{uuid.uuid4().hex[:24]}",
+ "type": "function",
+ "function": {"name": name,
+ "arguments": json.dumps(args, ensure_ascii=False)},
+ })
+ text = QWEN38_CALL_RE.sub("", reply or "")
+ if not calls and tools and "<tool_call>" in (reply or ""):
+ sys.stderr.write("[api] qwen38 tool markers present but no call parsed -- "
+ "possibly truncated or mangled output\n")
+ sys.stderr.flush()
+ return text.strip(), calls
+
+
def render_chat_qwen38(messages, enable_thinking=True, reasoning_effort=None, tools=None,
tool_choice=None):
"""Text-only Qwen3.8 chat-template subset with native reasoning hints."""
if not isinstance(messages, list) or not messages:
raise APIError(400, "`messages` must be a non-empty array.", "messages")
- if tools or tool_choice not in (None, "none"):
- raise APIError(400, "Tool use is not wired up for the qwen38 engine yet.",
- "tools", "unsupported_parameter")
+ if tool_choice in ("none",):
+ tools = None # the client forbade them: do not offer any
+ if tools is not None and not isinstance(tools, list):
+ raise APIError(400, "`tools` must be an array.", "tools")
instruction = ""
if enable_thinking:
@@ -1235,18 +1350,26 @@ def render_chat_qwen38(messages, enable_thinking=True, reasoning_effort=None, to
first_role = first.get("role") if isinstance(first, dict) else None
if first_role == "developer":
first_role = "system"
+ system_text = ""
+ start = 0
if first_role == "system":
raw = first.get("content")
- text = content_text(raw, "messages.0.content").strip() if raw is not None else ""
+ system_text = content_text(raw, "messages.0.content").strip() if raw is not None else ""
+ start = 1
+ if tools:
+ # With tools the template builds ONE system turn in a fixed order:
+ # reasoning instruction, then the tool block, then the user's own system
+ # text last -- not the other way round.
+ head = (instruction + "\n\n") if instruction else ""
+ block = head + _qwen38_tool_block(tools)
+ if system_text:
+ block += "\n\n" + system_text
+ parts.append(f"<|im_start|>system\n{block}<|im_end|>\n")
+ elif system_text or instruction:
+ text = system_text
if instruction:
text = instruction + ("\n\n" + text if text else "")
parts.append(f"<|im_start|>system\n{text}<|im_end|>\n")
- start = 1
- elif instruction:
- parts.append(f"<|im_start|>system\n{instruction}<|im_end|>\n")
- start = 0
- else:
- start = 0
for index, message in enumerate(messages[start:], start=start):
if not isinstance(message, dict):
@@ -1254,7 +1377,7 @@ def render_chat_qwen38(messages, enable_thinking=True, reasoning_effort=None, to
role = message.get("role")
if role == "developer":
role = "system"
- if role not in ("system", "user", "assistant"):
+ if role not in ("system", "user", "assistant", "tool"):
raise APIError(400, f"Unsupported role {role!r}.", f"messages.{index}.role")
if role == "system" and index != 0:
raise APIError(400, "System message must be at the beginning.",
@@ -1262,12 +1385,32 @@ def render_chat_qwen38(messages, enable_thinking=True, reasoning_effort=None, to
raw = message.get("content")
text = (content_text(raw, f"messages.{index}.content").strip()
if raw is not None else "")
+ if role == "tool":
+ # Consecutive tool results share ONE user turn: the opening tag is
+ # written only when the previous message was not a tool, and the
+ # closing one only when the next is not. Emitting a turn per result
+ # would be a different conversation shape.
+ prev = messages[index - 1].get("role") if index > 0 and isinstance(
+ messages[index - 1], dict) else None
+ nxt = messages[index + 1].get("role") if index + 1 < len(messages) and isinstance(
+ messages[index + 1], dict) else None
+ if prev != "tool":
+ parts.append("<|im_start|>user")
+ parts.append(f"\n<tool_response>\n{text}\n</tool_response>")
+ if nxt != "tool":
+ parts.append("<|im_end|>\n")
+ continue
if role == "assistant":
reasoning = message.get("reasoning_content", "")
if not isinstance(reasoning, str):
raise APIError(400, "`reasoning_content` must be a string.",
f"messages.{index}.reasoning_content")
- text = f"<think>\n{reasoning.strip()}\n</think>\n\n{text}"
+ calls = message.get("tool_calls")
+ rendered = f"<think>\n{reasoning.strip()}\n</think>\n\n{text}"
+ if calls:
+ rendered += _qwen38_tool_calls(calls, bool(text.strip()), index)
+ parts.append(f"<|im_start|>assistant\n{rendered}<|im_end|>\n")
+ continue
parts.append(f"<|im_start|>{role}\n{text}<|im_end|>\n")
parts.append("<|im_start|>assistant\n")
diff --git a/c/tests/test_family_registry.py b/c/tests/test_family_registry.py
index 54c01fec..00d4c984 100644
--- a/c/tests/test_family_registry.py
+++ b/c/tests/test_family_registry.py
@@ -1066,6 +1066,37 @@ class FamilyRegistryTest(unittest.TestCase):
self.assertEqual(checks["engine.binary"]["status"], "fail")
self.assertEqual(report["status"], "error")
+ def test_tools_capability_matches_what_the_renderer_actually_does(self):
+ """The `tools` flag must agree with the gateway's behaviour.
+
+ It is descriptive -- it only feeds the capability dict -- which is
+ exactly why it drifted: glm53 and kimi both render and parse tool calls
+ while sharing a COMMON_CAP that said they do not, and nothing failed to
+ tell anyone. A client asking what a family supports was told the
+ opposite of the truth. Ask the renderer instead of trusting the flag.
+ """
+ import openai_server
+
+ probe = [{"role": "user", "content": "hi"}]
+ tool = [{"type": "function",
+ "function": {"name": "f", "description": "d",
+ "parameters": {"type": "object", "properties": {}}}}]
+ for family in FAMILIES:
+ renderer = getattr(openai_server, f"render_chat_{family.id}", None)
+ if renderer is None: # kimi/deepseek build their payload in C
+ continue
+ refused = False
+ try:
+ renderer(probe, tools=tool)
+ except openai_server.APIError as exc:
+ refused = getattr(exc, "code", None) == "unsupported_parameter"
+ except Exception: # nothing else here is a capability answer
+ continue
+ self.assertEqual(
+ family.capabilities.tools, not refused,
+ f"{family.id}: registry says tools={family.capabilities.tools} but the "
+ f"renderer {'refuses' if refused else 'accepts'} them")
+
def test_build_install_ci_and_release_cover_registered_engines(self):
repo = Path(__file__).resolve().parents[2]
makefile = (repo / "c" / "Makefile").read_text(encoding="utf-8")
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index 792c43eb..b76bc4da 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -19,7 +19,7 @@ from openai_server import (APIError, APIHandler, APIServer, ClientCancelled,
READY, Engine, InklingStreamSplit, StopFilter, ThinkingStreamSplit,
_engine_error, cap_for_arch, conversation_cache_slot, model_arch,
generation_options, parse_tool_calls, parse_dsv4_tool_calls,
- parse_arch_tool_calls, parse_k3_tool_calls,
+ parse_arch_tool_calls, parse_k3_tool_calls, parse_qwen38_tool_calls,
read_engine_turn, render_chat, render_chat_kimi, render_chat_olmoe,
render_chat_qwen38, render_chat_v4, _dsv4_tool_calls, serve,
split_thinking_reply,
@@ -116,15 +116,63 @@ class TemplateTest(unittest.TestCase):
"<|im_start|>user\nHi<|im_end|>\n"
"<|im_start|>assistant\n<think>\n\n</think>\n\n")
- def test_qwen38_rejects_tools_and_non_text_content(self):
- with self.assertRaisesRegex(APIError, "qwen38 engine"):
- render_chat_qwen38([{"role": "user", "content": "Hi"}],
- tools=[{"type": "function"}])
+ def test_qwen38_still_rejects_non_text_content(self):
+ # Tools are wired up now; images are not. The engine is text-only, so a
+ # picture must still be refused rather than silently dropped.
with self.assertRaisesRegex(APIError, "text message content only"):
render_chat_qwen38([{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": "x"}}
]}])
+ def test_qwen38_renders_and_parses_its_own_tool_format(self):
+ tool = {"type": "function", "function": {
+ "name": "weather", "description": "w",
+ "parameters": {"type": "object",
+ "properties": {"city": {"type": "string"},
+ "days": {"type": "integer"}}}}}
+ prompt = render_chat_qwen38([{"role": "user", "content": "Rome?"}], tools=[tool])
+ # The declaration teaches the model the syntax it must emit, so the
+ # preamble is transcribed from chat_template.jinja and not paraphrased.
+ self.assertIn("# Tools\n\nYou have access to the following functions:\n\n<tools>",
+ prompt)
+ self.assertIn("<function=example_function_name>", prompt)
+ self.assertIn("</tools>", prompt)
+
+ # A call with no preceding text attaches directly; one with text is
+ # separated by a blank line. Getting that wrong changes the prompt.
+ with_text = render_chat_qwen38([
+ {"role": "user", "content": "Rome?"},
+ {"role": "assistant", "content": "Checking.", "tool_calls": [
+ {"type": "function", "function": {
+ "name": "weather", "arguments": {"city": "Rome"}}}]},
+ {"role": "tool", "content": "clear"},
+ {"role": "user", "content": "thanks"},
+ ], tools=[tool])
+ self.assertIn("Checking.\n\n<tool_call>\n<function=weather>\n"
+ "<parameter=city>\nRome\n</parameter>\n</function>\n</tool_call>",
+ with_text)
+ # Consecutive tool results share one user turn.
+ self.assertIn("<|im_start|>user\n<tool_response>\nclear\n</tool_response><|im_end|>",
+ with_text)
+
+ text, calls = parse_qwen38_tool_calls(
+ "Sure.\n\n<tool_call>\n<function=weather>\n<parameter=city>\nRome\n"
+ "</parameter>\n<parameter=days>\n3\n</parameter>\n</function>\n</tool_call>",
+ [tool])
+ self.assertEqual(text, "Sure.")
+ self.assertEqual(len(calls), 1)
+ self.assertEqual(calls[0]["function"]["name"], "weather")
+ # The template writes a string argument unquoted, so the type comes back
+ # from the declared schema: city stays a string, days becomes an int.
+ self.assertEqual(json.loads(calls[0]["function"]["arguments"]),
+ {"city": "Rome", "days": 3})
+
+ def test_qwen38_tool_choice_none_suppresses_the_declaration(self):
+ tool = {"type": "function", "function": {"name": "f", "description": "d"}}
+ prompt = render_chat_qwen38([{"role": "user", "content": "Hi"}],
+ tools=[tool], tool_choice="none")
+ self.assertNotIn("<tools>", prompt)
+
def test_kimi_payload_preserves_utf8_lengths_and_turns(self):
prompt = render_chat_kimi([
{"role": "system", "content": "Be precise."},
diff --git a/c/tests/test_qwen38_chat_template.py b/c/tests/test_qwen38_chat_template.py
new file mode 100644
index 00000000..73dd631b
--- /dev/null
+++ b/c/tests/test_qwen38_chat_template.py
@@ -0,0 +1,213 @@
+#!/usr/bin/env python3
+"""Il renderer di Qwen3.8 nel gateway, contro chat_template.jinja ufficiale.
+
+Il gateway rende i prompt a mano invece di far girare jinja a ogni richiesta.
+Quella scelta si paga in un modo solo: la copia scritta a mano puo' scostarsi
+dall'originale senza che nessuno se ne accorga, perche' il modello risponde
+comunque. Qui pesa piu' che altrove, perche' il blocco degli strumenti di
+Qwen3.8 non e' JSON ma un formato suo:
+
+ <tool_call>
+ <function=NOME>
+ <parameter=CHIAVE>
+ VALORE
+ </parameter>
+ </function>
+ </tool_call>
+
+ed e' la dichiarazione stessa a insegnare al modello la sintassi che deve
+emettere. Un preambolo parafrasato e' un preambolo che il modello non ha mai
+visto: non da' errore, da' chiamate malformate.
+
+Il template vero viene reso con jinja2 e confrontato byte per byte con quello
+che produce il gateway. Se manca il template il test si dichiara SALTATO invece
+di passare: un test che non ha trovato il suo riferimento non ha verificato
+niente, e dirlo verde sarebbe peggio che non averlo.
+
+USO:
+ python3 tests/test_qwen38_chat_template.py --template PATH/chat_template.jinja
+"""
+import argparse
+import json
+import sys
+from pathlib import Path
+
+METEO = {"type": "function", "function": {
+ "name": "meteo", "description": "Il tempo che fa",
+ "parameters": {"type": "object",
+ "properties": {"citta": {"type": "string"},
+ "giorni": {"type": "integer"}},
+ "required": ["citta"]}}}
+ORA = {"type": "function", "function": {"name": "ora", "description": "L'ora corrente"}}
+
+CASES = {
+ "senza strumenti": {
+ "messages": [{"role": "user", "content": "ciao"}],
+ },
+ "un solo strumento": {
+ "messages": [{"role": "user", "content": "che tempo fa a Roma?"}],
+ "tools": [METEO],
+ },
+ "due strumenti": {
+ "messages": [{"role": "user", "content": "x"}],
+ "tools": [METEO, ORA],
+ },
+ "strumenti piu' messaggio di sistema": {
+ "messages": [{"role": "system", "content": "sii breve"},
+ {"role": "user", "content": "che ora e'?"}],
+ "tools": [ORA],
+ },
+ "chiamata senza testo che la precede": {
+ "messages": [
+ {"role": "user", "content": "che tempo fa a Roma?"},
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"type": "function", "function": {
+ "name": "meteo", "arguments": {"citta": "Roma"}}}]},
+ {"role": "tool", "content": "sereno, 24 gradi"},
+ {"role": "user", "content": "e domani?"},
+ ],
+ "tools": [METEO],
+ },
+ "chiamata preceduta da testo": {
+ "messages": [
+ {"role": "user", "content": "che tempo fa a Roma?"},
+ {"role": "assistant", "content": "Controllo subito.", "tool_calls": [
+ {"type": "function", "function": {
+ "name": "meteo", "arguments": {"citta": "Roma"}}}]},
+ {"role": "tool", "content": "sereno"},
+ {"role": "user", "content": "grazie"},
+ ],
+ "tools": [METEO],
+ },
+ "due chiamate nello stesso turno": {
+ "messages": [
+ {"role": "user", "content": "meteo e ora"},
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"type": "function", "function": {
+ "name": "meteo", "arguments": {"citta": "Roma"}}},
+ {"type": "function", "function": {"name": "ora", "arguments": {}}}]},
+ {"role": "tool", "content": "sereno"},
+ {"role": "tool", "content": "14:30"},
+ {"role": "user", "content": "ok"},
+ ],
+ "tools": [METEO, ORA],
+ },
+ "argomento non stringa": {
+ "messages": [
+ {"role": "user", "content": "meteo Roma tre giorni"},
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"type": "function", "function": {
+ "name": "meteo", "arguments": {"citta": "Roma", "giorni": 3}}}]},
+ {"role": "tool", "content": "sereno"},
+ {"role": "user", "content": "ok"},
+ ],
+ "tools": [METEO],
+ },
+ "turno precedente con ragionamento": {
+ "messages": [
+ {"role": "user", "content": "a"},
+ {"role": "assistant", "content": "b", "reasoning_content": "rifletto"},
+ {"role": "user", "content": "c"},
+ ],
+ },
+}
+
+EFFORTS = ("xhigh", "medium", "low")
+
+
+def reference(template_text, *, messages, tools=None, reasoning_effort=None):
+ import jinja2
+
+ def raise_exception(message):
+ raise RuntimeError(message)
+
+ environment = jinja2.Environment(trim_blocks=False, lstrip_blocks=False,
+ extensions=["jinja2.ext.loopcontrols"])
+ environment.filters["tojson"] = (
+ lambda value, ensure_ascii=False, **kw: json.dumps(value, ensure_ascii=ensure_ascii))
+ environment.globals["raise_exception"] = raise_exception
+ rendered = environment.from_string(template_text)
+ arguments = {"messages": messages, "add_generation_prompt": True,
+ "enable_thinking": True}
+ if tools:
+ arguments["tools"] = tools
+ if reasoning_effort:
+ arguments["reasoning_effort"] = reasoning_effort
+ return rendered.render(**arguments)
+
+
+def show(label, ours, theirs):
+ print(f"FAIL {label}")
+ for index, (a, b) in enumerate(zip(ours.splitlines(), theirs.splitlines())):
+ if a != b:
+ print(f" prima differenza alla riga {index + 1}")
+ print(f" gateway: {a!r}")
+ print(f" template: {b!r}")
+ return
+ print(f" lunghezze diverse: gateway {len(ours)}, template {len(theirs)}")
+ print(f" coda gateway: {ours[-120:]!r}")
+ print(f" coda template: {theirs[-120:]!r}")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--template", type=Path, required=True)
+ arguments = parser.parse_args()
+
+ if not arguments.template.exists():
+ print(f"SKIP: manca {arguments.template}; il riferimento non c'e' e "
+ f"questo test non ha verificato nulla")
+ return 0
+ try:
+ import jinja2 # noqa: F401
+ except ImportError:
+ print("SKIP: jinja2 non installato; senza non c'e' riferimento")
+ return 0
+
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+ import openai_server
+
+ openai_server.ARCH = "qwen38"
+ template_text = arguments.template.read_text(encoding="utf-8")
+
+ failures = 0
+ for effort in EFFORTS:
+ for label, case in CASES.items():
+ name = f"{label} [{effort}]"
+ theirs = reference(template_text, messages=case["messages"],
+ tools=case.get("tools"), reasoning_effort=effort)
+ ours = openai_server.render_chat_qwen38(
+ case["messages"], enable_thinking=True, reasoning_effort=effort,
+ tools=case.get("tools"))
+ if ours == theirs:
+ print(f"ok {name}")
+ else:
+ show(name, ours, theirs)
+ failures += 1
+
+ # Il giro completo: rendere una chiamata e rileggerla deve restituire quello
+ # che ci era stato dato. E' la meta' che il confronto col template non copre,
+ # perche' il template sa solo scrivere.
+ reply = ("Controllo.\n\n<tool_call>\n<function=meteo>\n<parameter=citta>\n"
+ "Roma\n</parameter>\n<parameter=giorni>\n3\n</parameter>\n"
+ "</function>\n</tool_call>")
+ text, calls = openai_server.parse_qwen38_tool_calls(reply, [METEO])
+ expected = {"citta": "Roma", "giorni": 3}
+ got = json.loads(calls[0]["function"]["arguments"]) if calls else None
+ if len(calls) == 1 and calls[0]["function"]["name"] == "meteo" and got == expected \
+ and text == "Controllo.":
+ print("ok andata e ritorno: chiamata riletta, interi restituiti come interi")
+ else:
+ print(f"FAIL andata e ritorno: {calls!r} testo={text!r}")
+ failures += 1
+
+ print()
+ if failures:
+ print(f"TEST FAIL ({failures} casi)")
+ return 1
+ print("template Qwen3.8: il gateway e' identico al riferimento")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/docs/qwen38.md b/docs/qwen38.md
index e7c30aac..cbb33785 100644
--- a/docs/qwen38.md
+++ b/docs/qwen38.md
@@ -30,7 +30,33 @@ COLI_MODEL=~/Models/Qwen3.8-Flash-Next-FP8 ./c/coli chat
`coli serve` and `coli web` use the same text-only gateway path. Qwen3.8 thinks
by default; `reasoning_effort` accepts `low`, `medium`, `high`, and `xhigh`, and
`enable_thinking: false` emits the model's official empty thinking prefix.
-Tools, image content, audio, and grammar constraints are rejected explicitly.
+Image content, audio and grammar constraints are rejected explicitly.
+
+Tool calling works. Qwen3.8 declares and emits calls in an XML-ish form of
+its own rather than the JSON block GLM uses, so it has its own renderer and
+its own parser:
+
+```
+<tool_call>
+<function=NAME>
+<parameter=KEY>
+VALUE
+</parameter>
+</function>
+</tool_call>
+```
+
+Both sides are transcribed from `chat_template.jinja` rather than
+paraphrased, because the declaration is what teaches the model the syntax it
+must emit: a preamble it has never seen is a different prompt. The whole
+rendering is pinned byte for byte against the official template
+(`tests/test_qwen38_chat_template.py`, 27 cases across the three reasoning
+levels).
+
+One asymmetry worth knowing: the template writes a string argument unquoted,
+so a value's original type is not recoverable from the text alone. The parser
+reads the declared schema and restores numbers and booleans from it, and
+leaves anything the schema did not describe as a string rather than guessing.
The official FP8 repository is about 185.5 GB in decimal units (roughly 173
GiB). The default CPU engine keeps resident BF16 matrices in their native