Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/DETAILS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<a id="config-keys"></a>

### Config keys (`strata-<model>.json`, outside `"args"`)
Expand Down
220 changes: 220 additions & 0 deletions terminal/serve/fixtures/qwen4_chat_template.jinja
Original file line number Diff line number Diff line change
@@ -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 <tools></tools> XML tags:\n<tools>\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 -%}
{{- '</tools>\n\nIf you choose to call a function, use exactly this format:\n' -}}
{{- '<tool_call>\n<function={function-name}>\n<parameter={parameter-name}>\n{parameter-value}\n</parameter>\n</function>\n</tool_call>' -}}
{%- 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 -%}
{{- '<tool_call>\n<function=' ~ name ~ '>\n' -}}
{%- if arguments is mapping -%}
{%- for arg_name, arg_value in arguments | items -%}
{{- '<parameter=' ~ (arg_name if arg_name is string else arg_name | tojson) ~ '>\n' -}}
{{- arg_value if arg_value is string else arg_value | tojson -}}
{{- '\n</parameter>\n' -}}
{%- endfor -%}
{%- elif arguments is not none and (arguments is not string or (arguments | trim) != '') -%}
{{- raise_exception('Unexpected argument types. Expected dict.') -}}
{%- endif -%}
{{- '</function>\n</tool_call>' -}}
{%- 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 -%}
{{- '<think>' + reasoning + '</think>' + 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' -}}
{{- '<think>' -}}
{%- if effort == 'off' -%}
{{- '</think>' -}}
{%- endif -%}
{%- endif -%}
25 changes: 24 additions & 1 deletion terminal/serve/frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <think></think>. 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<think></think>")

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.
Expand Down Expand Up @@ -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"}
Expand All @@ -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)
Expand Down
Loading