Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(studio): read the MLX reasoning prefill mode from the rendered generation prompt (#9288)
Long Yixingea6b38d5089f
diff --git a/pyproject.toml b/pyproject.tomlindex 76cf2b240f7..51b465f7292 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -119,6 +119,7 @@ studio = ["huggingface-hub>=1.23.0,<2.0 ; python_version >= '3.10'","huggingface-hub==0.36.2 ; python_version < '3.10'","urllib3>=2.3.0",+ "jinja2>=3.1.0","structlog>=24.1.0","diceware==1.0.1","ddgs==9.14.4 ; python_version >= '3.10'",diff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txtindex be4cd5bbfc9..98871316364 100644--- a/studio/backend/requirements/studio.txt+++ b/studio/backend/requirements/studio.txt@@ -27,6 +27,12 @@ huggingface-hub==0.36.2; python_version < "3.10"# below that the read is uninterruptible. The preflight abandons the reader either# way, so this is defence in depth, not the bound itself.urllib3>=2.3.0+# The safetensors reasoning-prefill probe renders chat templates in a Jinja sandbox. Transitive+# via torch and transformers, declared because the route imports it directly and this set is+# installed in every mode: without it the probe cannot render, falls back to always-prefill,+# and every reasoning model returns blank content. 3.1.0 is the floor -- the |items filter+# arrives there, and Hermes-3's tool_use branch fails to compile below it.+jinja2>=3.1.0structlog>=24.1.0diceware==1.0.1ddgs==9.14.4; python_version >= "3.10"diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex ea710f624db..b4140cd8d18 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -29,6 +29,7 @@ from fastapi.encoders import jsonable_encoderfrom fastapi.responses import StreamingResponse, JSONResponse, PlainTextResponse, Responsefrom starlette.requests import ClientDisconnectfrom typing import Any, Callable, Collection, List, NamedTuple, Optional, TYPE_CHECKING, Union+import functoolsimport jsonimport httpxfrom loggers import get_logger@@ -2897,21 +2898,21 @@ def _detect_safetensors_features(return flags-def _generation_prompt_opens_think(template: Optional[str]) -> bool:- """True when rendering the template's generation prompt ends INSIDE an unclosed ``<think>``.+_PROBE_MESSAGES = ({"role": "user", "content": "hi"},)++[email protected]_cache(maxsize = 64)+def _compile_generation_prompt_probe(template: str):+ """Compile the probe template, or None when it cannot be compiled.- Distinguishes templates that PREFILL an open ``<think>`` in the assistant generation- prompt (DeepSeek-R1, QwQ, Qwen3-Thinking) -- where the model emits only the closing- ``</think>`` and the extractor must start in reasoning mode -- from templates that merely- render PAST assistant ``<think>...</think>`` history while leaving the generation prompt- open with no ``<think>`` (e.g. Kimi-K2-Thinking), where the model self-emits its own block- and the extractor must start in normal mode. Renders a single-user-message probe with the- same sandbox transformers uses; on any failure returns True, preserving the historical- always-on prefill for templates that cannot be rendered here.+ Compilation is the expensive half (~60ms on a production-sized template) and rendering is+ not (~0.1ms). Memoising this half rather than the rendered string keeps that saving while+ letting the messages vary per request, which a template that decides its ``<think>`` shape+ from the conversation requires."""- if not template:- return Falsetry:+ from datetime import datetime+from jinja2.sandbox import ImmutableSandboxedEnvironmentdef _raise_exception(message: str):@@ -2924,17 +2925,85 @@ def _generation_prompt_opens_think(template: Optional[str]) -> bool:)env.filters["tojson"] = lambda value, **kwargs: json.dumps(value, ensure_ascii = False)env.globals["raise_exception"] = _raise_exception- rendered = env.from_string(template).render(- messages = [{"role": "user", "content": "hi"}],- add_generation_prompt = True,+ # transformers exposes this to every template; without it a date-stamping one raises+ # here and the failure reads as a prefill.+ env.globals["strftime_now"] = lambda fmt: datetime.now().strftime(fmt)+ return env.from_string(template)+ except Exception:+ return None+++def _render_generation_prompt_probe(+ template: str,+ enable_thinking: Optional[bool],+ reasoning_effort: Optional[str],+ messages: Optional[Collection] = None,+ generation_prompt: bool = True,+) -> Optional[str]:+ """Render the probe generation prompt, or None when it cannot be rendered."""+ reasoning_kwargs: dict = {}+ if enable_thinking is not None:+ reasoning_kwargs["enable_thinking"] = enable_thinking+ if reasoning_effort is not None:+ reasoning_kwargs["reasoning_effort"] = reasoning_effort+ try:+ # Inside the guard: an unhashable template would raise out of the memo key otherwise.+ compiled = _compile_generation_prompt_probe(template)+ if compiled is None:+ return None+ return compiled.render(+ messages = list(messages if messages is not None else _PROBE_MESSAGES),+ add_generation_prompt = generation_prompt,bos_token = "",eos_token = "",+ **reasoning_kwargs,)except Exception:+ return None+++def _generation_prompt_opens_think(+ template: Optional[str],+ enable_thinking: Optional[bool] = None,+ reasoning_effort: Optional[str] = None,+ messages: Optional[Collection] = None,+) -> bool:+ """True when rendering the template's generation prompt ends INSIDE an unclosed ``<think>``.++ Separates templates that prefill an open ``<think>``, where the model emits only the closing+ tag, from those that leave the prompt open and let the model emit its own block.++ Three things keep this reading what generation reads. A ``None`` kwarg is omitted exactly as+ ``apply_chat_template_for_generation`` omits it, so a template states its own default. The+ request's messages are rendered when given, since a template may take the shape from them+ (Nemotron opens the block only once a message says ``/think``). And only the assistant+ prefix is weighed, diffed against the render without a generation prompt, so a user who+ merely types ``<think>`` cannot become the last opener.++ Both fallbacks stay conservative: a history the template refuses drops back to the+ single-user probe rather than to True, and a template the sandbox cannot render at all+ (``{% generation %}`` is not in its extension set) returns True, the historical always-on+ prefill.+ """+ if not template:+ return False+ if not isinstance(template, str):+ return True+ args = (template, enable_thinking, reasoning_effort)+ rendered = _render_generation_prompt_probe(*args, messages)+ if rendered is None and messages is not None:+ messages = None+ rendered = _render_generation_prompt_probe(*args)+ if rendered is None:return True- # ``<think>`` is not a substring of ``</think>`` (the ``/`` breaks it), so the last open- # tag sitting after the last close tag means the prompt ends inside an open block.- return rendered.rfind("<think>") > rendered.rfind("</think>")+ # Everything the two renders share is history. A template that ignores the flag yields an+ # empty prefix and prefills nothing, right for one that opens no block.+ body = _render_generation_prompt_probe(*args, messages, generation_prompt = False)+ prefix = (+ rendered[len(os.path.commonprefix((rendered, body))) :] if body is not None else rendered+ )+ # ``<think>`` is not a substring of ``</think>``, so a later open tag means it stays open.+ return prefix.rfind("<think>") > prefix.rfind("</think>")def _sf_reasoning_prefill_mode(@@ -2942,15 +3011,16 @@ def _sf_reasoning_prefill_mode(enable_thinking: Optional[bool],template: Optional[str] = None,reasoning_effort: Optional[str] = None,+ messages: Optional[Collection] = None,) -> bool:"""Whether a safetensors/MLX generation begins INSIDE an unclosed ``<think>``.- ``enable_thinking`` templates (Qwen3/GLM) prefill an open ``<think>`` so the model- emits only the closing ``</think>``, and the extractor must start in reasoning mode.Gated on the STANDARD ``<think>``/``</think>`` markers: bespoke channels (gemma's- ``<|think|>``) never emit ``</think>`` and would swallow the answer, so they and- gpt-oss and thinking-disabled requests return False. ``enable_thinking`` None- defaults thinking ON, so a plain request still prefills.+ ``<|think|>``) never emit ``</think>`` and would swallow the answer, so they, gpt-oss and+ thinking-disabled requests return False. Past the gates the generation prompt's shape+ decides rather than the capability flags, since a template free to state its own default+ states it, and ``messages`` is rendered with it because a template may read the shape+ off them."""if features.get("reasoning_style") not in ("enable_thinking", "enable_thinking_effort"):return False@@ -2966,7 +3036,7 @@ def _sf_reasoning_prefill_mode(# template, including markup that only renders PAST assistant history (Kimi-K2-Thinking)# while the generation prompt opens none. Prefill only when the generation prompt opens# one, else the extractor captures a normal answer as reasoning_content and returns blank.- return _generation_prompt_opens_think(tpl)+ return _generation_prompt_opens_think(tpl, messages = messages)if not features.get("supports_reasoning"):return Falseif enable_thinking is False:@@ -2975,7 +3045,7 @@ def _sf_reasoning_prefill_mode(# so we don't prefill and capture the answer. Plain enable_thinking models ignore effort.if features.get("reasoning_style") == "enable_thinking_effort" and reasoning_effort == "none":return False- return True+ return _generation_prompt_opens_think(tpl, enable_thinking, reasoning_effort, messages)def _effective_enable_tools(payload) -> Optional[bool]:@@ -17206,6 +17276,29 @@ async def openai_chat_completions(if not _sf_template_tools and _sf_server_tool_intent:_sf_template_tools = ({},)+ # What the prefill probe renders, built to match what generation renders: a template may+ # read the ``<think>`` shape off the conversation (Nemotron opens it only once a message+ # says ``/think``), so any difference here is a wrong verdict. Hence the normalized+ # messages rather than the payload (content parts flattened, system lifted, as+ # mlx_inference sees them) and the same sweep the renderer applies, which turns a user's+ # ``<think>`` into ``< think>``. Markup profile is not in scope, so this takes the+ # renderer's own default rewrite.+ try:+ from core.inference.chat_template_helpers import (+ neutralize_control_markup_in_messages as _sf_sweep,+ )+ _sf_probe_messages = (+ jsonable_encoder(+ _sf_sweep(+ ([{"role": "system", "content": system_prompt}] if system_prompt else [])+ + chat_messages+ )+ )+ or None+ )+ except Exception:+ _sf_probe_messages = None+def _sf_response_protocol(tools = None):features = _detect_safetensors_features(backend, _sf_tpl, tools = tools)parse_think = bool(@@ -17216,6 +17309,7 @@ async def openai_chat_completions(payload.enable_thinking,_sf_tpl,reasoning_effort = payload.reasoning_effort,+ messages = _sf_probe_messages,)return features, parse_think, reasoning_prefilleddiff --git a/studio/backend/tests/test_chat_template_continuation.py b/studio/backend/tests/test_chat_template_continuation.pyindex c8e7ad85546..76bc299f0b7 100644--- a/studio/backend/tests/test_chat_template_continuation.py+++ b/studio/backend/tests/test_chat_template_continuation.py@@ -720,7 +720,11 @@ def test_the_manual_splice_appends_the_fallback_swept_partial():# ── Non-streaming tool loop: the prefill mode belongs to the turn that produced the text ──-_THINK_TEMPLATE = "{% if x %}<think>\n{% endif %}</think>"+# R1/QwQ shape: the generation prompt opens an unclosed <think>.+_THINK_TEMPLATE = (+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ "{% if add_generation_prompt %}<|im_start|>assistant\n<think>\n{% endif %}"+)# A resumed turn that calls a tool: the kept text is the POST-tool turn, which rendered# an ordinary generation prompt, so its output opens inside the template's <think>._RESUMED_TOOL_EVENTS = [diff --git a/studio/backend/tests/test_safetensors_capability_advertise.py b/studio/backend/tests/test_safetensors_capability_advertise.pyindex 35c3937a960..6b42a873895 100644--- a/studio/backend/tests/test_safetensors_capability_advertise.py+++ b/studio/backend/tests/test_safetensors_capability_advertise.py@@ -874,20 +874,29 @@ def test_detect_safetensors_features_keeps_tools_for_function_alias_bare_json():# _sf_reasoning_prefill_mode gates the prefilled-<think> extractor (GGUF reasoning parity).class TestSafetensorsReasoningPrefillGate:- # A minimal Qwen3-style template with the standard <think>/</think> markers.- _QWEN_TPL = "{% if enable_thinking %}<think>{% endif %}...</think>..."+ # Qwen3.5 shape: renders a CLOSED <think></think> unless thinking is explicitly asked for.+ _QWEN35_TPL = (+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ "{% if add_generation_prompt %}<|im_start|>assistant\n"+ "{% if enable_thinking is defined and enable_thinking is true %}<think>\n"+ "{% else %}<think>\n\n</think>\n\n{% endif %}{% endif %}"+ )+ # Qwen3 shape: the model self-emits its block, so the generation prompt opens none.+ _QWEN3_TPL = (+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ "{% if add_generation_prompt %}<|im_start|>assistant\n"+ "{% if enable_thinking is defined and enable_thinking is false %}<think>\n\n</think>\n\n{% endif %}"+ "{% endif %}"+ )# gemma-style bespoke reasoning channel -- no standard markers._GEMMA_TPL = "{% if enable_thinking %}<|think|>{% endif %}<|channel>thought<channel|>"- # always-on template whose GENERATION PROMPT opens an unclosed <think> (DeepSeek-R1 / QwQ /- # Qwen3-Thinking shape): the model emits only the closing </think>, so prefill.- _ALWAYS_ON_OPEN_TPL = (+ # DeepSeek-R1 / QwQ shape: the generation prompt opens an unclosed <think>.+ _PROMPT_OPENS_THINK_TPL = ("{% for m in messages %}{{ m['content'] }}{% endfor %}""{% if add_generation_prompt %}<|assistant|><think>\n{% endif %}")- # always-on template that renders PAST assistant <think>...</think> history but leaves the- # generation prompt open with no <think> (Kimi-K2-Thinking shape): the model self-emits its- # own block, so prefill mode would blank a normal answer.- _ALWAYS_ON_HISTORY_TPL = (+ # Kimi-K2-Thinking shape: renders past <think> history but opens none in the prompt.+ _HISTORY_ONLY_THINK_TPL = ("{% for m in messages %}""{% if m['role'] == 'assistant' %}<think>{{ m.get('reasoning_content', '') }}</think>""{{ m['content'] }}{% endif %}"@@ -907,41 +916,48 @@ class TestSafetensorsReasoningPrefillGate:def test_g1_enable_thinking_true(self):# G1: Qwen3.5 template + explicit enable_thinking=True -> prefilled.from routes.inference import _sf_reasoning_prefill_mode- assert _sf_reasoning_prefill_mode(self._features(), True, self._QWEN_TPL) is True+ assert _sf_reasoning_prefill_mode(self._features(), True, self._QWEN35_TPL) is True++ def test_g2_enable_thinking_none_follows_template_default(self):+ # G2: the kwarg is omitted, so the template's own default decides. Reading it as+ # prefilled captured the whole answer as reasoning and blanked the visible content.+ from routes.inference import _sf_reasoning_prefill_mode+ assert _sf_reasoning_prefill_mode(self._features(), None, self._QWEN35_TPL) is False- def test_g2_enable_thinking_none_defaults_on(self):- # G2: default request (None) -> prefilled (Qwen3/GLM templates default on).+ def test_g2b_self_emitting_template_not_prefilled(self):+ # G2b: thinking is on but the prompt opens no <think>, so the extractor starts normal.from routes.inference import _sf_reasoning_prefill_mode- assert _sf_reasoning_prefill_mode(self._features(), None, self._QWEN_TPL) is True+ assert _sf_reasoning_prefill_mode(self._features(), None, self._QWEN3_TPL) is False+ assert _sf_reasoning_prefill_mode(self._features(), True, self._QWEN3_TPL) is Falsedef test_g3_enable_thinking_false(self):# G3: thinking explicitly off -> not prefilled.from routes.inference import _sf_reasoning_prefill_mode- assert _sf_reasoning_prefill_mode(self._features(), False, self._QWEN_TPL) is False+ assert _sf_reasoning_prefill_mode(self._features(), False, self._QWEN35_TPL) is Falsedef test_g4_gpt_oss_reasoning_effort_excluded(self):# G4: gpt-oss uses explicit tags via HarmonyTextStreamer -> normal mode.from routes.inference import _sf_reasoning_prefill_modefeats = self._features(reasoning_style = "reasoning_effort")- assert _sf_reasoning_prefill_mode(feats, True, self._QWEN_TPL) is False+ assert _sf_reasoning_prefill_mode(feats, True, self._PROMPT_OPENS_THINK_TPL) is Falsedef test_g5_enable_thinking_effort_included(self):- # G5: GLM-style enable_thinking_effort also prefills.+ # G5: enable_thinking_effort is not excluded by the style gate.from routes.inference import _sf_reasoning_prefill_modefeats = self._features(reasoning_style = "enable_thinking_effort")- assert _sf_reasoning_prefill_mode(feats, None, self._QWEN_TPL) is True+ assert _sf_reasoning_prefill_mode(feats, None, self._PROMPT_OPENS_THINK_TPL) is Truedef test_g6_non_reasoning_model(self):# G6: no reasoning capability -> never prefilled.from routes.inference import _sf_reasoning_prefill_modefeats = self._features(supports_reasoning = False, reasoning_style = None)- assert _sf_reasoning_prefill_mode(feats, True, self._QWEN_TPL) is False+ assert _sf_reasoning_prefill_mode(feats, True, self._PROMPT_OPENS_THINK_TPL) is Falsedef test_g7_reasoning_always_on_prompt_opens_think(self):# G7: always-on template whose generation prompt opens <think> -> prefilled regardless of the flag.from routes.inference import _sf_reasoning_prefill_modefeats = self._features(reasoning_always_on = True)- assert _sf_reasoning_prefill_mode(feats, False, self._ALWAYS_ON_OPEN_TPL) is True+ assert _sf_reasoning_prefill_mode(feats, False, self._PROMPT_OPENS_THINK_TPL) is Truedef test_g7b_reasoning_always_on_history_only_not_prefilled(self):# G7b (#5704): always-on classification from rendered assistant HISTORY <think></think>@@ -949,7 +965,7 @@ class TestSafetensorsReasoningPrefillGate:# normal answer entirely as reasoning_content and blank the visible answer, so it must be off.from routes.inference import _sf_reasoning_prefill_modefeats = self._features(reasoning_always_on = True)- assert _sf_reasoning_prefill_mode(feats, None, self._ALWAYS_ON_HISTORY_TPL) is False+ assert _sf_reasoning_prefill_mode(feats, None, self._HISTORY_ONLY_THINK_TPL) is Falsedef test_g8_gemma_bespoke_channel_excluded(self):# G8: gemma's <|think|>/<|channel> format has no </think> -> NOT prefilleddiff --git a/studio/backend/tests/test_safetensors_reasoning_stream.py b/studio/backend/tests/test_safetensors_reasoning_stream.pyindex 6a9139b5935..b49f64d0f9d 100644--- a/studio/backend/tests/test_safetensors_reasoning_stream.py+++ b/studio/backend/tests/test_safetensors_reasoning_stream.py@@ -3,11 +3,13 @@"""Safetensors/MLX reasoning-block parity with GGUF.-enable_thinking templates (Qwen3/GLM) prefill an unclosed ``<think>`` so the model-emits only the closing ``</think>`` then the answer; the safetensors stream must-split the leading text into ``reasoning_content`` deltas (plain stream and tool-loop), resetting per turn and appending only visible text to the monitor. Replays a-copy of ``sf_tool_stream``'s reasoning loop against synthetic events.+Some enable_thinking templates prefill an unclosed ``<think>`` so the model emits only+the closing ``</think>`` then the answer; the safetensors stream must split the leading+text into ``reasoning_content`` deltas (plain stream and tool loop), resetting per turn+and appending only visible text to the monitor. Others render a closed block or none at+all and the answer is visible from the first token, so the prefill mode is read from the+generation prompt the request renders. Replays a copy of ``sf_tool_stream``'s reasoning+loop against synthetic events, and covers the split through the route itself."""from __future__ import annotations@@ -99,7 +101,51 @@ for _name in reversed(_STUBBED):sys.modules.pop(_name, None)-_THINK_TPL = "...<think>...</think>..."+# DeepSeek-R1 / QwQ / GLM shape: the generation prompt opens an unclosed ``<think>``.+_THINK_TPL = (+ "{% for m in messages %}<|user|>{{ m['content'] }}{% endfor %}"+ "{% if add_generation_prompt %}<|assistant|>\n<think>\n{% endif %}"+)+# Qwen3.5 shape: a CLOSED ``<think></think>`` unless thinking is explicitly requested.+_TEMPLATE_DEFAULT_OFF_TPL = (+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ "{% if add_generation_prompt %}<|im_start|>assistant\n"+ "{% if enable_thinking is defined and enable_thinking is true %}<think>\n"+ "{% else %}<think>\n\n</think>\n\n{% endif %}{% endif %}"+)+# Opens ``<think>`` only at high effort.+_EFFORT_SHAPE_TPL = (+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ "{% if add_generation_prompt %}<|im_start|>assistant\n"+ "{% if reasoning_effort is defined and reasoning_effort == 'high' %}<think>\n"+ "{% else %}<think>\n\n</think>\n\n{% endif %}{% endif %}"+)+# Stamps a date through the ``strftime_now`` global transformers exposes to every template.+_STRFTIME_TPL = (+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ "{{ strftime_now('%Y') }}"+ "{% if add_generation_prompt %}<|im_start|>assistant\n<think>\n\n</think>\n\n{% endif %}"+)+# Nemotron shape: thinking is off until a message opts in with ``/think``.+_MESSAGE_SHAPE_TPL = (+ "{% set ns = namespace(think = false) %}"+ "{% for m in messages %}{% if '/think' in m['content'] %}{% set ns.think = true %}{% endif %}"+ "<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ "{% if add_generation_prompt %}<|im_start|>assistant\n"+ "{% if ns.think %}<think>\n{% else %}<think></think>{% endif %}{% endif %}"+)+# Kimi shape: renders history into the prompt but opens no block of its own.+_HISTORY_ONLY_TPL = (+ "{% for m in messages %}<|im_user|>{{ m['role'] }}<|im_middle|>{{ m['content'] }}<|im_end|>"+ "{% if m['role'] == 'assistant' %}<think></think>{% endif %}{% endfor %}"+ "{% if add_generation_prompt %}<|im_assistant|>assistant<|im_middle|>{% endif %}"+)+# Closes its block, and raises on a tool turn the way a strict template does.+_STRICT_HISTORY_TPL = (+ "{% for m in messages %}{% if m['role'] == 'tool' %}{{ raise_exception('no tool turns') }}"+ "{% endif %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ "{% if add_generation_prompt %}<|im_start|>assistant\n<think>\n\n</think>\n\n{% endif %}"+)_ETHINK = {"reasoning_style": "enable_thinking", "supports_reasoning": True}_ETHINK_EFFORT = {"reasoning_style": "enable_thinking_effort", "supports_reasoning": True}@@ -108,6 +154,13 @@ def test_prefill_mode_on_for_enable_thinking_default():assert _sf_reasoning_prefill_mode(_ETHINK, None, _THINK_TPL) is True+def test_prefill_mode_follows_template_default_not_the_request_flag():+ # The kwarg is omitted when the request says nothing, so the template's own default+ # decides. Assuming a prefill blanked ``content`` for every OpenAI client.+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _TEMPLATE_DEFAULT_OFF_TPL) is False+ assert _sf_reasoning_prefill_mode(_ETHINK, True, _TEMPLATE_DEFAULT_OFF_TPL) is True++def test_prefill_mode_off_when_thinking_disabled():assert _sf_reasoning_prefill_mode(_ETHINK, False, _THINK_TPL) is False@@ -125,10 +178,79 @@ def test_prefill_mode_off_for_reasoning_effort_none():)+def test_prefill_mode_renders_with_the_requested_reasoning_effort():+ # Rendering without the request's effort would report the closed shape for both.+ assert _sf_reasoning_prefill_mode(_ETHINK_EFFORT, None, _EFFORT_SHAPE_TPL, "high") is True+ assert _sf_reasoning_prefill_mode(_ETHINK_EFFORT, None, _EFFORT_SHAPE_TPL, "low") is False+++def test_a_template_that_stamps_a_date_still_renders():+ # Without ``strftime_now`` the render raises and the failure reads as a prefill.+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _STRFTIME_TPL) is False++def test_prefill_mode_off_without_think_markers():assert _sf_reasoning_prefill_mode(_ETHINK, None, "no markers here") is False+def test_prefill_mode_renders_the_request_messages():+ # The template reads the shape off the conversation, so a fixed stand-in classifies a+ # request nobody made and the answer to the opted-in one lands in visible content.+ plain = [{"role": "user", "content": "what is 2+2"}]+ opted_in = [{"role": "user", "content": "/think what is 2+2"}]+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _MESSAGE_SHAPE_TPL, None, plain) is False+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _MESSAGE_SHAPE_TPL, None, opted_in) is True+++def test_messages_the_template_refuses_fall_back_to_the_single_user_probe():+ # A history the template raises on must not itself read as a prefill: fall back to the+ # stand-in every caller got before the messages were threaded through.+ refused = [{"role": "user", "content": "hi"}, {"role": "tool", "content": "42"}]+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _STRICT_HISTORY_TPL, None, refused) is False+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _STRICT_HISTORY_TPL) is False+++def test_a_think_tag_the_user_typed_does_not_prefill():+ # Only the assistant prefix counts. Weighing the whole prompt would let anyone asking+ # about a <think> tag become the last opener and blank their own answer.+ for text in ("how do I emit a <think> tag?", "use <think>x</think> tags", "plain"):+ msgs = [{"role": "user", "content": text}]+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _HISTORY_ONLY_TPL, None, msgs) is False+ # A template that really does open one is still read as prefilled.+ typed = [{"role": "user", "content": "a <think> b"}]+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _THINK_TPL, None, typed) is True+++def test_content_parts_must_reach_the_probe_flattened():+ # Why the route probes the normalized conversation: the shapes disagree, so a raw array+ # would test ``'/think' in <list>``, miss the opt-in, and classify a prompt never rendered.+ flattened = [{"role": "user", "content": "/think what is 2+2"}]+ raw_parts = [{"role": "user", "content": [{"type": "text", "text": "/think what is 2+2"}]}]+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _MESSAGE_SHAPE_TPL, None, flattened) is True+ assert _sf_reasoning_prefill_mode(_ETHINK, None, _MESSAGE_SHAPE_TPL, None, raw_parts) is False+++def test_control_markup_must_reach_the_probe_swept():+ # The renderer neutralizes control markup first, so a user's ``<think>`` arrives as+ # ``< think>``. A template branching on it would otherwise split from generation.+ from core.inference.chat_template_helpers import neutralize_control_markup_in_messages++ raw = [{"role": "user", "content": "<think> tags"}]+ swept = neutralize_control_markup_in_messages([dict(m) for m in raw])+ assert swept[0]["content"] == "< think> tags"+ marker_tpl = _MESSAGE_SHAPE_TPL.replace("'/think' in", "'<think>' in")+ assert _sf_reasoning_prefill_mode(_ETHINK, None, marker_tpl, None, raw) is True+ assert _sf_reasoning_prefill_mode(_ETHINK, None, marker_tpl, None, swept) is False+++def test_prefill_mode_without_messages_matches_the_single_user_probe():+ # Omitting the argument keeps the pre-existing signature and verdict.+ for tpl in (_THINK_TPL, _TEMPLATE_DEFAULT_OFF_TPL, _MESSAGE_SHAPE_TPL):+ assert _sf_reasoning_prefill_mode(_ETHINK, None, tpl) == _sf_reasoning_prefill_mode(+ _ETHINK, None, tpl, None, [{"role": "user", "content": "hi"}]+ )++def _replay_sf_reasoning_stream(events: list[dict], *, prefilled: bool) -> dict:"""Mirror sf_tool_stream's reasoning loop: diff each cumulative ``content``snapshot, feed the delta through the extractor, and reset (flushing first) on@@ -491,3 +613,59 @@ def test_the_eager_import_under_the_stubs_actually_succeeded():f"not for anything transformers probes with importlib.util.find_spec).")assert "core.inference.inference" in sys.modules+++def _sf_route_message(monkeypatch, template, snapshots, **body):+ """POST a non-streaming safetensors chat completion and return the assistant message."""+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ import routes.inference as inference_route+ from auth.authentication import get_current_subject+ from utils.api_errors import install_api_error_handlers++ class _NoGGUF:+ is_loaded = False+ supports_tools = False++ class _Safetensors:+ active_model_name = "qwen"+ models = {"qwen": {"chat_template_info": {"template": template}}}++ def generate_chat_response(self, **kwargs):+ yield from snapshots++ def reset_generation_state(self, *_args):+ return None++ monkeypatch.setattr(+ inference_route,+ "_detect_safetensors_features",+ lambda backend, chat_template, tools = None: dict(_ETHINK, supports_tools = False),+ )+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _NoGGUF())+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Safetensors())++ app = FastAPI()+ app.include_router(inference_route.router, prefix = "/v1")+ install_api_error_handlers(app)+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ resp = TestClient(app).post(+ "/v1/chat/completions",+ json = {+ "messages": [{"role": "user", "content": "hi"}],+ "stream": False,+ **body,+ },+ )+ assert resp.status_code == 200, resp.text+ return resp.json()["choices"][0]["message"]+++def test_route_returns_the_answer_as_content_when_the_template_closes_its_block(monkeypatch):+ """The user-visible symptom: a plain answer reaching ``content``, not the thinking drawer."""+ # generate_chat_response yields cumulative text snapshots, not events.+ snapshots = ["The capital", "The capital of Japan is Tokyo."]+ message = _sf_route_message(monkeypatch, _TEMPLATE_DEFAULT_OFF_TPL, snapshots)+ assert message["content"] == "The capital of Japan is Tokyo."+ assert not message["reasoning_content"]