Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(olmoe): continue an open assistant turn
enif9efa23cd742
diff --git a/c/openai_server.py b/c/openai_server.pyindex 79d7f4e8..b87f1bba 100644--- a/c/openai_server.py+++ b/c/openai_server.py@@ -1257,7 +1257,7 @@ def render_chat_v4(messages, enable_thinking=False, reasoning_effort=None, toolsdef render_chat_olmoe(messages, enable_thinking=False, reasoning_effort=None, tools=None,- tool_choice=None):+ tool_choice=None, add_generation_prompt=True):"""OLMoE-Instruct's native chat_template (tokenizer_config.json): onebos_token, then per-message <|system|>/<|user|>/<|assistant|> turns eachclosed by a newline, prior assistant turns also closed by eos_token@@ -1265,7 +1265,11 @@ def render_chat_olmoe(messages, enable_thinking=False, reasoning_effort=None, torepurposed as this tokenizer's BOS/EOS marker), and a trailing"<|assistant|>\\n" generation prompt. No tool-call syntax and no thinkingmode exist in this template, so both parameters are accepted but unused.- """++ add_generation_prompt=False continues a trailing assistant turn. The template closes+ even the last assistant turn with eos_token, so the open-turn shape is that turn without+ the eos and with no cue -- the same drop-the-terminator move as the ChatML families, with+ eos_token as the terminator here."""if not isinstance(messages, list) or not messages:raise APIError(400, "`messages` must be a non-empty array.", "messages")if tool_choice == "none":@@ -1300,10 +1304,13 @@ def render_chat_olmoe(messages, enable_thinking=False, reasoning_effort=None, toelse:calls = (_fallback_tool_calls(message.get("tool_calls"), index)if _TOOL_FALLBACK else "")- parts.append(f"<|assistant|>\n{text}{calls}{boundary}")+ # A continued turn is the last message rendered open: no eos, no cue.+ terminator = "" if (not add_generation_prompt and index == last) else boundary+ parts.append(f"<|assistant|>\n{text}{calls}{terminator}")if index != last:parts.append("\n")- parts.append("<|assistant|>\n")+ if add_generation_prompt:+ parts.append("<|assistant|>\n")return "".join(parts)@@ -2374,7 +2381,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", "qwen36", "glm"}+CONTINUATION_FAMILIES = {"glm53", "qwen38", "qwen36", "glm", "olmoe"}def resolve_generation_prompt(messages, body):@@ -2471,10 +2478,12 @@ def render_chat_for_arch(messages, enable_thinking=False, reasoning_effort=None,if ARCH == "glm":return render_chat(messages, enable_thinking, reasoning_effort, tools,tool_choice, add_generation_prompt)+ if ARCH == "olmoe":+ return render_chat_olmoe(messages, enable_thinking, reasoning_effort, tools,+ tool_choice, add_generation_prompt)renderer = (render_chat_kimi if ARCH == "kimi" elserender_chat_v4 if ARCH == "deepseek_v4" else- render_chat_dsv41 if ARCH == "deepseek_v41" else- render_chat_olmoe if ARCH == "olmoe" else render_chat)+ render_chat_dsv41 if ARCH == "deepseek_v41" else render_chat)return renderer(messages, enable_thinking, reasoning_effort, tools, tool_choice)diff --git a/c/tests/test_olmoe_chat_template.py b/c/tests/test_olmoe_chat_template.pynew file mode 100644index 00000000..3c3d781a--- /dev/null+++ b/c/tests/test_olmoe_chat_template.py@@ -0,0 +1,134 @@+#!/usr/bin/env python3+"""Il renderer di OLMoE nel gateway, contro il chat_template del checkpoint.++Il template di OLMoE vive dentro tokenizer_config.json, non in un chat_template.jinja+a se'. Estrai il campo `chat_template` in un file e passalo qui. bos_token ed eos_token+sono lo stesso marcatore, "|||IP_ADDRESS|||".++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 -- percio' un salto esce con codice 2, distinto dallo 0 di+un confronto riuscito.++RIFERIMENTO (scaricato 2026-09-10):+ repo allenai/OLMoE-1B-7B-0125-Instruct+ file campo `chat_template` estratto da tokenizer_config.json+ sha256 fe689ffbd6a4e2d0532d7480696b065b10e0e1eff3f9b9fc4bea415761e4bf4a (del .jinja estratto)+ hf download allenai/OLMoE-1B-7B-0125-Instruct tokenizer_config.json # poi estrai chat_template++USO:+ python3 tests/test_olmoe_chat_template.py --template PATH/olmoe-chat_template.jinja+"""+import argparse+import sys+from pathlib import Path++BOUNDARY = "|||IP_ADDRESS|||" # bos_token == eos_token++CASES = {+ "un turno utente": [{"role": "user", "content": "ciao"}],+ "sistema piu' utente": [{"role": "system", "content": "Sei conciso."},+ {"role": "user", "content": "capitale della Francia?"}],+ "assistant in cronologia": [{"role": "user", "content": "1+1?"},+ {"role": "assistant", "content": "2"},+ {"role": "user", "content": "e 2+2?"}],+}+++def reference(template_text, *, messages, add_generation_prompt=True):+ import jinja2+ environment = jinja2.Environment(trim_blocks=False, lstrip_blocks=False,+ extensions=["jinja2.ext.loopcontrols"])+ rendered = environment.from_string(template_text)+ return rendered.render(messages=messages, add_generation_prompt=add_generation_prompt,+ bos_token=BOUNDARY, eos_token=BOUNDARY)+++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 = "olmoe"+ template_text = arguments.template.read_text(encoding="utf-8")++ failures = 0+ for label, messages in CASES.items():+ theirs = reference(template_text, messages=messages)+ ours = openai_server.render_chat_olmoe(messages)+ if ours == theirs:+ print(f"ok {label}")+ else:+ show(label, ours, theirs)+ failures += 1++ # Prosecuzione: l'ultimo turno assistant e' da CONTINUARE. Il template chiude anche+ # l'ultimo turno con eos_token, quindi la forma aperta e' quel rendering MENO l'eos+ # finale e senza cue -- lo stesso taglio del terminatore delle famiglie ChatML.+ aperto = [{"role": "user", "content": "capitale della Francia?"},+ {"role": "assistant", "content": "La capitale e'"}]+ produced = openai_server.render_chat_for_arch(aperto, add_generation_prompt=False)+ closed = reference(template_text, messages=aperto, add_generation_prompt=False)+ # L'eos 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.+ if not closed.endswith(BOUNDARY):+ print(f"FAIL prosecuzione: il riferimento non finisce con l'eos {BOUNDARY!r} da "+ f"togliere -- convenzione del template cambiata? coda: {closed[-40:]!r}")+ failures += 1+ expected = closed+ else:+ expected = closed[:-len(BOUNDARY)]+ if produced == expected:+ print("ok prosecuzione: turno aperto = template(add_generation_prompt=False) "+ "senza l'eos 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.endswith(BOUNDARY):+ print("FAIL prosecuzione: il turno resta chiuso con l'eos")+ failures += 1+ # Controllo negativo: col ramo normale lo stesso scambio DEVE finire sulla cue.+ if not openai_server.render_chat_for_arch(aperto).endswith("<|assistant|>\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 OLMoE: il gateway e' identico al riferimento")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.pyindex e1dbdad2..432dfc90 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 ("deepseek_v4", "kimi", "olmoe", "inkling"):+ for arch in ("deepseek_v4", "kimi", "inkling"):with self.on(), patch("openai_server.ARCH", arch):self.assertTrue(resolve_generation_prompt(self.OPEN_TURN, {}))