diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index ce2faa145b..2d3365e414 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -546,6 +546,9 @@ in `chat.py` (`/think low`) or over the API:
Without a setting the model uses its own default, **high**. `none` answers at once. The levels are instructions the model was
trained with, not a hard token limit.
+Qwen4-35B-A3B has other levels: `low`, `high` (its default) and `xhigh`, and no `medium`. For that model `medium` means
+`high`, and `xhigh` (or `max`) asks for its longest thinking. The server knows the model by its chat template.
+
### Config keys (`strata-.json`, outside `"args"`)
diff --git a/terminal/serve/fixtures/qwen4_chat_template.jinja b/terminal/serve/fixtures/qwen4_chat_template.jinja
new file mode 100644
index 0000000000..88f39cd165
--- /dev/null
+++ b/terminal/serve/fixtures/qwen4_chat_template.jinja
@@ -0,0 +1,220 @@
+{#- Qwen4 Jinja chat template for compatibility only. Deliberate omissions:
+ - tool-result ordering is limited to text-only runs with explicit tool_call_id.
+ Media runs keep input order: HF collects media before rendering this template.
+ Missing/null tool_call_id never falls back to id: newer HF versions strip null
+ fields before rendering, so these cases cannot be distinguished here.
+ For full Python ordering semantics, reorder messages before media collection.
+ - tool_calls[].function.arguments is only read as a dict; other types cause exceptions.
+ - no anti-injection: the encoder tokenizes data with allow_special=false, so message
+ text can never become a control token. A flat string cannot express that, and
+ re-tokenizing it does not reproduce the encoder's token ids -- use the Qwen4
+ tokenizer's apply_chat_template(tokenize=True) for exact ids.
+ - the generation blocks (return_assistant_tokens_mask) cover a whole assistant
+ body; the encoder additionally masks out media placeholders inside it.
+-#}
+{%- macro render_content(content) -%}
+ {%- if content is string -%}
+ {{- content -}}
+ {%- elif content is iterable and content is not mapping -%}
+ {%- for item in content -%}
+ {%- if item is string -%}
+ {{- item -}}
+ {%- elif item.get('type') == 'text' -%}
+ {{- item.get('text', '') | default('', true) -}}
+ {%- elif item.get('type') in ('image', 'image_url') -%}
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' -}}
+ {%- elif item.get('type') in ('video', 'video_url') -%}
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' -}}
+ {%- elif item.get('type') in ('audio', 'audio_url') -%}
+ {{- '<|audio_start|><|audio_pad|><|audio_end|>' -}}
+ {%- else -%}
+ {{- raise_exception('Unexpected content part type ' ~ item.get('type') ~ '. Supported types are text, image, image_url, video, video_url, audio and audio_url.') -}}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- elif content is not none -%}
+ {{- content | tojson -}}
+ {%- endif -%}
+{%- endmacro -%}
+{%- macro render_reasoning(reasoning) -%}
+ {%- if reasoning is string -%}
+ {{- reasoning -}}
+ {%- elif reasoning is iterable and reasoning is not mapping -%}
+ {%- for item in reasoning -%}
+ {%- if item is string -%}
+ {{- item -}}
+ {%- elif item.get('type') in (none, 'text') -%}
+ {{- item.get('text', '') | default('', true) -}}
+ {%- else -%}
+ {{- item | tojson -}}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- elif reasoning is not none -%}
+ {{- reasoning | tojson -}}
+ {%- endif -%}
+{%- endmacro -%}
+{%- macro render_tools(tools) -%}
+ {{- '# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n\n' -}}
+ {%- for tool in tools -%}
+ {%- if tool is not mapping -%}
+ {{- raise_exception('Unexpected tool spec ' ~ tool ~ '. Expected a function schema dict.') -}}
+ {%- elif tool.get('type') == 'function' and 'function' in tool -%}
+ {{- tool | tojson -}}
+ {%- elif 'function' in tool -%}
+ {{- ({'type': 'function', 'function': tool['function']}) | tojson -}}
+ {%- else -%}
+ {{- ({'type': 'function', 'function': tool}) | tojson -}}
+ {%- endif -%}
+ {{- '\n' -}}
+ {%- endfor -%}
+ {{- '\n\nIf you choose to call a function, use exactly this format:\n' -}}
+ {{- '\n\n\n{parameter-value}\n\n\n' -}}
+{%- endmacro -%}
+{%- macro render_tool_calls(tool_calls) -%}
+ {%- for tool_call in tool_calls -%}
+ {%- if tool_call.function is mapping -%}
+ {%- set name = tool_call.function.get('name', '') -%}
+ {%- set arguments = tool_call.function.get('arguments') -%}
+ {%- else -%}
+ {%- set name = tool_call.get('name', '') -%}
+ {%- set arguments = tool_call.get('arguments') -%}
+ {%- endif -%}
+ {{- '\n\n' -}}
+ {%- if arguments is mapping -%}
+ {%- for arg_name, arg_value in arguments | items -%}
+ {{- '\n' -}}
+ {{- arg_value if arg_value is string else arg_value | tojson -}}
+ {{- '\n\n' -}}
+ {%- endfor -%}
+ {%- elif arguments is not none and (arguments is not string or (arguments | trim) != '') -%}
+ {{- raise_exception('Unexpected argument types. Expected dict.') -}}
+ {%- endif -%}
+ {{- '\n' -}}
+ {%- endfor -%}
+{%- endmacro -%}
+{%- set enable_thinking = enable_thinking | default(none) -%}
+{%- if enable_thinking is not none and enable_thinking is not boolean -%}
+ {{- raise_exception('Unexpected enable_thinking ' ~ enable_thinking ~ '. Expected true, false or none.') -}}
+{%- endif -%}
+{%- set reasoning_effort = reasoning_effort | default(none) -%}
+{%- if reasoning_effort is not none and reasoning_effort not in ('xhigh', 'high', 'low', 'off') -%}
+ {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported efforts are xhigh, high, low and off.') -}}
+{%- endif -%}
+{%- if enable_thinking is none -%}
+ {%- set effort = reasoning_effort if reasoning_effort is not none else 'high' -%}
+{%- elif enable_thinking -%}
+ {%- if reasoning_effort == 'off' -%}
+ {{- raise_exception('Conflicting thinking settings: enable_thinking=true with reasoning_effort=off.') -}}
+ {%- endif -%}
+ {%- set effort = reasoning_effort if reasoning_effort is not none else 'high' -%}
+{%- else -%}
+ {%- if reasoning_effort is not none and reasoning_effort != 'off' -%}
+ {{- raise_exception('Conflicting thinking settings: enable_thinking=false with reasoning_effort=' ~ reasoning_effort ~ '.') -}}
+ {%- endif -%}
+ {%- set effort = 'off' -%}
+{%- endif -%}
+{%- set preserve_thinking = preserve_thinking | default(true) -%}
+{%- if preserve_thinking is not none and preserve_thinking is not boolean -%}
+ {{- raise_exception('Unexpected preserve_thinking ' ~ preserve_thinking ~ '. Expected true, false or none.') -}}
+{%- endif -%}
+{%- set preserve_thinking = true if preserve_thinking is none else preserve_thinking -%}
+{{- '<|im_start|>system\n' + 'Reasoning effort is set to ' + effort + '.' -}}
+{%- if tools -%}
+ {{- '\n\n' -}}
+ {{- render_tools(tools) -}}
+{%- endif -%}
+{{- '<|im_end|>\n' -}}
+{#- Sort text-only tool-result runs only when every explicit tool_call_id resolves. -#}
+{%- set order = namespace(messages=[], call_ids=[], pending=[], unresolved=false) -%}
+{%- for message in messages + [none] -%}
+ {%- if message is none or message.get('role') != 'tool' -%}
+ {%- if not order.unresolved -%}
+ {%- set order.pending = order.pending | sort(attribute='position') -%}
+ {%- endif -%}
+ {%- for item in order.pending -%}
+ {%- set order.messages = order.messages + [item.message] -%}
+ {%- endfor -%}
+ {%- set order.pending = [] -%}
+ {%- set order.unresolved = false -%}
+ {%- if message is not none -%}
+ {%- if message.get('role') == 'assistant' -%}
+ {%- set order.call_ids = [] -%}
+ {%- for call in message.get('tool_calls') or [] -%}
+ {%- if call is mapping and call.get('id') is not none -%}
+ {%- set order.call_ids = order.call_ids + [call.id | string] -%}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- endif -%}
+ {%- set order.messages = order.messages + [message] -%}
+ {%- endif -%}
+ {%- else -%}
+ {#- Do not reorder media independently of the processor's already-collected inputs. -#}
+ {%- set content = message.get('content') -%}
+ {%- if content is iterable and content is not string and content is not mapping -%}
+ {%- for part in content -%}
+ {%- if part is not string and (part is not mapping or part.get('type') != 'text') -%}
+ {%- set order.unresolved = true -%}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- elif content is not none and content is not string -%}
+ {%- set order.unresolved = true -%}
+ {%- endif -%}
+ {%- set cid = message.get('tool_call_id') -%}
+ {%- set match = namespace(position=none) -%}
+ {%- for call_id in order.call_ids -%}
+ {%- if cid is not none and call_id == (cid | string) and match.position is none -%}
+ {%- set match.position = loop.index0 -%}
+ {%- endif -%}
+ {%- endfor -%}
+ {%- if match.position is none -%}
+ {%- set order.unresolved = true -%}
+ {%- endif -%}
+ {%- set order.pending = order.pending + [{'position': match.position, 'message': message}] -%}
+ {%- endif -%}
+{%- endfor -%}
+{%- set messages = order.messages -%}
+{#- with preserve_thinking=false, reasoning survives only on and after the last user turn -#}
+{%- set ns = namespace(last_user=-1) -%}
+{%- if not preserve_thinking -%}
+ {%- for message in messages -%}
+ {%- if message.get('role') == 'user' -%}
+ {%- set ns.last_user = loop.index0 -%}
+ {%- endif -%}
+ {%- endfor -%}
+{%- endif -%}
+{%- for message in messages -%}
+ {%- set role = 'system' if message.get('role') == 'developer' else message.get('role') -%}
+ {%- if role in ('system', 'user') -%}
+ {{- '<|im_start|>' + role + '\n' + render_content(message.get('content')) + '<|im_end|>\n' -}}
+ {%- elif role == 'assistant' -%}
+ {%- if not preserve_thinking and loop.index0 < ns.last_user -%}
+ {%- set reasoning = '' -%}
+ {%- elif 'reasoning_content' in message -%}
+ {%- set reasoning = render_reasoning(message['reasoning_content']) | trim -%}
+ {%- elif 'reasoning' in message -%}
+ {%- set reasoning = render_reasoning(message['reasoning']) | trim -%}
+ {%- else -%}
+ {%- set reasoning = '' -%}
+ {%- endif -%}
+ {%- set content = render_content(message.get('content')) | trim -%}
+ {{- '<|im_start|>assistant\n' -}}
+ {%- generation -%}
+ {{- '' + reasoning + '' + content -}}
+ {%- if message.get('tool_calls') -%}
+ {{- render_tool_calls(message['tool_calls']) -}}
+ {%- endif -%}
+ {{- '<|im_end|>' -}}
+ {%- endgeneration -%}
+ {{- '\n' -}}
+ {%- elif role == 'tool' -%}
+ {{- '<|im_start|>tool\n' + render_content(message.get('content')) + '\n<|im_end|>\n' -}}
+ {%- else -%}
+ {{- raise_exception('Unexpected message role ' ~ message.get('role') ~ '. Supported roles are system, developer, user, assistant and tool.') -}}
+ {%- endif -%}
+{%- endfor -%}
+{%- if add_generation_prompt -%}
+ {{- '<|im_start|>assistant\n' -}}
+ {{- '' -}}
+ {%- if effort == 'off' -%}
+ {{- '' -}}
+ {%- endif -%}
+{%- endif -%}
diff --git a/terminal/serve/frontend.py b/terminal/serve/frontend.py
index e6e5ec9826..1b8de27fd1 100644
--- a/terminal/serve/frontend.py
+++ b/terminal/serve/frontend.py
@@ -84,8 +84,23 @@ def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False)
# block that always renders
source = re.sub(r"({%-?\s*)endgeneration(\s*-?%})", r"\1endif\2", self.source)
self.template = env.from_string(re.sub(r"({%-?\s*)generation(\s*-?%})", r"\1if true\2", source))
+ self.qwen4 = self._detect_qwen4()
self.caps = self._detect_caps()
+ def _detect_qwen4(self) -> bool:
+ """Is this Qwen4-35B-A3B's template? It names its own thinking levels (xhigh, high, low, off), refuses every
+ other word ("medium" included), and writes the thinking with no blank lines around it: a reply that does not
+ think starts with . Asked of the template itself, so a fine-tune that keeps it is served the
+ same way and one that brings another template is not."""
+ if self._is_hy4:
+ return False
+ try:
+ off = self.template.render(messages=[{"role": "user", "content": "x"}], tools=None,
+ add_generation_prompt=True, reasoning_effort="off")
+ except Exception: # noqa: BLE001 - a probe: a template that refuses the word is not Qwen4's
+ return False
+ return off.endswith("<|im_start|>assistant\n")
+
def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True,
**kwargs) -> str:
# Do not use completed empty assistant turns as examples for the next reply. Keep the final message.
@@ -181,6 +196,10 @@ def _text_of(content) -> str:
_EFFORT_QWEN = dict(EFFORT)
+# Qwen4-35B-A3B's template knows xhigh, high (its default), low and off, and stops on any other word. Its own words
+# keep their meaning; a client's "medium" (OpenAI's default level) is the model's default level, high.
+_EFFORT_QWEN4 = {"none": None, "off": None, "minimal": None, "disabled": None, "false": None,
+ "low": "low", "medium": "high", "high": "high", "xhigh": "xhigh", "max": "xhigh", "maximum": "xhigh"}
_EFFORT_INKLING = {"none": None, "off": None, "disabled": None, "false": None,
"minimal": "minimal", "low": "low", "medium": 0.4, "high": "high",
"xhigh": "xhigh", "max": "max", "maximum": "max"}
@@ -189,10 +208,14 @@ def _text_of(content) -> str:
def use_family(family: str | None) -> None:
"""The reasoning-effort words of the model family this server runs (module state, like ENV_TO_USER): the Qwen table, Hy4-Flash's
- (its template knows no_think, high and max: serve/hy4_dialect.py), or Inkling 2's (minimal, low, medium, high, xhigh, max, or 0..0.99)."""
+ (its template knows no_think, high and max: serve/hy4_dialect.py), Inkling 2's (minimal, low, medium, high, xhigh, max, or 0..0.99),
+ or Qwen4-35B-A3B's ("qwen4": xhigh, high, low and off; the rest of the server treats it as the Qwen form)."""
global _FAMILY
_FAMILY = family
EFFORT.clear()
+ if family == "qwen4":
+ EFFORT.update(_EFFORT_QWEN4)
+ return
if family == "hy4":
from serve import hy4_dialect
EFFORT.update(hy4_dialect.EFFORT)
diff --git a/terminal/serve/server.py b/terminal/serve/server.py
index 6e2e3acbf6..d0f42174db 100644
--- a/terminal/serve/server.py
+++ b/terminal/serve/server.py
@@ -569,10 +569,13 @@ def inkling_template_kwargs(kwargs: dict, default=0.4) -> dict:
return {**rest, "reasoning_effort": level}
-def closed_with(text: str, think_end: str) -> str:
+def closed_with(text: str, think_end: str, compact: bool = False) -> str:
"""REASONING_CLOSE or REASONING_WRAP_UP for a model whose thinking ends with think_end (OutputParser). Gemma 4
ends it with , its answer right after: a there is text inside the thought, and the model
- thought on until max_tokens (Discussion 60)."""
+ thought on until max_tokens (Discussion 60). `compact` (Qwen4-35B-A3B): the model's template writes the thinking
+ and the answer with nothing between them, ...answer, so the closing carries no line breaks either."""
+ if compact and think_end == THINK_END:
+ return text.replace("\n" + THINK_END + "\n\n", THINK_END)
return text if think_end == THINK_END else text.replace(THINK_END + "\n\n", think_end)
@@ -4925,6 +4928,7 @@ def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name
self.switch_on_request = False
self.counter = None # counter_for(): ((config, mtime), its counting Service)
self.family = None # the model family: set_family() below (None: the Qwen form)
+ self.qwen4 = False # Qwen4-35B-A3B's template: _read_tokenizer()
self._prompt_cache_lock = threading.Lock()
self._exact_prompt_cache: collections.OrderedDict = collections.OrderedDict()
self._render_inc_cache: collections.OrderedDict = collections.OrderedDict()
@@ -4935,6 +4939,8 @@ def _read_tokenizer(self, tokenizer) -> None:
"""What the model's tokenizer says of the model: the texts that stay text inside a message, the tokens that
end a reply, and how it writes a tool call."""
self.parser_cls = parser_for_template(getattr(self.template, "source", None)) # reads the model's output (reasoning, content, tool calls): by the template's tool-call form
+ # Qwen4-35B-A3B's template (ChatTemplate._detect_qwen4): its own thinking levels, and thinking written with no blank lines around it
+ self.qwen4 = getattr(self.template, "qwen4", False) is True
self.literals = literal_tags(getattr(tokenizer, "control_tokens", ()))
im_end = tokenizer.encode(IM_END, parse_special=True)
if len(im_end) == 1:
@@ -5022,7 +5028,8 @@ def set_family(self, family: str | None) -> None:
"""The model family (None: the Qwen form this server was written for)."""
self.family = family
import serve.frontend as _frontend
- _frontend.use_family(family)
+ # Qwen4-35B-A3B is the Qwen form with its own thinking levels (xhigh, high, low, off): its template says so
+ _frontend.use_family("qwen4" if family is None and getattr(self, "qwen4", False) else family)
_force_text = None
@@ -6673,7 +6680,7 @@ def render_prompt(self, messages, tools, kwargs) -> str:
and getattr(self.template, "_has_last_query", False)
and (not getattr(self.template, "_has_add_vision_id", False) or not kwargs.get("add_vision_id"))
)
- if not self.effort_end or (not off and effort in (None, "", "xhigh", "high")):
+ if not self.effort_end or (not off and effort in self.default_efforts()):
if qwen_inc_ok:
return self._render_qwen_cached(messages, tools, kwargs, bool(kwargs.get("add_generation_prompt", True)))
prompt = self.template.render(messages, tools=tools, **kwargs)
@@ -6687,16 +6694,29 @@ def render_prompt(self, messages, tools, kwargs) -> str:
history = self._render_qwen_cached(messages, tools, base, False) if qwen_inc_ok else \
self.template.render(messages, tools=tools, add_generation_prompt=False, **base)
_, gen_suffix = self._qwen_const_parts({k: v for k, v in kwargs.items() if k != "add_generation_prompt"})
- tail = "" if off else EFFORT_TURN.format(EFFORT_TEXT.get(effort, EFFORT_TEXT["medium"]))
+ tail = "" if off else EFFORT_TURN.format(self.effort_text(effort))
return history + tail + gen_suffix
history = self.template.render(messages, tools=tools, add_generation_prompt=False, **base)
full = self.template.render(messages, tools=tools, add_generation_prompt=True, **kwargs)
mine = self.template.render(messages, tools=tools, add_generation_prompt=False, **kwargs)
if not full.startswith(mine): # a template this cannot take apart: rendered as asked
return full
- tail = "" if off else EFFORT_TURN.format(EFFORT_TEXT.get(effort, EFFORT_TEXT["medium"]))
+ tail = "" if off else EFFORT_TURN.format(self.effort_text(effort))
return history + tail + full[len(mine):]
+ def default_efforts(self) -> tuple:
+ """The reasoning efforts that render the template's default prompt ("effort_position": "end" leaves those where
+ they are). Flash-Next's default is xhigh, which "high" means too; Qwen4-35B-A3B's is high, and its xhigh is a
+ level of its own."""
+ return (None, "", "high") if self.qwen4 else (None, "", "xhigh", "high")
+
+ def effort_text(self, effort) -> str:
+ """The sentence of "effort_position": "end"'s trailing system turn. Qwen4-35B-A3B's is the one its template
+ writes at the top of every prompt, with the level asked for."""
+ if self.qwen4:
+ return f"Reasoning effort is set to {effort}."
+ return EFFORT_TEXT.get(effort, EFFORT_TEXT["medium"])
+
def encode_prompt(self, messages, tools, kwargs, store: bool = True) -> list[int]:
"""The request's prompt: the template rendered and tokenized. #537: a / written inside a
message's text is encoded as the text it is, not as the model's reasoning markers (the template's own are).
@@ -7033,8 +7053,9 @@ def _head_prefix_ids(self, head_msgs, tools, kwargs, strip_inkling_effort: bool
marked, marked_tools, changed = mark_think_literals(head_msgs, tools, self.literals)
effort = kwargs.get("reasoning_effort")
off = kwargs.get("enable_thinking") is False
+ at_end = self.effort_end and (off or effort not in self.default_efforts())
kw = ({k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")}
- if self.effort_end and (off or effort not in (None, "", "xhigh", "high")) else dict(kwargs))
+ if at_end else dict(kwargs))
if self.call_format == "inkling":
kw = inkling_template_kwargs(kwargs, default=self.inkling_default_effort())
elif self.hy4:
@@ -7042,6 +7063,8 @@ def _head_prefix_ids(self, head_msgs, tools, kwargs, strip_inkling_effort: bool
else:
kw = {**self.template_tokens, **({"preserve_thinking": True} if self.preserve_thinking else {}), **kw,
"enable_thinking": not off}
+ if at_end and self.qwen4: # its template writes the level at the top: render_prompt's history has the default one
+ del kw["enable_thinking"]
if self.openai_tools and marked_tools:
marked_tools = [{"type": "function", "function": t} for t in marked_tools]
kw["add_generation_prompt"] = False
@@ -7808,7 +7831,7 @@ def replica_selected(index: int) -> None:
# #1053: the model wrote its reasoning and stopped before : the client would get
# an empty answer. Close the thinking once and let it answer.
close_retried = True
- extra = self.tok.encode(closed_with(REASONING_CLOSE, parser.think_end), parse_special=True)
+ extra = self.tok.encode(closed_with(REASONING_CLOSE, parser.think_end, self.qwen4), parse_special=True)
if max_new - n - len(extra) >= 1:
print("[strata] the reply ended inside its thinking with no answer: closing the "
"thinking once and continuing (reasoning_close_retry)", flush=True)
@@ -7846,7 +7869,8 @@ def replica_selected(index: int) -> None:
near = closest_declared(names[0], declared) if names else None
note = tool_retry_note(kind, names[:3], declared, near)
extra = self.tok.encode(IM_END + "\n<|im_start|>user\n" + note + IM_END
- + "\n<|im_start|>assistant\n\n\n\n\n"
+ + "\n<|im_start|>assistant\n"
+ + ("" if self.qwen4 else "\n\n\n\n")
+ (forced_text or ""), parse_special=True)
if max_new - n - len(extra) >= TOOL_RETRY_MIN_ROOM:
dropped = hold.drop()
@@ -7891,8 +7915,8 @@ def replica_selected(index: int) -> None:
text = (REASONING_WRAP_UP.partition("\n" + THINK_END)[0] + INK_END
+ (force or INK_MSG))
else:
- text = closed_with(REASONING_WRAP_UP, parser.think_end) + (force or "")
- elif self.call_format == "inkling": # a block of its own: no blank line before it
+ text = closed_with(REASONING_WRAP_UP, parser.think_end, self.qwen4) + (force or "")
+ elif self.call_format == "inkling" or self.qwen4: # a block of its own / Qwen4's template: no blank line before it
text = force
else:
text = "\n" * (2 - (len(tail) - len(tail.rstrip("\n")))) + force
diff --git a/terminal/serve/test_qwen4_effort.py b/terminal/serve/test_qwen4_effort.py
new file mode 100644
index 0000000000..68874de8ee
--- /dev/null
+++ b/terminal/serve/test_qwen4_effort.py
@@ -0,0 +1,212 @@
+"""serve/test_qwen4_effort.py - Qwen4-35B-A3B's chat template behind the server (mock engine, no GPU).
+
+The model's template names its own thinking levels (xhigh, high, low, off) at the top of every prompt, stops on any other
+word ("medium" included, the level most OpenAI clients send), and writes the thinking with no blank lines around it:
+...answer, and for a reply that does not think. This pins that the server knows the
+template when it sees it, that every way a client sets the level gives a prompt the template accepts, and that the texts
+the server writes into a reply (the closed thinking, the empty thinking block) are the template's own spelling.
+
+fixtures/qwen4_chat_template.jinja is the published template, byte for byte: tokenizer.chat_template in the header of
+UD-Q4_K_XL/Qwen4-35B-A3B-UD-Q4_K_XL-00001-of-00002.gguf, unsloth/Qwen4-35B-A3B-GGUF at revision 85a51187d937 (Apache 2.0;
+11,373 characters, SHA-256 50383841da44f207c2963a785171af043576cd160e905140878537cf72dd4e78).
+
+ python -m unittest serve.test_qwen4_effort -v
+"""
+from __future__ import annotations
+
+import gzip
+import json
+import sys
+import tempfile
+import unittest
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import serve.frontend as frontend # noqa: E402
+from serve.frontend import ChatTemplate # noqa: E402
+from serve.server import REASONING_CLOSE, REASONING_WRAP_UP, ByteTokenizer, MockEngine, Service, closed_with, serve # noqa: E402
+
+ROOT = Path(__file__).resolve().parents[1]
+FIXTURES = Path(__file__).resolve().parent / "fixtures"
+MSG = [{"role": "user", "content": "hello"}]
+THINKS, NO_THINK = "<|im_start|>assistant\n", "<|im_start|>assistant\n"
+
+
+def qwen4_template() -> ChatTemplate:
+ return ChatTemplate(FIXTURES / "qwen4_chat_template.jinja")
+
+
+def level_of(prompt: str) -> str:
+ """The level the template wrote at the top of the prompt, checked against how the prompt ends."""
+ head = prompt.split("<|im_end|>", 1)[0]
+ level = head.rsplit("Reasoning effort is set to ", 1)[1].split(".", 1)[0]
+ if prompt.endswith(NO_THINK) != (level == "off") or not prompt.endswith((THINKS, NO_THINK)):
+ return f"{level}, but the prompt ends {prompt[-40:]!r}"
+ return level
+
+
+class Detection(unittest.TestCase):
+ def test_the_published_template_is_known(self):
+ self.assertTrue(qwen4_template().qwen4)
+
+ def test_other_templates_are_not_taken_for_it(self):
+ self.assertFalse(ChatTemplate(ROOT / "serve/chat_template.jinja").qwen4) # Qwen3.8-Flash-Next's
+ with gzip.open(FIXTURES / "family_templates.json.gz", "rt", encoding="utf-8") as f:
+ families = {name: entry["chat_template"] for name, entry in json.load(f).items()} # every strata-poly family's
+ self.assertIn("qwen36", families)
+ others = {"refuses everything": "{{ raise_exception('no') }}",
+ "opens the thinking with a line break": "{% for m in messages %}{{ m.content }}{% endfor %}<|im_start|>assistant\n\n",
+ "no thinking at all": "{% for m in messages %}{{ m.content }}{% endfor %}"}
+ with tempfile.TemporaryDirectory() as d:
+ for name, source in {**families, **others}.items():
+ with self.subTest(name):
+ path = Path(d) / "t.jinja"
+ path.write_text(source, encoding="utf-8")
+ self.assertFalse(ChatTemplate(path).qwen4)
+
+ def test_the_words_of_each_table(self):
+ try:
+ frontend.use_family("qwen4")
+ self.assertEqual(frontend.effort_kwargs("medium"), {"reasoning_effort": "high"})
+ self.assertEqual(frontend.effort_kwargs("high"), {"reasoning_effort": "high"})
+ self.assertEqual(frontend.effort_kwargs("xhigh"), {"reasoning_effort": "xhigh"})
+ self.assertEqual(frontend.effort_kwargs("off"), {"enable_thinking": False})
+ frontend.use_family(None) # Flash-Next: high means xhigh, medium is a level
+ self.assertEqual(frontend.effort_kwargs("medium"), {"reasoning_effort": "medium"})
+ self.assertEqual(frontend.effort_kwargs("high"), {"reasoning_effort": "xhigh"})
+ finally:
+ frontend.use_family(None)
+
+
+class ClosedThinking(unittest.TestCase):
+ def test_compact_closing_has_no_line_breaks(self):
+ self.assertEqual(closed_with(REASONING_CLOSE, "", True), "")
+ self.assertEqual(closed_with(REASONING_WRAP_UP, "", True),
+ "\n\nI have thought about this long enough; time to give my answer.")
+
+ def test_the_other_models_keep_theirs(self):
+ self.assertEqual(closed_with(REASONING_CLOSE, ""), REASONING_CLOSE)
+ self.assertEqual(closed_with(REASONING_WRAP_UP, "", False), REASONING_WRAP_UP)
+ self.assertEqual(closed_with(REASONING_CLOSE, ""), "\n")
+ self.assertEqual(closed_with(REASONING_CLOSE, "", True), "\n")
+
+
+class EffortPaths(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.tok = ByteTokenizer()
+ cls.engine = MockEngine(cls.tok, "hmok", max_context=16384)
+ cls.svc = Service(cls.engine, cls.tok, qwen4_template())
+ cls.httpd = serve(cls.svc, port=0)
+ cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.httpd.shutdown()
+ cls.httpd.server_close()
+ frontend.use_family(None) # the words are module state: the next suite's models are not Qwen4
+
+ def setUp(self):
+ self.svc.config_effort = None
+ self.svc.shared = {}
+ self.svc.effort_end = False
+
+ def post(self, path, body):
+ req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
+ headers={"Content-Type": "application/json"})
+ self.engine.last_prompt = []
+ try:
+ with urllib.request.urlopen(req, timeout=30) as r:
+ return r.status, json.loads(r.read())
+ except urllib.error.HTTPError as e:
+ with e:
+ return e.code, json.loads(e.read())
+
+ def prompt(self, path, body):
+ status, answer = self.post(path, body)
+ self.assertEqual(status, 200, (path, body, answer))
+ return self.tok.decode(self.engine.last_prompt)
+
+ def level(self, path, body):
+ return level_of(self.prompt(path, body))
+
+ def chat(self, **extra):
+ return self.level("/v1/chat/completions", {"messages": MSG, "max_tokens": 8, **extra})
+
+ def test_the_server_knows_the_model(self):
+ self.assertTrue(self.svc.qwen4)
+ self.assertIsNone(self.svc.family) # the Qwen form: tool-call retries and the rest stay as they are
+
+ def test_no_level_is_the_models_default(self):
+ self.assertEqual(self.chat(), "high")
+
+ def test_openai_levels(self):
+ for sent, got in (("low", "low"), ("medium", "high"), ("high", "high"), ("xhigh", "xhigh"), ("max", "xhigh"),
+ ("none", "off"), ("off", "off"), ("minimal", "off"), (False, "off")):
+ with self.subTest(sent):
+ self.assertEqual(self.chat(reasoning_effort=sent), got)
+ self.assertEqual(self.chat(reasoning={"effort": sent}), got)
+
+ def test_template_kwargs(self):
+ for kwargs, got in (({"reasoning_effort": "medium"}, "high"), ({"reasoning_effort": "off"}, "off"),
+ ({"enable_thinking": False}, "off"), ({"enable_thinking": True}, "high"),
+ ({"enable_thinking": False, "reasoning_effort": "low"}, "off"),
+ ({"thinking_mode": "xhigh"}, "xhigh")):
+ with self.subTest(kwargs):
+ self.assertEqual(self.chat(chat_template_kwargs=kwargs), got)
+
+ def test_an_unknown_level_is_a_400_with_the_servers_words(self):
+ status, answer = self.post("/v1/chat/completions", {"messages": MSG, "max_tokens": 8, "reasoning_effort": "bogus"})
+ self.assertEqual(status, 400)
+ self.assertIn("unknown reasoning effort", json.dumps(answer))
+
+ def test_anthropic(self):
+ base = {"model": "m", "max_tokens": 4096, "messages": MSG}
+ for thinking, got in (({"type": "enabled", "budget_tokens": 1024}, "low"),
+ ({"type": "enabled", "budget_tokens": 4096}, "high"), # medium: the model's default level
+ ({"type": "enabled", "budget_tokens": 32000}, "high"),
+ ({"type": "disabled"}, "off")):
+ with self.subTest(thinking):
+ self.assertEqual(self.level("/v1/messages", {**base, "thinking": thinking}), got)
+ self.assertEqual(self.level("/v1/messages", {**base, "output_config": {"effort": "medium"}}), "high")
+
+ def test_responses(self):
+ self.assertEqual(self.level("/v1/responses", {"input": "hello", "reasoning": {"effort": "medium"}}), "high")
+ self.assertEqual(self.level("/v1/responses", {"input": "hello", "reasoning": {"effort": "low"}}), "low")
+
+ def test_the_configs_level(self):
+ self.svc.config_effort = "low"
+ self.assertEqual(self.chat(), "low")
+ self.assertEqual(self.chat(reasoning_effort="medium"), "high") # the request's own level wins
+ self.assertEqual(self.chat(chat_template_kwargs={"enable_thinking": False}), "off")
+
+ def test_a_tool_call_in_the_history_renders(self):
+ call = {"id": "c1", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\": \"Lisbon\"}"}}
+ tools = [{"type": "function", "function": {"name": "get_weather", "parameters": {
+ "type": "object", "properties": {"city": {"type": "string"}}}}}]
+ prompt = self.prompt("/v1/chat/completions", {"max_tokens": 8, "tools": tools, "reasoning_effort": "medium", "messages": [
+ {"role": "user", "content": "weather?"}, {"role": "assistant", "content": "", "tool_calls": [call]},
+ {"role": "tool", "tool_call_id": "c1", "content": "19 C"}]})
+ self.assertIn("\n\n\nLisbon\n\n\n", prompt)
+ self.assertIn("<|im_start|>tool\n19 C\n<|im_end|>", prompt)
+ self.assertEqual(level_of(prompt), "high")
+
+ def test_effort_position_end(self):
+ """The opt-in "effort_position": "end": the history is the default level's whatever the request asks, and the
+ level follows in the template's own sentence right before the answer."""
+ self.svc.effort_end = True
+ default = self.prompt("/v1/chat/completions", {"messages": MSG, "max_tokens": 8})
+ history = default[:-len(THINKS)]
+ self.assertEqual(self.prompt("/v1/chat/completions", {"messages": MSG, "max_tokens": 8, "reasoning_effort": "medium"}), default)
+ for sent in ("low", "xhigh"):
+ with self.subTest(sent):
+ got = self.prompt("/v1/chat/completions", {"messages": MSG, "max_tokens": 8, "reasoning_effort": sent})
+ self.assertEqual(got, history + f"<|im_start|>system\nReasoning effort is set to {sent}.<|im_end|>\n" + THINKS)
+ off = self.prompt("/v1/chat/completions", {"messages": MSG, "max_tokens": 8, "reasoning_effort": "none"})
+ self.assertEqual(off, history + NO_THINK)
+
+
+if __name__ == "__main__":
+ unittest.main()