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

api: add Qwen3.6 tool calling

GenericRikka2cb51e8294b1
diff --git a/c/openai_server.py b/c/openai_server.py
index b4e093ed..fdab0091 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -442,7 +442,7 @@ _PARTIAL_END_RE = re.compile(r"<(?:/(?:t(?:o(?:o(?:l(?:_(?:c(?:a(?:l)?)?)?)?)?)?
# <arg_key>K</arg_key><arg_value> structure. Default OFF (never rewrites well-formed output).
_SALVAGE = os.environ.get("COLI_TOOL_SALVAGE", "0") == "1"
-# Families whose chat template has no tool syntax at all (OLMoE, Qwen3.6) refuse
+# Families whose chat template has no tool syntax at all (OLMoE) refuse
# tools[] and role:"tool" rather than invent a format. COLI_TOOL_FALLBACK=1 opts
# into a prompt-injected translation for them: the declaration block, the prior
# assistant calls and the tool results are written as ordinary turns, in the
@@ -964,8 +964,8 @@ def _parse_arch_tool_calls(reply, tools, tool_reply, track_spans):
_sideband_text, calls = parse_k3_tool_calls(tool_reply, tools)
return reply.strip(), calls, None, None
return parse_k3_tool_calls(reply, tools) + (None, None) # pre-#1147 engines
- if chat_flavor() == "qwen38":
- return parse_qwen38_tool_calls(reply, tools) + (None, None)
+ if chat_flavor() in ("qwen36", "qwen38"):
+ return parse_qwen_tool_calls(reply, tools) + (None, None)
return _parse_tool_calls(reply, tools, track_spans)
@@ -1679,7 +1679,7 @@ def render_chat_olmoe(messages, enable_thinking=False, reasoning_effort=None, to
def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, tools=None,
tool_choice=None, add_generation_prompt=True, preserve_thinking=False):
- """Text-only subset of Qwen3.6's chat_template: <|im_start|>role\\n ...
+ """Qwen3.6's chat_template, tool calling included: <|im_start|>role\\n ...
<|im_end|>\\n frames, then the generation prompt. The official template
opens a mandatory <think> block after `<|im_start|>assistant\\n` — the
model was never trained on the bare `assistant\\n` state, and greedy
@@ -1687,6 +1687,11 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, too
disabled the template pre-closes the block instead; both branches are
mirrored here byte for byte.
+ Tool declarations, assistant tool calls and tool responses follow the checkpoint's
+ chat_template.jinja: the `# Tools` block opens the one system turn (the client's own
+ system text goes last in it), calls are the XML-ish <tool_call> form Qwen3.8 shares,
+ and consecutive `tool` messages share ONE user turn of <tool_response> blocks.
+
add_generation_prompt=False continues a trailing assistant turn. The template renders an
assistant turn AFTER the last user query with its <think></think> block (an earlier one,
from history, has it stripped) -- so the open-turn shape is that think-form minus the
@@ -1703,6 +1708,8 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, too
raise APIError(400, "`messages` must be a non-empty array.", "messages")
if tool_choice == "none":
tools = None
+ if tools is not None and not isinstance(tools, list):
+ raise APIError(400, "`tools` must be an array.", "tools")
# The template's last_query_index: the last user turn that is a real query and not a
# tool result riding in as one. An assistant turn after it keeps its <think> block
# with or without preserve_thinking. With no query at all the template raises; here
@@ -1717,27 +1724,37 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, too
if not (query.startswith("<tool_response>") and query.endswith("</tool_response>")):
last_query = index
break
- if (tools or tool_choice not in (None, "none")) and not _TOOL_FALLBACK:
- raise APIError(400, "Tool use is not wired up for the qwen36 engine yet. "
- "Set COLI_TOOL_FALLBACK=1 to opt into prompt-injected "
- "tool translation.", "tools", "unsupported_parameter")
parts = []
- if tools and _TOOL_FALLBACK:
- parts.append("<|im_start|>system\n"
- + _fallback_tool_preamble(tools) + "<|im_end|>\n")
- for index, message in enumerate(messages):
+ # With tools the template builds ONE system turn: the tool block, then the client's
+ # own system text (trimmed) after a blank line.
+ first = messages[0]
+ first_role = first.get("role") if isinstance(first, dict) else None
+ system_text = ""
+ start = 0
+ if first_role in ("system", "developer"):
+ raw = first.get("content")
+ system_text = content_text(raw, "messages.0.content").strip() if raw is not None else ""
+ start = 1
+ if tools:
+ block = _qwen_tool_block(tools)
+ if system_text:
+ block += "\n\n" + system_text
+ parts.append(f"<|im_start|>system\n{block}<|im_end|>\n")
+ elif start:
+ parts.append(f"<|im_start|>system\n{system_text}<|im_end|>\n")
+ for index, message in enumerate(messages[start:], start=start):
if not isinstance(message, dict):
raise APIError(400, "Each message must be an object.", f"messages.{index}")
role = message.get("role")
if role == "developer":
role = "system"
- allowed = ("system", "user", "assistant")
- if _TOOL_FALLBACK:
- allowed += ("tool",)
- if role not in allowed:
+ if role not in ("system", "user", "assistant", "tool"):
raise APIError(400, f"Unsupported role {role!r}.", f"messages.{index}.role")
+ if role == "system":
+ raise APIError(400, "System message must be at the beginning.",
+ f"messages.{index}.role")
raw = message.get("content")
- text = content_text(raw, f"messages.{index}.content") if raw is not None else ""
+ text = content_text(raw, f"messages.{index}.content").strip() if raw is not None else ""
if not add_generation_prompt and role == "assistant" and index == len(messages) - 1:
# Continued turn: the template gives a post-query assistant turn a <think></think>
# block, then the model resumes the content. Match it, minus the terminator/cue.
@@ -1746,27 +1763,44 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, too
raise APIError(400, "`reasoning_content` must be a string.",
f"messages.{index}.reasoning_content")
parts.append(f"<|im_start|>assistant\n<think>\n{reasoning.strip()}\n</think>\n\n"
- f"{text.strip()}")
+ f"{text}")
continue
if role == "tool":
- # No tool role in this template: the result rides in as a user turn.
- parts.append("<|im_start|>user\n"
- + _fallback_tool_result(message, index) + "<|im_end|>\n")
+ # Consecutive tool results share ONE user turn: the opening tag is written only
+ # when the previous message was not a tool, the closing one only when the next
+ # is not.
+ 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":
# The template's reading of a past turn: `reasoning_content` when it is a
# string, otherwise whatever the content carries before a </think> (a client
# echoing the raw reply), which then leaves the content.
reasoning = message.get("reasoning_content")
- if not isinstance(reasoning, str):
+ if reasoning is not None and not isinstance(reasoning, str):
+ raise APIError(400, "`reasoning_content` must be a string.",
+ f"messages.{index}.reasoning_content")
+ if reasoning is None:
reasoning = ""
if "</think>" in text:
reasoning = text.split("</think>")[0].rstrip("\n").split("<think>")[-1].lstrip("\n")
text = text.split("</think>")[-1].lstrip("\n")
if preserve_thinking or index > last_query:
- text = f"<think>\n{reasoning.strip()}\n</think>\n\n{text}"
- if role == "assistant" and _TOOL_FALLBACK:
- text += _fallback_tool_calls(message.get("tool_calls"), index)
+ rendered = f"<think>\n{reasoning.strip()}\n</think>\n\n{text}"
+ else:
+ rendered = text
+ calls = message.get("tool_calls")
+ if calls:
+ rendered += _qwen_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")
if add_generation_prompt:
parts.append("<|im_start|>assistant\n")
@@ -1774,11 +1808,10 @@ 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.
+# Qwen3.6 and Qwen3.8 declare and emit tool calls using the same XML-ish wire
+# format rather than GLM's JSON block or DeepSeek's DSML. Keep the shared
+# declaration and call syntax transcribed from chat_template.jinja rather than
+# paraphrased: the declaration is what teaches the model the syntax it must emit.
#
# <tool_call>
# <function=NAME>
@@ -1787,20 +1820,20 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, too
# </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>")
+QWEN_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):
+def _qwen_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)
+ lines.append(QWEN_TOOL_PREAMBLE)
return "".join(lines)
-def _qwen38_tool_calls(tool_calls, has_content, index):
+def _qwen_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
@@ -1838,13 +1871,13 @@ def _qwen38_tool_calls(tool_calls, has_content, index):
return "".join(out)
-QWEN38_CALL_RE = re.compile(
+QWEN_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)
+QWEN_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`.
+def parse_qwen_tool_calls(reply, tools=None):
+ """Parse Qwen'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
@@ -1854,14 +1887,15 @@ def parse_qwen38_tool_calls(reply, tools=None):
schema = {}
for tool in (tools or []):
fn = tool.get("function", tool) if isinstance(tool, dict) else {}
+ name = fn.get("name")
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()
+ if isinstance(name, str) and name:
+ if isinstance(params, dict):
+ schema[name] = params
+
+ def make_call(name, body):
args = {}
- for key, raw in QWEN38_PARAM_RE.findall(match.group(2)):
+ for key, raw in QWEN_PARAM_RE.findall(body):
key = key.strip()
declared = (schema.get(name) or {}).get(key) or {}
kind = declared.get("type") if isinstance(declared, dict) else None
@@ -1872,20 +1906,38 @@ def parse_qwen38_tool_calls(reply, tools=None):
args[key] = json.loads(raw)
except (TypeError, ValueError):
args[key] = raw
- calls.append({
+ return {
"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")
+ "function": {
+ "name": name,
+ "arguments": json.dumps(args, ensure_ascii=False),
+ },
+ }
+
+ calls = []
+ for match in QWEN_CALL_RE.finditer(reply or ""):
+ name = match.group(1).strip()
+ calls.append(make_call(name, match.group(2)))
+
+ text = QWEN_CALL_RE.sub("", reply or "")
+
+ if not calls and tools and (
+ "<tool_call>" in (reply or "") or "<function=" in (reply or "")
+ ):
+ sys.stderr.write(
+ "[api] qwen tool markers present but no call parsed -- "
+ "possibly truncated or mangled output\n"
+ )
sys.stderr.flush()
+
return text.strip(), calls
+# Backward compatibility for existing Qwen3.8 callers.
+parse_qwen38_tool_calls = parse_qwen_tool_calls
+
+
def render_chat_qwen38(messages, enable_thinking=True, reasoning_effort=None, tools=None,
tool_choice=None, add_generation_prompt=True):
"""Text-only Qwen3.8 chat-template subset with native reasoning hints.
@@ -1938,7 +1990,7 @@ def render_chat_qwen38(messages, enable_thinking=True, reasoning_effort=None, to
# 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)
+ block = head + _qwen_tool_block(tools)
if system_text:
block += "\n\n" + system_text
parts.append(f"<|im_start|>system\n{block}<|im_end|>\n")
@@ -1985,11 +2037,12 @@ def render_chat_qwen38(messages, enable_thinking=True, reasoning_effort=None, to
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)
+ rendered += _qwen_tool_calls(calls, bool(text.strip()), index)
# A continued turn is the last message rendered open: no <|im_end|>, no cue.
terminator = "" if (not add_generation_prompt and index == len(messages) - 1) \
else "<|im_end|>\n"
parts.append(f"<|im_start|>assistant\n{rendered}{terminator}")
+
continue
parts.append(f"<|im_start|>{role}\n{text}<|im_end|>\n")
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index 89978702..782b4dee 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -26,7 +26,8 @@ from openai_server import (APIError, APIHandler, APIServer, ClientCancelled,
conversation_cache_slot, model_arch,
generation_options, parse_tool_calls, parse_dsv4_tool_calls,
parse_arch_tool_calls, parse_k3_tool_calls, parse_qwen38_tool_calls,
- read_engine_turn, render_chat, render_chat_for_arch,
+ parse_qwen_tool_calls,
+ read_engine_turn, render_chat, render_chat_qwen, render_chat_for_arch,
render_chat_glm53, render_chat_inkling, render_chat_kimi,
render_chat_olmoe, render_chat_qwen,
render_chat_qwen38, render_chat_v4, render_chat_dsv41,
@@ -430,7 +431,7 @@ class TemplateTest(unittest.TestCase):
self.assertIn("<|im_start|>user\n<tool_response>\nclear\n</tool_response><|im_end|>",
with_text)
- text, calls = parse_qwen38_tool_calls(
+ text, calls = parse_qwen_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])
@@ -899,6 +900,245 @@ class TemplateTest(unittest.TestCase):
with self.assertRaises(APIError):
stop_policy({"x_colibri_ignore_leading_stop": "yes"}, True)
+class Qwen36ToolCallTest(unittest.TestCase):
+ WEATHER = [{
+ "type": "function",
+ "function": {
+ "name": "weather",
+ "description": "Get weather for a city.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "city": {"type": "string"},
+ "days": {"type": "integer"},
+ },
+ "required": ["city"],
+ },
+ },
+ }]
+
+ def test_qwen36_renders_tool_declaration(self):
+ prompt = render_chat_qwen(
+ [{"role": "user", "content": "Weather in Rome?"}],
+ tools=self.WEATHER,
+ )
+
+ self.assertIn(
+ "# Tools\n\nYou have access to the following functions:\n\n<tools>",
+ prompt,
+ )
+ self.assertIn('"name": "weather"', prompt)
+ self.assertIn("</tools>", prompt)
+ self.assertIn("<function=example_function_name>", prompt)
+
+ def test_qwen36_tool_choice_none_suppresses_declaration(self):
+ prompt = render_chat_qwen(
+ [{"role": "user", "content": "Weather?"}],
+ tools=self.WEATHER,
+ tool_choice="none",
+ )
+
+ self.assertNotIn("<tools>", prompt)
+
+ def test_qwen36_renders_assistant_tool_call(self):
+ prompt = render_chat_qwen([
+ {"role": "user", "content": "Weather in Rome?"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [{
+ "id": "call_1",
+ "type": "function",
+ "function": {
+ "name": "weather",
+ "arguments": '{"city":"Rome","days":3}',
+ },
+ }],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_1",
+ "content": "sunny",
+ },
+ ], tools=self.WEATHER)
+
+ self.assertIn(
+ "<tool_call>\n"
+ "<function=weather>\n"
+ "<parameter=city>\n"
+ "Rome\n"
+ "</parameter>\n"
+ "<parameter=days>\n"
+ "3\n"
+ "</parameter>\n"
+ "</function>\n"
+ "</tool_call>",
+ prompt,
+ )
+
+ self.assertIn(
+ "<|im_start|>user\n"
+ "<tool_response>\n"
+ "sunny\n"
+ "</tool_response><|im_end|>",
+ prompt,
+ )
+
+ def test_qwen36_consecutive_tool_results_share_user_turn(self):
+ prompt = render_chat_qwen([
+ {"role": "user", "content": "Check both."},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "a",
+ "type": "function",
+ "function": {
+ "name": "weather",
+ "arguments": '{"city":"Rome"}',
+ },
+ },
+ {
+ "id": "b",
+ "type": "function",
+ "function": {
+ "name": "weather",
+ "arguments": '{"city":"Berlin"}',
+ },
+ },
+ ],
+ },
+ {"role": "tool", "tool_call_id": "a", "content": "sunny"},
+ {"role": "tool", "tool_call_id": "b", "content": "cloudy"},
+ ], tools=self.WEATHER)
+
+ self.assertIn(
+ "<|im_start|>user\n"
+ "<tool_response>\n"
+ "sunny\n"
+ "</tool_response>\n"
+ "<tool_response>\n"
+ "cloudy\n"
+ "</tool_response><|im_end|>",
+ prompt,
+ )
+
+ def test_qwen36_parser_accepts_native_call(self):
+ text, calls = parse_qwen_tool_calls(
+ "Checking.\n\n"
+ "<tool_call>\n"
+ "<function=weather>\n"
+ "<parameter=city>\n"
+ "Rome\n"
+ "</parameter>\n"
+ "<parameter=days>\n"
+ "3\n"
+ "</parameter>\n"
+ "</function>\n"
+ "</tool_call>",
+ self.WEATHER,
+ )
+
+ self.assertEqual(text, "Checking.")
+ self.assertEqual(len(calls), 1)
+ self.assertEqual(calls[0]["function"]["name"], "weather")
+
+ args = json.loads(calls[0]["function"]["arguments"])
+ self.assertEqual(args["city"], "Rome")
+ self.assertEqual(args["days"], 3)
+
+ def test_qwen36_parser_preserves_text_around_native_call(self):
+ reply = (
+ "Checking.\n\n"
+ "<tool_call>\n"
+ "<function=weather>\n"
+ "<parameter=city>\n"
+ "Karlsruhe\n"
+ "</parameter>\n"
+ "</function>\n"
+ "</tool_call>"
+ )
+
+ text, calls = parse_qwen_tool_calls(reply, self.WEATHER)
+
+ self.assertEqual(text, "Checking.")
+ self.assertEqual(len(calls), 1)
+ self.assertEqual(calls[0]["function"]["name"], "weather")
+ self.assertEqual(
+ json.loads(calls[0]["function"]["arguments"]),
+ {"city": "Karlsruhe"},
+ )
+
+ def test_qwen36_preserves_current_query_reasoning_content(self):
+ prompt = render_chat_qwen([
+ {"role": "user", "content": "Think about this."},
+ {
+ "role": "assistant",
+ "reasoning_content": "current reasoning",
+ "content": "answer",
+ },
+ {"role": "tool", "content": "result"},
+ ])
+
+ self.assertIn(
+ "<|im_start|>assistant\n"
+ "<think>\ncurrent reasoning\n</think>\n\n"
+ "answer<|im_end|>",
+ prompt,
+ )
+
+ def test_qwen36_drops_reasoning_before_last_user_query(self):
+ prompt = render_chat_qwen([
+ {"role": "user", "content": "First question."},
+ {
+ "role": "assistant",
+ "reasoning_content": "old private reasoning",
+ "content": "first answer",
+ },
+ {"role": "user", "content": "Second question."},
+ ])
+
+ self.assertNotIn("old private reasoning", prompt)
+ self.assertIn(
+ "<|im_start|>assistant\nfirst answer<|im_end|>",
+ prompt,
+ )
+
+ def test_qwen36_extracts_native_think_history(self):
+ prompt = render_chat_qwen([
+ {"role": "user", "content": "Think about this."},
+ {
+ "role": "assistant",
+ "content": (
+ "<think>\n"
+ "native reasoning\n"
+ "</think>\n\n"
+ "visible answer"
+ ),
+ },
+ {"role": "tool", "content": "result"},
+ ])
+
+ self.assertEqual(prompt.count("native reasoning"), 1)
+ self.assertIn(
+ "<|im_start|>assistant\n"
+ "<think>\nnative reasoning\n</think>\n\n"
+ "visible answer<|im_end|>",
+ prompt,
+ )
+
+ def test_qwen36_rejects_non_string_reasoning_content(self):
+ with self.assertRaises(APIError):
+ render_chat_qwen([
+ {"role": "user", "content": "Question."},
+ {
+ "role": "assistant",
+ "reasoning_content": {"not": "a string"},
+ "content": "answer",
+ },
+ ])
+
class StopFilterTest(unittest.TestCase):
def test_explicit_stop_composes_with_inkling_stream_split(self):
diff --git a/c/tests/test_openai_tools_fallback_e2e.py b/c/tests/test_openai_tools_fallback_e2e.py
index 8e2045aa..575dd109 100644
--- a/c/tests/test_openai_tools_fallback_e2e.py
+++ b/c/tests/test_openai_tools_fallback_e2e.py
@@ -1,15 +1,10 @@
-"""Prompt-injected tool translation for families with no native tool syntax.
-
-OLMoE and Qwen3.6 have no tool tokens in their chat templates, so the gateway
-answers 400 for `tools[]` and for a `role: "tool"` turn rather than invent a
-format. `COLI_TOOL_FALLBACK=1` opts into a translation that writes the
-declaration, the prior assistant calls and the tool results as ordinary turns,
-in the GLM wire format `parse_tool_calls()` already reads back (#1378).
-
-These tests pin both halves of that switch: the default still refuses, and with
-the flag set a full two-turn agent loop completes through
-`/v1/chat/completions`. Runs against a mock engine speaking the SERVE wire
-protocol, so no checkpoint is needed.
+"""End-to-end tool calling for OLMoE and Qwen3.6.
+
+OLMoE retains opt-in prompt-injected tool translation, while Qwen3.6
+supports native tool calling without COLI_TOOL_FALLBACK.
+
+Both implementations are exercised through /v1/chat/completions using
+a mock SERVE engine, without requiring a checkpoint.
"""
import json
import os
@@ -33,7 +28,7 @@ CALL = ("<tool_call>get_weather"
"</tool_call>")
MOCK_ENGINE = r'''#!/usr/bin/env python3
-import sys, os
+import sys, os, re
out, inp = sys.stdout.buffer, sys.stdin.buffer
out.write(b"\x01\x01READY\x01\x01\n" + b"STAT 0 0 0 0 0\n"); out.flush()
@@ -42,6 +37,18 @@ CALL = ("<tool_call>get_weather"
"<arg_key>unit</arg_key><arg_value>celsius</arg_value>"
"</tool_call>")
+QWEN_CALL = (
+ "<tool_call>"
+ "<function=get_weather>"
+ "<parameter=location>\nRome\n</parameter>"
+ "<parameter=unit>\ncelsius\n</parameter>"
+ "</function>"
+ "</tool_call>"
+)
+
+NATIVE_QWEN = os.environ.get("MOCK_NATIVE_QWEN") == "1"
+
+
def reply(rid, text):
data = text.encode("utf-8")
out.write(("DATA %s %d\n" % (rid, len(data))).encode() + data + b"\n"); out.flush()
@@ -57,10 +64,18 @@ while True:
prompt = inp.read(plen).decode("utf-8", "replace"); inp.read(1)
with open(os.environ["MOCK_LOG"], "a") as log:
log.write(prompt + "\n\x00\n")
- if "<tool_response>" in prompt:
+ if NATIVE_QWEN and re.search(
+ r'<\|im_start\|>user\n'
+ r'<tool_response>\n'
+ r'\s*\{"temp_c"\s*:\s*25\}\s*\n'
+ r'</tool_response><\|im_end\|>',
+ prompt,
+ ):
+ reply(rid, "25 degrees and sunny in Rome.")
+ elif not NATIVE_QWEN and "<tool_response>" in prompt:
reply(rid, "25 degrees and sunny in Rome.")
elif "weather in Rome" in prompt:
- reply(rid, CALL)
+ reply(rid, QWEN_CALL if NATIVE_QWEN else CALL)
else:
reply(rid, "Hello from the mock engine.")
'''
@@ -103,7 +118,8 @@ class _FallbackBase(unittest.TestCase):
probe.bind(("127.0.0.1", 0))
cls.port = probe.getsockname()[1]
env = dict(os.environ, MOCK_LOG=str(cls.mock_log),
- COLI_TOOL_FALLBACK=cls.fallback)
+ COLI_TOOL_FALLBACK=cls.fallback,
+ MOCK_NATIVE_QWEN="1" if cls.arch == "qwen36" else "0")
env.pop("COLI_API_KEY", None)
cls.server = subprocess.Popen(
[sys.executable, str(SERVER), "--model", cls.tmp.name,
@@ -180,9 +196,71 @@ class OlmoeToolFallbackE2E(_TwoTurnLoop):
arch = "olmoe"
-class Qwen36ToolFallbackE2E(_TwoTurnLoop):
+class Qwen36NativeToolsE2E(_TwoTurnLoop):
+ """Native Qwen3.6 tool calling works without the fallback flag."""
+
arch = "qwen36"
model_type = "qwen3_5_moe"
+ fallback = "0"
+
+ def test_second_turn_completes(self):
+ mid = self.model_id()
+ msgs = [{"role": "user", "content": "weather in Rome?"}]
+
+ out = self.post({
+ "model": mid,
+ "messages": msgs,
+ "tools": TOOLS,
+ "temperature": 0,
+ "max_tokens": 128,
+ })
+
+ choice = out["choices"][0]
+ self.assertEqual(choice["finish_reason"], "tool_calls")
+ calls = choice["message"]["tool_calls"]
+ self.assertEqual(len(calls), 1)
+
+ msgs.append({
+ "role": "assistant",
+ "content": None,
+ "tool_calls": calls,
+ })
+ msgs.append({
+ "role": "tool",
+ "tool_call_id": calls[0]["id"],
+ "content": json.dumps({"temp_c": 25}),
+ })
+
+ out2 = self.post({
+ "model": mid,
+ "messages": msgs,
+ "tools": TOOLS,
+ "temperature": 0,
+ "max_tokens": 128,
+ })
+
+ self.assertEqual(out2["choices"][0]["finish_reason"], "stop")
+ self.assertEqual(
+ out2["choices"][0]["message"]["content"],
+ "25 degrees and sunny in Rome.",
+ )
+
+ prompts = self.mock_log.read_text()
+ second_prompt = prompts.split("\x00")[-2]
+ call_marker = "<function=get_weather>"
+ response_marker = (
+ '<|im_start|>user\n'
+ '<tool_response>\n'
+ '{"temp_c": 25}\n'
+ '</tool_response><|im_end|>'
+ )
+
+ self.assertIn(call_marker, second_prompt)
+ self.assertIn(response_marker, second_prompt)
+ self.assertLess(
+ second_prompt.index(call_marker),
+ second_prompt.index(response_marker),
+ )
class _RefusedByDefault(_FallbackBase):
@@ -213,9 +291,74 @@ class OlmoeToolRefusedByDefault(_RefusedByDefault):
arch = "olmoe"
-class Qwen36ToolRefusedByDefault(_RefusedByDefault):
+class Qwen36ToolAcceptedByDefault(_FallbackBase):
+ """Qwen3.6 accepts native tools without the fallback flag."""
+
arch = "qwen36"
model_type = "qwen3_5_moe"
+ fallback = "0"
+
+ def test_tools_accepted(self):
+ out = self.post({
+ "model": self.model_id(),
+ "messages": [
+ {"role": "user", "content": "weather in Rome?"}
+ ],
+ "tools": TOOLS,
+ "temperature": 0,
+ "max_tokens": 128,
+ })
+
+ choice = out["choices"][0]
+ self.assertEqual(choice["finish_reason"], "tool_calls")
+
+ calls = choice["message"]["tool_calls"]
+ self.assertEqual(len(calls), 1)
+ self.assertEqual(
+ calls[0]["function"]["name"],
+ "get_weather",
+ )
+
+ def test_tool_role_accepted(self):
+ out = self.post({
+ "model": self.model_id(),
+ "messages": [
+ {
+ "role": "user",
+ "content": "weather in Rome?",
+ },
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{
+ "id": "call_test",
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "arguments": json.dumps({
+ "location": "Rome",
+ "unit": "celsius",
+ }),
+ },
+ }],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_test",
+ "content": json.dumps({"temp_c": 25}),
+ },
+ ],
+ "tools": TOOLS,
+ "temperature": 0,
+ "max_tokens": 128,
+ })
+
+ choice = out["choices"][0]
+ self.assertEqual(choice["finish_reason"], "stop")
+ self.assertIn(
+ "25",
+ choice["message"]["content"] or "",
+ )
# The shared base classes must not run as tests themselves.
diff --git a/c/tests/test_qwen36_chat_template.py b/c/tests/test_qwen36_chat_template.py
index a3ab3101..2067bdff 100644
--- a/c/tests/test_qwen36_chat_template.py
+++ b/c/tests/test_qwen36_chat_template.py
@@ -5,9 +5,9 @@ Il gateway rende i prompt a mano invece di far girare jinja a ogni richiesta, e
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 il template vero viene reso con jinja2 e confrontato byte per byte
-con quello che produce il gateway, senza strumenti (che il motore qwen36 non
-espone) e sui due rami del blocco di ragionamento, per ciascuno con e senza
-preserve_thinking (#1759), piu' il turno aperto della prosecuzione.
+con quello che produce il gateway, con e senza strumenti, sui due rami del
+blocco di ragionamento, per ciascuno con e senza preserve_thinking (#1759),
+piu' il turno aperto della prosecuzione.
Se manca il template o jinja2, il test si dichiara SALTATO invece di passare: un
test che non ha trovato il suo riferimento non ha verificato niente, e dirlo
@@ -61,14 +61,67 @@ CASES = {
"messages": [{"role": "user", "content": "1+1?"},
{"role": "assistant", "content": "2"}],
},
+ "dichiarazione e chiamata tool": {
+ "messages": [{"role": "user", "content": "Weather in Rome?"},
+ {"role": "assistant", "content": "", "tool_calls": [{
+ "type": "function", "function": {
+ "name": "weather", "arguments": {"city": "Rome"}}}]}],
+ "tools": [{"type": "function", "function": {
+ "name": "weather", "description": "Get weather for a city.",
+ "parameters": {"type": "object", "properties": {
+ "city": {"type": "string"}}, "required": ["city"]}}}],
+ },
+ "risposta tool": {
+ "messages": [{"role": "user", "content": "Weather in Rome?"},
+ {"role": "assistant", "content": "", "tool_calls": [{
+ "type": "function", "function": {
+ "name": "weather", "arguments": {"city": "Rome"}}}]},
+ {"role": "tool", "content": "sunny", "tool_call_id": "call_1"},
+ {"role": "assistant", "content": "Sunny."}],
+ "tools": [{"type": "function", "function": {
+ "name": "weather", "description": "Get weather for a city.",
+ "parameters": {"type": "object", "properties": {
+ "city": {"type": "string"}}, "required": ["city"]}}}],
+ },
+ # Un giro d'agente completo: sistema piegato nel blocco strumenti, ragionamento e
+ # testo prima di due chiamate parallele (argomenti non stringa: tojson), due risposte
+ # nello stesso turno utente, poi una domanda nuova che fa perdere il blocco ai turni
+ # vecchi (senza preserve_thinking).
+ "giro d'agente con chiamate parallele": {
+ "messages": [{"role": "system", "content": " Sei un agente. "},
+ {"role": "user", "content": "Meteo a Roma e Milano?"},
+ {"role": "assistant", "content": "Controllo.",
+ "reasoning_content": "servono due chiamate",
+ "tool_calls": [
+ {"type": "function", "function": {
+ "name": "weather",
+ "arguments": {"city": "Roma", "days": 2, "metric": True}}},
+ {"type": "function", "function": {
+ "name": "weather",
+ "arguments": {"city": "Milano", "opts": {"a": [1, 2]}}}}]},
+ {"role": "tool", "content": "sole", "tool_call_id": "c1"},
+ {"role": "tool", "content": "pioggia", "tool_call_id": "c2"},
+ {"role": "assistant", "content": "Roma sole, Milano pioggia."},
+ {"role": "user", "content": "grazie"}],
+ "tools": [{"type": "function", "function": {
+ "name": "weather", "description": "Get weather for a city.",
+ "parameters": {"type": "object", "properties": {
+ "city": {"type": "string"}, "days": {"type": "integer"}},
+ "required": ["city"]}}}],
+ },
+ # Un turno di sistema vuoto senza strumenti: il template lo scrive lo stesso.
+ "sistema vuoto": {
+ "messages": [{"role": "system", "content": ""},
+ {"role": "user", "content": "ciao"}],
+ },
}
THINKING = (True, False)
PRESERVE = (False, True)
-def reference(template_text, *, messages, enable_thinking=True, add_generation_prompt=True,
- preserve_thinking=False):
+def reference(template_text, *, messages, tools=None, enable_thinking=True,
+ add_generation_prompt=True, preserve_thinking=False):
import jinja2
def raise_exception(message):
@@ -81,7 +134,8 @@ def reference(template_text, *, messages, enable_thinking=True, add_generation_p
environment.globals["raise_exception"] = raise_exception
rendered = environment.from_string(template_text)
return rendered.render(messages=messages, add_generation_prompt=add_generation_prompt,
- enable_thinking=enable_thinking, preserve_thinking=preserve_thinking)
+ enable_thinking=enable_thinking, tools=tools,
+ preserve_thinking=preserve_thinking)
def show(label, ours, theirs):
@@ -125,9 +179,11 @@ def main() -> int:
name = (f"{label} [thinking={enable_thinking} "
f"preserve_thinking={preserve_thinking}]")
theirs = reference(template_text, messages=case["messages"],
+ tools=case.get("tools"),
enable_thinking=enable_thinking,
preserve_thinking=preserve_thinking)
ours = openai_server.render_chat_qwen(case["messages"],
+ tools=case.get("tools"),
enable_thinking=enable_thinking,
preserve_thinking=preserve_thinking)
if ours == theirs:
diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md
index 30dfa551..5d5f0074 100644
--- a/docs/SETTINGS.md
+++ b/docs/SETTINGS.md
@@ -119,7 +119,7 @@ Run directly (or via `coli serve`). OpenAI-compatible `/v1/chat/completions`.
| `--queue-timeout` | `$COLI_QUEUE_TIMEOUT` or `300` | Request queue timeout (s). |
| `--kv-slots` | `$COLI_KV_SLOTS` or `1` | KV conversation slots. |
-Tool calling is supported by GLM and DeepSeek V4; Inkling, Kimi K3, and OLMoE reject active tool declarations and choices explicitly. See the [per-engine API matrix](api.md#tool-calling-support). The opt-in `COLI_TOOL_SALVAGE=1` env var recovers malformed GLM int4 tool calls; V4 uses its native DSML parser. Engine-specific runtime variables are listed in [ENVIRONMENT.md](ENVIRONMENT.md); the server passes the environment through to the selected engine.
+Tool calling is supported by GLM, DeepSeek V4, Kimi K3, Qwen3.6, and Qwen3.8; Inkling rejects active tool declarations and choices explicitly, and OLMoE does too unless `COLI_TOOL_FALLBACK=1`. See the [per-engine API matrix](api.md#tool-calling-support). The opt-in `COLI_TOOL_SALVAGE=1` env var recovers malformed GLM int4 tool calls; V4 uses its native DSML parser. Engine-specific runtime variables are listed in [ENVIRONMENT.md](ENVIRONMENT.md); the server passes the environment through to the selected engine.
---
diff --git a/docs/api.md b/docs/api.md
index d989d742..fce28398 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -235,7 +235,8 @@ Known limitations, current build:
| DeepSeek V4 | yes | yes | native DSML tool-call blocks |
| Inkling | no | no | active tool declarations/choices return HTTP 400 |
| Kimi K3 | yes | yes | native XTML `tools`/`call`/`argument` blocks (#1143) |
-| Qwen3.8-Flash-Next | no | no | active tool declarations/choices return HTTP 400 |
+| Qwen3.6 | yes | yes | native `<tool_call>`/`<tool_response>` blocks, the same XML-ish form as Qwen3.8 |
+| Qwen3.8-Flash-Next | yes | yes | native `<tool_call>`/`<tool_response>` blocks |
| OLMoE | no | no | active tool declarations/choices return HTTP 400 |
On supported engines, pass OpenAI `tools` and optionally `tool_choice` to
diff --git a/docs/qwen36.md b/docs/qwen36.md
index 40824fab..15fe8e6c 100644
--- a/docs/qwen36.md
+++ b/docs/qwen36.md
@@ -41,6 +41,11 @@ family registry (`qwen3_5_moe` / `qwen3_5_moe_text` — an exact match, so other
Qwen architectures are not claimed by this engine), picks it, and drives it over the serve protocol — `coli web` and
`coli serve` (OpenAI-compatible API) work the same way.
+Tool calling is supported through the HTTP gateway using Qwen3.6's native
+`<tool_call>` / `<tool_response>` protocol. The gateway translates between
+the native format and the supported API tool representations; see the
+[per-engine API matrix](api.md#tool-calling-support).
+
Direct invocation without the gateway:
```sh