Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(qwen36): continue an open assistant turn
eniac2927ec7352
diff --git a/c/openai_server.py b/c/openai_server.pyindex e392729d..1ffafc4a 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -1308,14 +1308,20 @@ def render_chat_olmoe(messages, enable_thinking=False, reasoning_effort=None, todef render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, tools=None,- tool_choice=None):+ tool_choice=None, add_generation_prompt=True):"""Text-only subset of Qwen3.6's chat_template: <|im_start|>role\\n ...<|im_end|>\\n frames, then the generation prompt. The official templateopens a mandatory <think> block after `<|im_start|>assistant\\n` — themodel was never trained on the bare `assistant\\n` state, and greedyargmax there lands on an EOS special (measured: gen=0). With thinkingdisabled the template pre-closes the block instead; both branches are- mirrored here byte for byte."""+ mirrored here byte for byte.++ 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+ <|im_end|> terminator and with no cue, not the bare history form the loop emits otherwise.+ ChatML's per-turn terminator is why the marker has to be dropped explicitly, as on qwen38."""if not isinstance(messages, list) or not messages:raise APIError(400, "`messages` must be a non-empty array.", "messages")if tool_choice == "none":@@ -1341,6 +1347,16 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, tooraise APIError(400, f"Unsupported role {role!r}.", f"messages.{index}.role")raw = message.get("content")text = content_text(raw, f"messages.{index}.content") 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.+ reasoning = message.get("reasoning_content", "")+ if not isinstance(reasoning, str):+ 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()}")+ continueif role == "tool":# No tool role in this template: the result rides in as a user turn.parts.append("<|im_start|>user\n"@@ -1349,8 +1365,9 @@ def render_chat_qwen(messages, enable_thinking=False, reasoning_effort=None, tooif role == "assistant" and _TOOL_FALLBACK:text += _fallback_tool_calls(message.get("tool_calls"), index)parts.append(f"<|im_start|>{role}\n{text}<|im_end|>\n")- parts.append("<|im_start|>assistant\n")- parts.append("<think>\n" if enable_thinking else "<think>\n\n</think>\n\n")+ if add_generation_prompt:+ parts.append("<|im_start|>assistant\n")+ parts.append("<think>\n" if enable_thinking else "<think>\n\n</think>\n\n")return "".join(parts)@@ -2351,7 +2368,7 @@ def render_chat_dsv41(messages, enable_thinking=False, reasoning_effort=None, to# (the cue is appended, exactly as before this existed) rather than erroring -- continuation is# on by default, and a family without its open-turn shape yet must not start rejecting requests# nobody opted into. Each renderer adds itself here in the same commit that derives its shape.-CONTINUATION_FAMILIES = {"glm53", "qwen38"}+CONTINUATION_FAMILIES = {"glm53", "qwen38", "qwen36"}def resolve_generation_prompt(messages, body):@@ -2442,8 +2459,10 @@ def render_chat_for_arch(messages, enable_thinking=False, reasoning_effort=None,if ARCH == "qwen38":return render_chat_qwen38(messages, enable_thinking, reasoning_effort, tools,tool_choice, add_generation_prompt)+ if ARCH == "qwen36":+ return render_chat_qwen(messages, enable_thinking, reasoning_effort, tools,+ tool_choice, add_generation_prompt)renderer = (render_chat_kimi if ARCH == "kimi" else- render_chat_qwen if ARCH == "qwen36" elserender_chat_v4 if ARCH == "deepseek_v4" elserender_chat_dsv41 if ARCH == "deepseek_v41" elserender_chat_olmoe if ARCH == "olmoe" else render_chat)diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.pyindex d11968a3..6cfe390b 100644--- a/c/tests/test_openai_server.py+++ b/c/tests/test_openai_server.py@@ -2148,7 +2148,7 @@ class TrailingAssistantTurnTest(unittest.TestCase):yet must render as before -- append the cue -- not reject a request nobody opted into.Each family leaves this list in the commit that derives its shape; Kimi K3 (framedengine-side, so its open turn is a change in kimi_k3.c) is the standing case."""- for arch in ("glm", "deepseek_v4", "kimi", "olmoe", "inkling", "qwen36"):+ for arch in ("glm", "deepseek_v4", "kimi", "olmoe", "inkling"):with self.on(), patch("openai_server.ARCH", arch):self.assertTrue(resolve_generation_prompt(self.OPEN_TURN, {}))diff --git a/c/tests/test_qwen36_chat_template.py b/c/tests/test_qwen36_chat_template.pynew file mode 100644index 00000000..f3014f5d--- /dev/null+++ b/c/tests/test_qwen36_chat_template.py@@ -0,0 +1,161 @@+#!/usr/bin/env python3+"""Il renderer di Qwen3.6 nel gateway, contro chat_template.jinja ufficiale.++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, 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+verde sarebbe peggio che non averlo -- percio' un salto esce con codice 2,+distinto dallo 0 di un confronto riuscito.++RIFERIMENTO (scaricato 2026-09-10):+ repo Qwen/Qwen3.6-35B-A3B (repo vendor; il container colibri dava 404)+ file chat_template.jinja+ sha256 e84f32a23fdda27689f868aa4a1a5621f41133e51a48d7f3efcbea2839574259+ hf download Qwen/Qwen3.6-35B-A3B chat_template.jinja++USO:+ python3 tests/test_qwen36_chat_template.py --template PATH/chat_template.jinja+"""+import argparse+import json+import sys+from pathlib import Path++CASES = {+ "un turno utente": {+ "messages": [{"role": "user", "content": "ciao"}],+ },+ "sistema piu' utente": {+ "messages": [{"role": "system", "content": "Sei conciso."},+ {"role": "user", "content": "capitale della Francia?"}],+ },+ "assistant in cronologia": {+ "messages": [{"role": "user", "content": "1+1?"},+ {"role": "assistant", "content": "2"},+ {"role": "user", "content": "e 2+2?"}],+ },+}++THINKING = (True, False)+++def reference(template_text, *, messages, enable_thinking=True, add_generation_prompt=True):+ 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)+ return rendered.render(messages=messages, add_generation_prompt=add_generation_prompt,+ enable_thinking=enable_thinking)+++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 2 # salto != successo (vedi docstring)+ try:+ import jinja2 # noqa: F401+ except ImportError:+ print("SKIP: jinja2 non installato; senza non c'e' riferimento")+ return 2 # salto != successo (vedi docstring)++ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+ import openai_server++ openai_server.ARCH = "qwen36"+ template_text = arguments.template.read_text(encoding="utf-8")++ failures = 0+ for enable_thinking in THINKING:+ for label, case in CASES.items():+ name = f"{label} [thinking={enable_thinking}]"+ theirs = reference(template_text, messages=case["messages"],+ enable_thinking=enable_thinking)+ ours = openai_server.render_chat_qwen(case["messages"],+ enable_thinking=enable_thinking)+ if ours == theirs:+ print(f"ok {name}")+ else:+ show(name, ours, theirs)+ failures += 1++ # Prosecuzione: l'ultimo turno assistant e' da CONTINUARE. Come qwen38, ChatML chiude+ # ogni turno con <|im_end|> e il template non ha un ramo di continuazione, quindi la+ # forma aperta e' il suo add_generation_prompt=False MENO il <|im_end|>\n finale. Qui in+ # piu' il turno da proseguire e' DOPO l'ultima domanda, e li' il template scrive il blocco+ # <think></think> (una cronologia piu' vecchia lo perde): la resa aperta lo tiene.+ aperto = [{"role": "user", "content": "capitale della Francia?"},+ {"role": "assistant", "content": "La capitale e'"}]+ produced = openai_server.render_chat_for_arch(aperto, enable_thinking=True,+ add_generation_prompt=False)+ closed = reference(template_text, messages=aperto, add_generation_prompt=False)+ # Il terminatore da togliere DEVE esserci nel riferimento: toglierlo "se c'e'" sarebbe un+ # no-op silenzioso se il template cambiasse convenzione, e il confronto perderebbe senso.+ TERM = "<|im_end|>\n"+ if not closed.endswith(TERM):+ print(f"FAIL prosecuzione: il riferimento non finisce col terminatore {TERM!r} da "+ f"togliere -- convenzione del template cambiata? coda: {closed[-40:]!r}")+ failures += 1+ expected = closed+ else:+ expected = closed[:-len(TERM)]+ if produced == expected:+ print("ok prosecuzione: turno aperto = template(add_generation_prompt=False) "+ "senza il <|im_end|> finale")+ else:+ show("prosecuzione", produced, expected)+ failures += 1+ if not produced.endswith("La capitale e'"):+ print(f"FAIL prosecuzione: il prompt non finisce sull'apertura del client: "+ f"{produced[-60:]!r}")+ failures += 1+ if produced.rstrip("\n").endswith("<|im_end|>"):+ print("FAIL prosecuzione: il turno resta chiuso col terminatore")+ failures += 1+ # Controllo negativo: col ramo normale lo stesso scambio DEVE finire sulla cue.+ if not openai_server.render_chat_for_arch(+ aperto, enable_thinking=True).endswith("<think>\n"):+ print("FAIL prosecuzione: il ramo normale non emette piu' il prompt di generazione")+ failures += 1++ print()+ if failures:+ print(f"TEST FAIL ({failures} casi)")+ return 1+ print("template Qwen3.6: il gateway e' identico al riferimento")+ return 0+++if __name__ == "__main__":+ sys.exit(main())