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 reasoning channel rendering (#7121)
Long Yixing5441266e3aba
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.pyindex 897db8262df..5113eebb36f 100644--- a/studio/backend/core/inference/chat_template_helpers.py+++ b/studio/backend/core/inference/chat_template_helpers.py@@ -10,10 +10,242 @@ native-chat-template fallback used by the transformers and MLX backends.import copyimport jsonimport logging+from dataclasses import dataclassfrom typing import Optional_THINK_OPEN = "<think>"_THINK_CLOSE = "</think>"+_GEMMA_CHANNEL_START = "<|channel>"+_GEMMA_THOUGHT_OPEN = "<|channel>thought"+_GEMMA_THOUGHT_CLOSE = "<channel|>"+_GEMMA_TEMPLATE_OPENERS = (+ _GEMMA_THOUGHT_OPEN + "\n",+ _GEMMA_THOUGHT_OPEN + "\\n",+ _GEMMA_THOUGHT_OPEN + _GEMMA_THOUGHT_CLOSE,+)+++def _tokenizer_objects(tokenizer) -> tuple:+ """Return a processor/tokenizer and its distinct nested tokenizer."""+ if tokenizer is None:+ return ()+ nested = getattr(tokenizer, "tokenizer", None)+ return (tokenizer,) if nested is None or nested is tokenizer else (tokenizer, nested)+++def _selected_template_strings_from_value(+ template,+ tools = None,+ *,+ prefer_tool_use: bool = True,+) -> tuple[str, ...]:+ """Return the named chat template matching HF's default selection rules."""+ tools = tools or None+ if isinstance(template, str):+ return (template,)+ if not isinstance(template, dict):+ return ()+ if prefer_tool_use and tools and isinstance(template.get("tool_use"), str):+ return (template["tool_use"],)+ if isinstance(template.get("default"), str):+ return (template["default"],)+ values = tuple(value for value in template.values() if isinstance(value, str))+ return values if len(values) == 1 else ()+++def _selected_chat_template_strings(tokenizer, tools = None) -> tuple[str, ...]:+ """Return the active chat template selected for this request."""+ tools = tools or None+ getter = getattr(tokenizer, "get_chat_template", None)+ if callable(getter):+ for kwargs in ({"chat_template": None, "tools": tools}, {"tools": tools}, {}):+ try:+ selected = getter(**kwargs)+ except Exception:+ continue+ if isinstance(selected, str):+ return (selected,)+ # ProcessorMixin.apply_chat_template does not switch to "tool_use" implicitly;+ # it uses "default" unless chat_template= names another template.+ is_processor = getattr(tokenizer, "tokenizer", None) is not None and callable(+ getattr(tokenizer, "apply_chat_template", None)+ )+ return _selected_template_strings_from_value(+ getattr(tokenizer, "chat_template", None),+ tools,+ prefer_tool_use = not is_processor,+ )+++def _detect_reasoning_channel_markers_from_templates(+ templates: tuple[str, ...],+) -> Optional[tuple[str, str]]:+ """Return Gemma native reasoning markers only when a template emits them."""+ if any(opener in template for template in templates for opener in _GEMMA_TEMPLATE_OPENERS):+ return _GEMMA_THOUGHT_OPEN, _GEMMA_THOUGHT_CLOSE+ return None+++def detect_reasoning_channel_markers(tokenizer, tools = None) -> Optional[tuple[str, str]]:+ """Return native Gemma thought-channel markers supported by a tokenizer.++ Detection uses the active chat template rather than model names or vocabulary+ membership. Some models expose Gemma control tokens without using the native+ thought-channel response protocol, and those must keep normal+ ``skip_special_tokens`` streaming.+ """+ for obj in _tokenizer_objects(tokenizer):+ templates = _selected_chat_template_strings(obj, tools)+ if templates:+ return _detect_reasoning_channel_markers_from_templates(templates)+ return None+++def detect_reasoning_channel_markers_from_template(+ template, tools = None+) -> Optional[tuple[str, str]]:+ """Return native Gemma thought-channel markers from a raw template value."""+ return _detect_reasoning_channel_markers_from_templates(+ _selected_template_strings_from_value(template, tools)+ )+++def detect_reasoning_channel_markers_from_model_info(+ tokenizer,+ model_info: Optional[dict] = None,+ tools = None,+) -> Optional[tuple[str, str]]:+ """Return reasoning markers from the active or cached native template."""+ markers = detect_reasoning_channel_markers(tokenizer, tools = tools)+ if markers is not None or not isinstance(model_info, dict):+ return markers++ native_templates = (+ model_info.get("native_chat_template"),+ (model_info.get("chat_template_info") or {}).get("template"),+ )+ for template in native_templates:+ markers = detect_reasoning_channel_markers_from_template(template, tools)+ if markers is not None:+ return markers+ return None+++@dataclass(frozen = True)+class ChatTemplateRenderResult:+ """Prompt plus response-protocol metadata selected by the renderer."""++ prompt: str+ reasoning_channel_markers: Optional[tuple[str, str]] = None+++def _split_partial_marker(text: str, marker: str) -> tuple[str, str]:+ """Hold the longest suffix that may become ``marker`` in the next chunk."""+ for length in range(min(len(text), len(marker) - 1), 0, -1):+ if text.endswith(marker[:length]):+ return text[:-length], text[-length:]+ return text, ""+++class ReasoningChannelNormalizer:+ """Incrementally convert one native reasoning channel to ``<think>``.++ The parser follows mlx-vlm's streaming boundary behavior but emits Studio's+ established canonical text contract. Only the configured opening and+ closing markers are consumed; tool-call and other control markers remain+ available to downstream parsers.+ """++ def __init__(self, opening_marker: str, closing_marker: str):+ self._opening_marker = opening_marker+ self._closing_marker = closing_marker+ self._buffer = ""+ self._in_reasoning = False+ self._reasoning_done = False+ self._skip_opening_newline = False++ def feed(self, text: str) -> str:+ """Consume a raw text delta and return the stable canonical delta."""+ self._buffer += text or ""+ output: list[str] = []+ while self._buffer:+ if self._reasoning_done:+ output.append(self._buffer)+ self._buffer = ""+ break++ if self._in_reasoning and self._skip_opening_newline:+ if self._buffer.startswith("\n"):+ self._buffer = self._buffer[1:]+ self._skip_opening_newline = False+ if not self._buffer:+ break++ marker = self._closing_marker if self._in_reasoning else self._opening_marker+ index = self._buffer.find(marker)+ if index < 0:+ stable, self._buffer = _split_partial_marker(self._buffer, marker)+ output.append(stable)+ break++ output.append(self._buffer[:index])+ self._buffer = self._buffer[index + len(marker) :]+ if self._in_reasoning:+ output.append(_THINK_CLOSE)+ self._in_reasoning = False+ self._reasoning_done = True+ else:+ output.append(_THINK_OPEN)+ self._in_reasoning = True+ self._skip_opening_newline = True+ return "".join(output)++ def finish(self) -> str:+ """Flush a naturally completed stream and close an open think block."""+ output = self.drain()+ if self._in_reasoning:+ output += _THINK_CLOSE+ self._in_reasoning = False+ self._reasoning_done = True+ return output++ def drain(self) -> str:+ """Flush buffered literal text without synthesizing a closing tag."""+ output = self._buffer+ self._buffer = ""+ return output+++def normalize_reasoning_snapshots(+ stream,+ tokenizer = None,+ cancel_event = None,+ markers: Optional[tuple[str, str]] = None,+ tools = None,+):+ """Normalize a prefix-monotonic cumulative text stream when supported."""+ markers = markers or detect_reasoning_channel_markers(tokenizer, tools = tools)+ if markers is None:+ yield from stream+ return++ normalizer = ReasoningChannelNormalizer(*markers)+ raw_output = ""+ normalized_output = ""+ for snapshot in stream:+ if not snapshot.startswith(raw_output):+ raise RuntimeError("Reasoning normalization requires cumulative text snapshots")+ delta = normalizer.feed(snapshot[len(raw_output) :])+ raw_output = snapshot+ if delta:+ normalized_output += delta+ yield normalized_output++ cancelled = cancel_event is not None and cancel_event.is_set()+ tail = normalizer.drain() if cancelled else normalizer.finish()+ if tail:+ normalized_output += tail+ yield normalized_outputdef detect_think_prefill(prompt: Optional[str], special_tokens = None) -> str:@@ -166,7 +398,8 @@ def render_native_template(preserve_thinking: Optional[bool] = None,apply_fn = None,hf_token: Optional[str] = None,-) -> Optional[str]:+ return_metadata: bool = False,+):"""Render ``messages`` + ``tools`` with the model's NATIVE chat template.Some Unsloth override templates (e.g. ``mistral``, ``gemma-4``) do not emit@@ -175,7 +408,9 @@ def render_native_template(tool-calling syntax. It is loaded straight from the repo (bypassing anyoverride on the live tokenizer) and cached on ``model_info``. Returns therendered prompt only if the native template actually emits the tools (render- differs with vs without tools); otherwise ``None``.+ differs with vs without tools); otherwise ``None``. With ``return_metadata``,+ returns ``ChatTemplateRenderResult`` so callers can stream with the response+ protocol selected by this request's template.``hf_token`` is the token the model was loaded with -- passed to the repo loadso a gated/private model's native template can still be fetched (otherwise the@@ -261,7 +496,16 @@ def render_native_template(exc,)return None- return with_tools if with_tools != no_tools else None+ if with_tools == no_tools:+ return None+ if return_metadata:+ return ChatTemplateRenderResult(+ with_tools,+ _detect_reasoning_channel_markers_from_templates(+ _selected_template_strings_from_value(native_tpl, tools)+ ),+ )+ return with_toolsdef render_with_native_template_fallback(@@ -277,7 +521,8 @@ def render_with_native_template_fallback(preserve_thinking: Optional[bool] = None,apply_fn = None,hf_token: Optional[str] = None,-) -> str:+ return_metadata: bool = False,+):"""Return ``formatted_prompt``, swapping in a native-template render when anoverride template dropped the ``tools`` schema.@@ -285,9 +530,27 @@ def render_with_native_template_fallback(them (detected by comparison, robust against tool names in the system prompt),re-render with the model's native template. Shared by the transformers and MLXbackends so both advertise tools consistently. ``hf_token`` is forwarded so a- gated/private model's native template can still be fetched."""+ gated/private model's native template can still be fetched. With+ ``return_metadata``, returns the selected prompt plus reasoning-channel markers+ for the exact template used by this request."""+ live_markers = detect_reasoning_channel_markers(tokenizer, tools = tools)++ def _result(prompt: str, markers = live_markers):+ if return_metadata:+ return ChatTemplateRenderResult(prompt, markers)+ return prompt+if not tools:- return formatted_prompt+ # Gemma 4 can emit its native reasoning protocol even when a generation-time+ # Unsloth override rendered a marker-free prompt. Preserve the live-verified+ # no-tools thinking behavior without letting cached native metadata describe+ # unrelated tool prompts that kept the active override.+ markers = live_markers+ if markers is None:+ markers = detect_reasoning_channel_markers_from_model_info(+ tokenizer, model_info, tools = None+ )+ return _result(formatted_prompt, markers)if apply_fn is None:apply_fn = apply_chat_template_for_generation# Probe whether the live template dropped the schema. A tools-requiring template@@ -307,9 +570,9 @@ def render_with_native_template_fallback(active_model_name,exc,)- return formatted_prompt+ return _result(formatted_prompt)if formatted_prompt != probe_no_tools:- return formatted_prompt # template already emits the tools schema+ return _result(formatted_prompt) # template already emits the tools schemanative_prompt = render_native_template(model_info = model_info,active_model_name = active_model_name,@@ -320,6 +583,7 @@ def render_with_native_template_fallback(preserve_thinking = preserve_thinking,apply_fn = apply_fn,hf_token = hf_token,+ return_metadata = return_metadata,)if native_prompt:logger.info(@@ -328,4 +592,4 @@ def render_with_native_template_fallback(active_model_name,)return native_prompt- return formatted_prompt+ return _result(formatted_prompt)diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex 172e9e5546a..eae705d20e3 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -5,7 +5,7 @@from unsloth import FastLanguageModel, FastVisionModelfrom unsloth.chat_templates import get_chat_template-from transformers import TextStreamer+from transformers import TextIteratorStreamer, TextStreamerfrom peft import PeftModel, PeftModelForCausalLMimport json@@ -32,6 +32,11 @@ from core.inference.chat_eos import (chat_eos_repair,resolve_chat_turn_end_eos_ids_using,)+from core.inference.chat_template_helpers import (+ ReasoningChannelNormalizer,+ detect_reasoning_channel_markers,+ detect_think_prefill,+)from core.inference.presence_penalty import _make_presence_penalty_processorfrom io import StringIOimport structlog@@ -187,6 +192,53 @@ class HarmonyTextStreamer:self._queue.put(new_content)+class ReasoningTextIteratorStreamer(TextIteratorStreamer):+ """TextIteratorStreamer that preserves native channel tokens until parsed."""++ def __init__(+ self,+ tokenizer,+ *,+ markers: tuple[str, str],+ skip_prompt: bool = True,+ timeout: float = 0.2,+ cancel_event = None,+ **decode_kwargs,+ ):+ decode_kwargs["skip_special_tokens"] = False+ super().__init__(tokenizer, skip_prompt = skip_prompt, timeout = timeout, **decode_kwargs)+ self._normalizer = ReasoningChannelNormalizer(*markers)+ self._cancel_event = cancel_event+ self._aborted = False++ def abort(self):+ """Mark generation as failed so ``end`` drains without closing."""+ self._aborted = True++ def on_finalized_text(+ self,+ text: str,+ stream_end: bool = False,+ ):+ """Queue canonical deltas, closing only on natural stream completion."""+ delta = self._normalizer.feed(text)+ if delta:+ self.text_queue.put(delta, timeout = self.timeout)++ if stream_end:+ cancelled = self._aborted or (+ self._cancel_event is not None and self._cancel_event.is_set()+ )+ tail = self._normalizer.drain() if cancelled else self._normalizer.finish()+ if tail:+ self.text_queue.put(tail, timeout = self.timeout)+ self.text_queue.put(self.stop_signal, timeout = self.timeout)+++class _GenerationThreadError(RuntimeError):+ """Generation worker failures that should propagate through stream routes."""++class InferenceBackend:"""Unified inference backend supporting text, vision, and LoRA models"""@@ -960,8 +1012,7 @@ class InferenceBackend:thread can toggle adapters under the generation lock."""if not self.active_model_name:- yield "Error: No active model"- return+ raise RuntimeError("No active model")model_info = self.models[self.active_model_name]is_vision = model_info.get("is_vision", False)@@ -1049,6 +1100,7 @@ class InferenceBackend:template_messages = [{"role": "system", "content": system_prompt}] + messageselse:template_messages = messages+ reasoning_channel_markers_resolved = Falsetry:if not (hasattr(tokenizer, "chat_template") and tokenizer.chat_template):raise ValueError(@@ -1058,6 +1110,7 @@ class InferenceBackend:f"Please use a model that includes a chat template, or manually set "f"one via tokenizer.chat_template before inference.")+ reasoning_channel_markers = Noneformatted_prompt = self._apply_chat_template_for_generation(tokenizer,template_messages,@@ -1073,7 +1126,7 @@ class InferenceBackend:render_with_native_template_fallback,)- formatted_prompt = render_with_native_template_fallback(+ render_result = render_with_native_template_fallback(formatted_prompt = formatted_prompt,tokenizer = tokenizer,model_info = model_info,@@ -1085,13 +1138,19 @@ class InferenceBackend:preserve_thinking = preserve_thinking,apply_fn = self._apply_chat_template_for_generation,hf_token = model_info.get("hf_token"),+ return_metadata = True,)+ formatted_prompt = render_result.prompt+ reasoning_channel_markers = render_result.reasoning_channel_markers+ reasoning_channel_markers_resolved = Truelogger.debug(f"Formatted prompt: {formatted_prompt[:200]}...")except Exception as e:logger.error(f"Error applying chat template: {e}")# Fall back to manual formattingformatted_prompt = self.format_chat_prompt(messages, system_prompt)+ reasoning_channel_markers = None+ reasoning_channel_markers_resolved = True# Step 3: generateyield from self.generate_stream(@@ -1105,6 +1164,8 @@ class InferenceBackend:cancel_event = cancel_event,_adapter_state = _adapter_state,presence_penalty = presence_penalty,+ reasoning_channel_markers = reasoning_channel_markers,+ reasoning_channel_markers_resolved = reasoning_channel_markers_resolved,)def _generate_vision_response(@@ -1190,21 +1251,27 @@ class InferenceBackend:# Stream with TextIteratorStreamer + background threadtry:- from core.inference.chat_template_helpers import detect_think_prefill-# Re-emit an open <think> prefill swallowed by skip_prompt (see# generate_stream).think_prefix = detect_think_prefill(prompt_text, getattr(raw_tokenizer, "all_special_tokens", None))- from transformers import TextIteratorStreamerimport threading- streamer = TextIteratorStreamer(+ streamer = self._make_text_streamer(raw_tokenizer,+ protocol_source = processor,+ # The text-only VLM fallback above did not render with the+ # processor template, so its native markers do not describe+ # this request's response protocol.+ reasoning_channel_markers = detect_reasoning_channel_markers(processor)+ if image+ else None,+ reasoning_channel_markers_resolved = True,skip_prompt = True,- skip_special_tokens = True,timeout = 0.2,+ cancel_event = cancel_event,+ use_harmony = self._is_gpt_oss_model(),)generation_kwargs = dict(@@ -1226,6 +1293,10 @@ class InferenceBackend:)if _pp is not None:generation_kwargs["logits_processor"] = _pp+ stopping_criteria = self._cancel_stopping_criteria(cancel_event)+ if stopping_criteria is not None:+ generation_kwargs["stopping_criteria"] = stopping_criteria+ active_stop_token_ids = self._generation_stop_token_ids(model, generation_kwargs)err: dict[str, str] = {}@@ -1235,6 +1306,8 @@ class InferenceBackend:model.generate(**generation_kwargs)except Exception as e:err["msg"] = str(e)+ if hasattr(streamer, "abort"):+ streamer.abort()logger.error(f"Vision generation error in thread: {e}")finally:try:@@ -1251,12 +1324,17 @@ class InferenceBackend:if think_prefix:yield think_prefixfrom queue import Empty+ import timegeneration_complete = False+ cancel_deadline = Nonetry:while True:if cancel_event is not None and cancel_event.is_set():- break+ if cancel_deadline is None:+ cancel_deadline = time.monotonic() + 10+ elif time.monotonic() >= cancel_deadline:+ breaktry:new_token = next(streamer)except StopIteration:@@ -1265,27 +1343,48 @@ class InferenceBackend:except Empty:if not thread.is_alive():generation_complete = True+ output = yield from self._drain_streamer_tail(+ streamer, output, active_stop_token_ids+ )+ break+ if cancel_deadline is not None:+ remaining = cancel_deadline - time.monotonic()+ if remaining <= 0:+ break+ thread.join(timeout = remaining)+ if thread.is_alive():+ break+ generation_complete = True+ output = yield from self._drain_streamer_tail(+ streamer, output, active_stop_token_ids+ )breakcontinueif new_token:- output += new_token- cleaned = self._clean_generated_text(output)+ output, cleaned = self._append_stream_delta(+ output, new_token, active_stop_token_ids+ )yield cleanedfinally:if cancel_event is not None and not generation_complete:cancel_event.set()- thread.join(timeout = 10)+ join_timeout = 10+ if cancel_deadline is not None:+ join_timeout = max(0, cancel_deadline - time.monotonic())+ thread.join(timeout = join_timeout)if thread.is_alive():logger.warning("Vision generation thread did not exit after cancel/join timeout")if err.get("msg"):- yield f"Error: {err['msg']}"+ raise _GenerationThreadError(err["msg"])+ except _GenerationThreadError:+ raiseexcept Exception as e:logger.error(f"Vision generation error: {e}")- yield f"Error: {str(e)}"+ raisedef generate_audio_input_response(self,@@ -1410,11 +1509,13 @@ class InferenceBackend:)if err.get("msg"):- yield f"Error: {err['msg']}"+ raise _GenerationThreadError(err["msg"])+ except _GenerationThreadError:+ raiseexcept Exception as e:logger.error(f"Audio input generation error: {e}")- yield f"Error: {str(e)}"+ raisedef generate_whisper_response(self,@@ -1447,6 +1548,86 @@ class InferenceBackend:from utils.datasets import is_gpt_oss_model_namereturn is_gpt_oss_model_name(model_name or self.active_model_name or "")+ def _make_text_streamer(+ self,+ tokenizer,+ *,+ protocol_source = None,+ reasoning_channel_markers = None,+ reasoning_channel_markers_resolved: bool = False,+ skip_prompt: bool = True,+ timeout: float = 0.2,+ cancel_event = None,+ use_harmony: bool = False,+ ):+ """Create the streamer matching this model's native response protocol."""+ if use_harmony:+ try:+ return HarmonyTextStreamer(+ tokenizer,+ skip_prompt = skip_prompt,+ timeout = timeout,+ )+ except Exception as e:+ logger.warning(f"HarmonyTextStreamer init failed, falling back: {e}")+ return TextIteratorStreamer(+ tokenizer,+ skip_prompt = skip_prompt,+ skip_special_tokens = True,+ timeout = timeout,+ )++ markers = (+ reasoning_channel_markers+ if reasoning_channel_markers_resolved+ else reasoning_channel_markers+ or detect_reasoning_channel_markers(protocol_source or tokenizer)+ )+ if markers is not None:+ return ReasoningTextIteratorStreamer(+ tokenizer,+ markers = markers,+ skip_prompt = skip_prompt,+ timeout = timeout,+ cancel_event = cancel_event,+ )+ return TextIteratorStreamer(+ tokenizer,+ skip_prompt = skip_prompt,+ skip_special_tokens = True,+ timeout = timeout,+ )++ def _append_stream_delta(+ self,+ output: str,+ new_token: str,+ stop_token_ids = None,+ ):+ """Append a streamer delta and apply response-boundary cleanup."""+ output += new_token+ return output, self._clean_generated_text(output, stop_token_ids = stop_token_ids)++ def _drain_streamer_tail(+ self,+ streamer,+ output: str,+ stop_token_ids = None,+ ):+ """Drain queued streamer text after the producer exits."""+ while True:+ try:+ new_token = next(streamer)+ except StopIteration:+ return output+ except Exception:+ return output+ if new_token:+ output, cleaned = self._append_stream_delta(+ output, new_token, stop_token_ids = stop_token_ids+ )+ yield cleaned+def generate_stream(self,prompt: str,@@ -1459,6 +1640,8 @@ class InferenceBackend:cancel_event = None,_adapter_state = None,presence_penalty: float = 0.0,+ reasoning_channel_markers = None,+ reasoning_channel_markers_resolved: bool = False,) -> Generator[str, None, None]:"""Generate a streaming text response (text models only).@@ -1467,8 +1650,7 @@ class InferenceBackend:``presence_penalty`` matches the GGUF sampling path via a logits processor (0 disables it)."""if not self.active_model_name:- yield "Error: No active model"- return+ raise RuntimeError("No active model")model_info = self.models[self.active_model_name]model = model_info["model"]@@ -1481,9 +1663,7 @@ class InferenceBackend:try:inputs = tokenizer(prompt, return_tensors = "pt").to(model.device)- from transformers import TextIteratorStreamerimport threading- from core.inference.chat_template_helpers import detect_think_prefill# skip_prompt swallows an open <think> prefilled by the template;# re-emit it so the frontend can render the thinking block.@@ -1494,30 +1674,16 @@ class InferenceBackend:else detect_think_prefill(prompt, getattr(tokenizer, "all_special_tokens", None)))- # gpt-oss models: HarmonyTextStreamer parses the multi-channel- # harmony protocol into <think> tags- if self._is_gpt_oss_model():- try:- streamer = HarmonyTextStreamer(- tokenizer,- skip_prompt = True,- timeout = 0.2,- )- except Exception as e:- logger.warning(f"HarmonyTextStreamer init failed, falling back: {e}")- streamer = TextIteratorStreamer(- tokenizer,- skip_prompt = True,- skip_special_tokens = True,- timeout = 0.2,- )- else:- streamer = TextIteratorStreamer(- tokenizer,- skip_prompt = True,- skip_special_tokens = True,- timeout = 0.2,- )+ streamer = self._make_text_streamer(+ tokenizer,+ protocol_source = model_info.get("tokenizer"),+ reasoning_channel_markers = reasoning_channel_markers,+ reasoning_channel_markers_resolved = reasoning_channel_markers_resolved,+ skip_prompt = True,+ timeout = 0.2,+ cancel_event = cancel_event,+ use_harmony = self._is_gpt_oss_model(),+ )generation_kwargs = dict(**inputs,@@ -1535,27 +1701,16 @@ class InferenceBackend:if tokenizer.pad_token_id is Noneelse tokenizer.pad_token_id,)+ active_stop_token_ids = self._generation_stop_token_ids(model, generation_kwargs)# Presence penalty (GGUF parity); prompt_len excludes prompt tokens._pp = _make_presence_penalty_processor(presence_penalty, int(inputs["input_ids"].shape[1]))if _pp is not None:generation_kwargs["logits_processor"] = _pp- if cancel_event is not None:- from transformers.generation.stopping_criteria import (- StoppingCriteria,- StoppingCriteriaList,- )- class _CancelCriteria(StoppingCriteria):- def __init__(self, ev):- self.ev = ev-- def __call__(self, input_ids, scores, **kwargs):- return self.ev.is_set()-- generation_kwargs["stopping_criteria"] = StoppingCriteriaList(- [_CancelCriteria(cancel_event)]- )+ stopping_criteria = self._cancel_stopping_criteria(cancel_event)+ if stopping_criteria is not None:+ generation_kwargs["stopping_criteria"] = stopping_criteriadef generate_fn():with self._generation_lock:@@ -1565,6 +1720,8 @@ class InferenceBackend:model.generate(**generation_kwargs)except Exception as e:err["msg"] = str(e)+ if hasattr(streamer, "abort"):+ streamer.abort()logger.error(f"Generation error: {e}")finally:try:@@ -1582,12 +1739,17 @@ class InferenceBackend:if think_prefix:yield think_prefixfrom queue import Empty+ import timegeneration_complete = False+ cancel_deadline = Nonetry:while True:if cancel_event is not None and cancel_event.is_set():- break+ if cancel_deadline is None:+ cancel_deadline = time.monotonic() + 10+ elif time.monotonic() >= cancel_deadline:+ breaktry:new_token = next(streamer)except StopIteration:@@ -1596,11 +1758,27 @@ class InferenceBackend:except Empty:if not thread.is_alive():generation_complete = True+ output = yield from self._drain_streamer_tail(+ streamer, output, active_stop_token_ids+ )+ break+ if cancel_deadline is not None:+ remaining = cancel_deadline - time.monotonic()+ if remaining <= 0:+ break+ thread.join(timeout = remaining)+ if thread.is_alive():+ break+ generation_complete = True+ output = yield from self._drain_streamer_tail(+ streamer, output, active_stop_token_ids+ )breakcontinueif new_token:- output += new_token- cleaned = self._clean_generated_text(output)+ output, cleaned = self._append_stream_delta(+ output, new_token, active_stop_token_ids+ )yield cleanedfinally:# Set cancel_event only on early exit (user cancel), NOT on@@ -1609,16 +1787,21 @@ class InferenceBackend:# disrupt the next serialized request (e.g. compare mode).if cancel_event is not None and not generation_complete:cancel_event.set()- thread.join(timeout = 10)+ join_timeout = 10+ if cancel_deadline is not None:+ join_timeout = max(0, cancel_deadline - time.monotonic())+ thread.join(timeout = join_timeout)if thread.is_alive():logger.warning("Generation thread did not exit after cancel/join timeout")if err.get("msg"):- yield f"Error: {err['msg']}"+ raise _GenerationThreadError(err["msg"])+ except _GenerationThreadError:+ raiseexcept Exception as e:logger.error(f"Error during generation: {e}")- yield f"Error: {str(e)}"+ raise# ── Audio (TTS) Generation ────────────────────────────────────@@ -2107,8 +2290,42 @@ class InferenceBackend:return img.resize(new_size, Image.Resampling.LANCZOS)return img- def _clean_generated_text(self, text: str) -> str:- """Strip leaked special tokens using the tokenizer's own token list."""+ def _generation_stop_token_ids(self, model, generation_kwargs: dict):+ """Return the stop-token ids active for a ``generate`` call."""+ if "eos_token_id" in generation_kwargs:+ return generation_kwargs.get("eos_token_id")+ generation_config = getattr(model, "generation_config", None)+ eos_token_id = getattr(generation_config, "eos_token_id", None)+ if eos_token_id is not None:+ return eos_token_id+ config = getattr(model, "config", None)+ return getattr(config, "eos_token_id", None)++ def _cancel_stopping_criteria(self, cancel_event):+ """Build a Transformers stopping criteria list for user cancellation."""+ if cancel_event is None:+ return None+ from transformers.generation.stopping_criteria import (+ StoppingCriteria,+ StoppingCriteriaList,+ )++ class _CancelCriteria(StoppingCriteria):+ def __init__(self, ev):+ self.ev = ev++ def __call__(self, input_ids, scores, **kwargs):+ return self.ev.is_set()++ return StoppingCriteriaList([_CancelCriteria(cancel_event)])++ def _clean_generated_text(+ self,+ text: str,+ *,+ stop_token_ids = None,+ ) -> str:+ """Strip leaked response-boundary tokens after streaming."""if self._is_gpt_oss_model():# HarmonyTextStreamer emits clean <think>...</think>. Strip any# harmony protocol tokens and other gpt-oss tokens (e.g.@@ -2118,10 +2335,28 @@ class InferenceBackend:return text.strip()tokenizer = self.models.get(self.active_model_name, {}).get("tokenizer")+ tokenizer = getattr(tokenizer, "tokenizer", tokenizer)if tokenizer:- for token in getattr(tokenizer, "all_special_tokens", []):- if token in text:- text = text.replace(token, "")+ if stop_token_ids is None:+ stop_token_ids = self.models.get(self.active_model_name, {}).get(+ "chat_turn_end_eos_ids"+ )+ if isinstance(stop_token_ids, int):+ stop_token_ids = (stop_token_ids,)+ for token_id in stop_token_ids or ():+ try:+ token = tokenizer.convert_ids_to_tokens(int(token_id))+ except Exception:+ token = None+ if isinstance(token, str) and token and text.endswith(token):+ text = text[: -len(token)]+ elif (+ isinstance(token, str)+ and token+ and text.endswith("</think>")+ and text[: -len("</think>")].endswith(token)+ ):+ text = text[: -len("</think>") - len(token)] + "</think>"return text.strip()def _load_chat_template_info(self, model_name: str):diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 163ade10c4d..e7a90b4307e 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -11,6 +11,10 @@ import threadingfrom typing import Optional, Generatorfrom core.inference.message_content import content_to_textfrom core.inference.runtime_context import runtime_context_length+from core.inference.chat_template_helpers import (+ ReasoningChannelNormalizer,+ normalize_reasoning_snapshots,+)from loggers import get_loggerlogger = get_logger(__name__)@@ -533,7 +537,7 @@ class MLXInferenceBackend:breakif self._is_vlm:- yield from self._generate_vlm(+ stream = self._generate_vlm(full_messages,image,temperature,@@ -550,7 +554,7 @@ class MLXInferenceBackend:presence_penalty = presence_penalty,)else:- yield from self._generate_text(+ stream = self._generate_text(full_messages,temperature,top_p,@@ -565,6 +569,7 @@ class MLXInferenceBackend:preserve_thinking = preserve_thinking,presence_penalty = presence_penalty,)+ yield from streamdef _generate_text(self,@@ -609,7 +614,7 @@ class MLXInferenceBackend:# probe and native render share a renderer. (VLM renders via the# processor for image tokens and is not wired here.)model_info = self.models.get(self.active_model_name, {})- prompt = render_with_native_template_fallback(+ render_result = render_with_native_template_fallback(formatted_prompt = prompt,tokenizer = self._tokenizer,model_info = model_info,@@ -620,7 +625,10 @@ class MLXInferenceBackend:reasoning_effort = reasoning_effort,preserve_thinking = preserve_thinking,hf_token = model_info.get("hf_token"),+ return_metadata = True,)+ prompt = render_result.prompt+ reasoning_channel_markers = render_result.reasoning_channel_markers# An open <think> prefilled by the template lives in the prompt, not# the generated tokens; re-emit it so the frontend renders the block.@@ -654,7 +662,17 @@ class MLXInferenceBackend:if not logits_processors:logits_processors = None+ preserve_native_channels = reasoning_channel_markers is not Nonetoken_ids = []+ normalizer = (+ ReasoningChannelNormalizer(*reasoning_channel_markers)+ if reasoning_channel_markers is not None+ else None+ )+ # MLX consumers diff cumulative snapshots. Keep a prompt-prefilled+ # <think> prefix on every native-protocol snapshot just as the normal+ # decoding path does below.+ normalized_output = think_prefixlogger.info("Generating: prompt_len=%d, max_tokens=%d, model=%s, tokenizer=%s",len(prompt),@@ -678,12 +696,19 @@ class MLXInferenceBackend:**gen_kwargs,):final_response = response- token_ids.append(response.token)- cumulative = self._tokenizer.decode(- token_ids,- skip_special_tokens = True,- )- yield think_prefix + cumulative+ if preserve_native_channels:+ piece = getattr(response, "text", None) or ""+ delta = normalizer.feed(piece)+ if delta:+ normalized_output += delta+ yield normalized_output+ else:+ token_ids.append(response.token)+ cumulative = self._tokenizer.decode(+ token_ids,+ skip_special_tokens = True,+ )+ yield think_prefix + cumulativeif cancel_event and cancel_event.is_set():break@@ -700,6 +725,12 @@ class MLXInferenceBackend:getattr(final_response, "generation_tokens", 0),getattr(final_response, "generation_tps", 0.0),)+ if normalizer is not None:+ cancelled = cancel_event is not None and cancel_event.is_set()+ tail = normalizer.drain() if cancelled else normalizer.finish()+ if tail:+ normalized_output += tail+ yield normalized_outputdef _generate_vlm(self,@@ -858,31 +889,37 @@ class MLXInferenceBackend:elif _rep_active:vlm_kwargs["repetition_penalty"] = float(repetition_penalty)- with self._generation_lock:- final_response = None- try:- for response in vlm_stream(- self._model,- self._processor,- prompt,- images,- **vlm_kwargs,- ):- final_response = response- token_text = response.text if hasattr(response, "text") else str(response)- cumulative += token_text- yield cumulative- if cancel_event and cancel_event.is_set():- break- finally:- # mlx_vlm exposes the same stats fields as mlx_lm.- if final_response is not None:- self.last_generation_stats = _build_generation_stats(- getattr(final_response, "prompt_tokens", 0),- getattr(final_response, "prompt_tps", 0.0),- getattr(final_response, "generation_tokens", 0),- getattr(final_response, "generation_tps", 0.0),- )+ def _stream_vlm_snapshots():+ nonlocal cumulative+ with self._generation_lock:+ final_response = None+ try:+ for response in vlm_stream(+ self._model,+ self._processor,+ prompt,+ images,+ **vlm_kwargs,+ ):+ final_response = response+ token_text = response.text if hasattr(response, "text") else str(response)+ cumulative += token_text+ yield cumulative+ if cancel_event and cancel_event.is_set():+ break+ finally:+ # mlx_vlm exposes the same stats fields as mlx_lm.+ if final_response is not None:+ self.last_generation_stats = _build_generation_stats(+ getattr(final_response, "prompt_tokens", 0),+ getattr(final_response, "prompt_tps", 0.0),+ getattr(final_response, "generation_tokens", 0),+ getattr(final_response, "generation_tps", 0.0),+ )++ yield from normalize_reasoning_snapshots(+ _stream_vlm_snapshots(), chat_target, cancel_event, tools = tools+ )def generate_with_adapter_control(self,diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex c2082bc198b..ea3b164052b 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -59,7 +59,32 @@ class GenStreamError(str):"Error:" by checking isinstance(chunk, GenStreamError)."""- __slots__ = ()+ __slots__ = ("public",)++ def __new__(+ cls,+ value,+ *,+ public: bool = False,+ ):+ obj = str.__new__(cls, value)+ obj.public = bool(public)+ return obj+++class GenStreamErrorRaised(RuntimeError):+ """Internal exception form of ``GenStreamError`` for generator boundaries."""++ __slots__ = ("public",)++ def __init__(+ self,+ value,+ *,+ public: bool = False,+ ):+ super().__init__(value)+ self.public = bool(public)class InferenceOrchestrator:@@ -531,13 +556,19 @@ class InferenceOrchestrator:initial_resp_queue = self._resp_queuewhile True:if self._proc is not initial_proc or self._resp_queue is not initial_resp_queue:- yield GenStreamError(f"Error: {self._subprocess_crash_message(crash_context)}")+ yield GenStreamError(+ f"Error: {self._subprocess_crash_message(crash_context)}",+ public = True,+ )returnresp = read_one(read_timeout)if resp is None:# Check subprocess healthif not self._ensure_subprocess_alive():- yield GenStreamError(f"Error: {self._subprocess_crash_message(crash_context)}")+ yield GenStreamError(+ f"Error: {self._subprocess_crash_message(crash_context)}",+ public = True,+ )returncontinue@@ -689,11 +720,11 @@ class InferenceOrchestrator:GPU work stays serialized; this only avoids orchestrator lock contention."""if not self._ensure_subprocess_alive():- yield GenStreamError("Error: Inference subprocess is not running")+ yield GenStreamError("Error: Inference subprocess is not running", public = True)returnif not self.active_model_name:- yield GenStreamError("Error: No active model")+ yield GenStreamError("Error: No active model", public = True)return# Latch the target model so the recheck below can detect a switch that completed# between _start_dispatcher and mailbox registration (mirrors the locked path's@@ -704,7 +735,7 @@ class InferenceOrchestrator:# so without this early-out a compare request would enqueue a generate on the# outgoing model and delay the switch.if self._unload_pending:- yield GenStreamError("Error: model is being unloaded")+ yield GenStreamError("Error: model is being unloaded", public = True)return# Ensure the dispatcher runs. _start_dispatcher serializes concurrent starters under@@ -776,7 +807,7 @@ class InferenceOrchestrator:# _stop_dispatcher joins the dispatcher, which itself takes that lock.if orphaned_dispatcher:self._stop_dispatcher()- yield GenStreamError("Error: model is being unloaded")+ yield GenStreamError("Error: model is being unloaded", public = True)returntry:@@ -1414,12 +1445,27 @@ class InferenceOrchestrator:presence_penalty = presence_penalty,)if use_adapter is not None:- yield from self.generate_with_adapter_control(+ stream = self.generate_with_adapter_control(use_adapter = use_adapter,**common_kwargs,)else:- yield from self.generate_chat_response(**common_kwargs)+ stream = self.generate_chat_response(**common_kwargs)+ close_stream = False+ try:+ for chunk in stream:+ if isinstance(chunk, GenStreamError):+ close_stream = True+ raise GenStreamErrorRaised(str(chunk), public = chunk.public)+ yield chunk+ finally:+ if close_stream:+ close = getattr(stream, "close", None)+ if callable(close):+ try:+ close()+ except Exception:+ logger.debug("failed to close errored generation stream", exc_info = True)initial = list(messages)if system_prompt:@@ -1489,11 +1535,11 @@ class InferenceOrchestrator:readers don't consume each other's tokens off the shared resp_queue."""if not self._ensure_subprocess_alive():- yield GenStreamError("Error: Inference subprocess is not running")+ yield GenStreamError("Error: Inference subprocess is not running", public = True)returnif not self.active_model_name:- yield GenStreamError("Error: No active model")+ yield GenStreamError("Error: No active model", public = True)returnexpected_model = self.active_model_name@@ -1510,7 +1556,7 @@ class InferenceOrchestrator:# so we never generate on the wrong one.if self._unload_pending or self.active_model_name != expected_model:# Won the lock handoff during a switch; don't start on the outgoing model.- yield GenStreamError("Error: model is being unloaded")+ yield GenStreamError("Error: model is being unloaded", public = True)returnrequest_id = str(uuid.uuid4())image_b64 = self._pil_to_base64(image) if image is not None else None@@ -1695,10 +1741,10 @@ class InferenceOrchestrator:) -> Generator[str, None, None]:"""Shared inner logic for audio input generation (Whisper + ASR)."""if not self._ensure_subprocess_alive():- yield GenStreamError("Error: Inference subprocess is not running")+ yield GenStreamError("Error: Inference subprocess is not running", public = True)returnif not self.active_model_name:- yield GenStreamError("Error: No active model")+ yield GenStreamError("Error: No active model", public = True)returnexpected_model = self.active_model_name@@ -1707,7 +1753,7 @@ class InferenceOrchestrator:# cleared or swapped the model while we waited.if self._unload_pending or self.active_model_name != expected_model:# Won the lock handoff during a switch; don't start on the outgoing model.- yield GenStreamError("Error: model is being unloaded")+ yield GenStreamError("Error: model is being unloaded", public = True)returnrequest_id = str(uuid.uuid4())diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 81dea96274e..d6090e2b624 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -29,6 +29,7 @@ import re as _refrom utils.models import extract_model_size_b as _extract_model_size_bfrom utils.api_errors import openai_error_body, anthropic_error_body+from core.inference.orchestrator import GenStreamError, GenStreamErrorRaisedfrom core.inference.llama_admission import (LlamaAdmissionCancelled,LlamaAdmissionConfig,@@ -213,6 +214,14 @@ def _friendly_error(exc: Exception) -> str:return "An internal error occurred"+def _friendly_gen_stream_error(value) -> str:+ """Return a client-safe message for typed local generation errors."""+ text = str(value)+ if getattr(value, "public", False):+ return text+ return safe_error_detail(RuntimeError(text), fallback = "An internal error occurred.")++def _friendly_upstream_error(text: str) -> str:"""Rewrite a raw llama-server error body into an actionable message where we can.@@ -1918,16 +1927,57 @@ async def artifact_preview_frame(allow_network: bool = False):_BARE_JSON_NAME_MARKER_RE = _re.compile(r'\{\s*\\?"(?:name|function)\\?"\s*:')-def _detect_safetensors_features(backend, chat_template: Optional[str]) -> dict:+def _detect_safetensors_features(+ backend,+ chat_template: Optional[str],+ tools = None,+) -> dict:"""Classify reasoning/tool capabilities via the GGUF classifier so flagsmatch across backends. gpt-oss is overridden: Harmony routes reasoning andtools through tokenizer channels, not template markup."""model_id = getattr(backend, "active_model_name", None)+ feature_template = chat_template+ try:+ from core.inference.chat_template_helpers import _selected_template_strings_from_value+ selected_templates = _selected_template_strings_from_value(chat_template, tools)+ if selected_templates:+ feature_template = selected_templates[0]+ except Exception:+ logger.debug("safetensors_named_template_selection_failed", exc_info = True)flags = detect_reasoning_flags(- chat_template,+ feature_template,model_identifier = model_id,log_source = "safetensors",)+ if not flags.get("supports_reasoning"):+ try:+ from core.inference.chat_template_helpers import (+ detect_reasoning_channel_markers_from_template,+ )++ templates = [chat_template]+ models = getattr(backend, "models", None)+ model_info = (+ models.get(model_id, {})+ if isinstance(models, dict) and model_id is not None+ else {}+ )+ if isinstance(model_info, dict):+ templates.extend(+ (+ model_info.get("native_chat_template"),+ (model_info.get("chat_template_info") or {}).get("template"),+ )+ )+ if any(+ detect_reasoning_channel_markers_from_template(template, tools = tools) is not None+ for template in templates+ ):+ flags["supports_reasoning"] = True+ flags["reasoning_always_on"] = True+ logger.info("safetensors: model always reasons (native channel markers)")+ except Exception:+ logger.debug("safetensors_native_reasoning_marker_check_failed", exc_info = True)# Markers any supported parser recognises (template advertises tools but# uses none -> drop the pill). Reuse the parser's own signal list so this# gate never drifts (a hand-maintained copy lost the DeepSeek variants);@@ -1941,9 +1991,9 @@ def _detect_safetensors_features(backend, chat_template: Optional[str]) -> dict:)if (flags.get("supports_tools")- and chat_template- and not any(m in chat_template for m in _PARSER_MARKERS)- and not _BARE_JSON_NAME_MARKER_RE.search(chat_template)+ and isinstance(feature_template, str)+ and not any(m in feature_template for m in _PARSER_MARKERS)+ and not _BARE_JSON_NAME_MARKER_RE.search(feature_template)):logger.info("safetensors: template advertises tools but uses an "@@ -5424,6 +5474,10 @@ async def generate_stream(if chunk is _DONE:completed = Truebreak+ if isinstance(chunk, GenStreamError):+ yield f"data: {json.dumps({'error': _friendly_gen_stream_error(chunk)})}\n\n"+ yield "data: [DONE]\n\n"+ returnyield f"data: {json.dumps({'content': chunk})}\n\n"if completed:yield "data: [DONE]\n\n"@@ -5437,6 +5491,7 @@ async def generate_stream(backend.reset_generation_state()logger.error(f"Error during generation: {e}", exc_info = True)yield f"data: {json.dumps({'error': _friendly_error(e)})}\n\n"+ yield "data: [DONE]\n\n"finally:await _stop_local_disconnect_cancel_watcher(disconnect_watcher)if not completed and not cancel_event.is_set():@@ -7060,6 +7115,13 @@ async def openai_chat_completions(chunk_text = await asyncio.to_thread(next, gen, _DONE)if chunk_text is _DONE:break+ if isinstance(chunk_text, GenStreamError):+ _msg = _friendly_gen_stream_error(chunk_text)+ api_monitor.fail(monitor_id, _msg)+ yield _openai_stream_error_sse(+ {"error": {"message": _msg, "type": "server_error"}}+ )+ returnif chunk_text:api_monitor.append_reply(monitor_id, chunk_text)yield _chat_content_chunk(@@ -7075,8 +7137,11 @@ async def openai_chat_completions(raiseexcept Exception as e:logger.error(f"Error during audio input streaming: {e}", exc_info = True)- api_monitor.fail(monitor_id, _friendly_error(e))- yield f"data: {json.dumps({'error': {'message': _friendly_error(e), 'type': 'server_error'}})}\n\n"+ _msg = _friendly_error(e)+ api_monitor.fail(monitor_id, _msg)+ yield _openai_stream_error_sse(+ {"error": {"message": _msg, "type": "server_error"}}+ )finally:await _stop_local_disconnect_cancel_watcher(disconnect_watcher)_tracker.__exit__(None, None, None)@@ -7093,7 +7158,15 @@ async def openai_chat_completions()else:try:- full_text = "".join(audio_input_generate())+ full_text = ""+ for chunk_text in audio_input_generate():+ if isinstance(chunk_text, GenStreamError):+ _msg = _friendly_gen_stream_error(chunk_text)+ api_monitor.fail(monitor_id, _msg)+ raise HTTPException(status_code = 500, detail = _msg)+ full_text += chunk_text+ except HTTPException:+ raiseexcept Exception as e:api_monitor.fail(monitor_id, _friendly_error(e))raise@@ -8637,19 +8710,33 @@ async def openai_chat_completions(# Classify capability flags from the loaded template._sf_model_info = backend.models.get(backend.active_model_name, {})_sf_tpl = (_sf_model_info.get("chat_template_info") or {}).get("template")- _sf_features = _detect_safetensors_features(backend, _sf_tpl)-- # GGUF parity: enable_thinking templates prefill an unclosed <think>; split into- # reasoning_content deltas so the UI renders the block for safetensors and MLX.- _sf_parse_think = bool(- _sf_features.get("supports_reasoning") or _sf_features.get("reasoning_always_on")+ # Named templates may expose native reasoning only in their ``tool_use``+ # branch. Use a truthy placeholder for Studio-managed tools, whose concrete+ # schemas are selected below, and the request schemas for client passthrough.+ _sf_server_tool_intent = bool(+ _effective_enable_tools(payload) or _explicit_studio_tool_loop_requested(payload))- # Prefilled-open only for prefill styles with thinking on; gpt-oss uses the normal mode.- _sf_reasoning_prefilled = _sf_reasoning_prefill_mode(- _sf_features,- payload.enable_thinking,- _sf_tpl,- reasoning_effort = payload.reasoning_effort,+ _sf_template_tools = payload.tools if payload.tool_choice != "none" else None+ if not _sf_template_tools and _sf_server_tool_intent:+ _sf_template_tools = ({},)++ def _sf_response_protocol(tools = None):+ features = _detect_safetensors_features(backend, _sf_tpl, tools = tools)+ parse_think = bool(+ features.get("supports_reasoning") or features.get("reasoning_always_on")+ )+ reasoning_prefilled = _sf_reasoning_prefill_mode(+ features,+ payload.enable_thinking,+ _sf_tpl,+ reasoning_effort = payload.reasoning_effort,+ )+ return features, parse_think, reasoning_prefilled++ # GGUF parity: split canonical <think> output into reasoning_content. The+ # selected template branch must match whether this request renders tools.+ _sf_features, _sf_parse_think, _sf_reasoning_prefilled = _sf_response_protocol(+ _sf_template_tools)def _new_sf_reasoning_extractor():@@ -8858,6 +8945,18 @@ async def openai_chat_completions(_sf_next_task = Noneif event is _sf_tool_sentinel:break+ if isinstance(event, GenStreamError):+ backend.reset_generation_state()+ _msg = _friendly_gen_stream_error(event)+ api_monitor.fail(monitor_id, _msg)+ yield _openai_stream_error_sse(+ {"error": {"message": _msg, "type": "server_error"}}+ )+ return+ if not isinstance(event, dict):+ raise RuntimeError(+ f"Invalid safetensors tool event: {type(event).__name__}"+ )if event["type"] == "heartbeat":# Tool-execution wrapper heartbeat -> SSE keepalive.@@ -8945,6 +9044,11 @@ async def openai_chat_completions(backend.reset_generation_state()api_monitor.finish(monitor_id, "cancelled")raise+ except GenStreamErrorRaised as exc:+ backend.reset_generation_state()+ _msg = _friendly_gen_stream_error(exc)+ api_monitor.fail(monitor_id, _msg)+ yield _openai_stream_error_sse({"error": {"message": _msg, "type": "server_error"}})except Exception:backend.reset_generation_state()# Generic wire message; full trace stays in the log (CWE-209:@@ -8994,6 +9098,15 @@ async def openai_chat_completions(for event in gen:if cancel_event.is_set():break+ if isinstance(event, GenStreamError):+ raise HTTPException(+ status_code = 500,+ detail = _friendly_gen_stream_error(event),+ )+ if not isinstance(event, dict):+ raise RuntimeError(+ f"Invalid safetensors tool event: {type(event).__name__}"+ )if event.get("type") == "content":full_text = _strip_tool_xml_for_display(event.get("text", ""),@@ -9034,6 +9147,15 @@ async def openai_chat_completions(backend.reset_generation_state()api_monitor.finish(monitor_id, "cancelled")raise+ except GenStreamErrorRaised as exc:+ backend.reset_generation_state()+ _msg = _friendly_gen_stream_error(exc)+ api_monitor.fail(monitor_id, _msg)+ raise HTTPException(status_code = 500, detail = _msg)+ except HTTPException as exc:+ backend.reset_generation_state()+ api_monitor.fail(monitor_id, str(exc.detail))+ raiseexcept Exception:backend.reset_generation_state()# CWE-209: generic detail; full trace in log.@@ -9120,6 +9242,12 @@ async def openai_chat_completions(else:gen_kwargs["tools"] = payload.tools+ # The potential tool context above is needed before server/client routing is+ # known. This standard path now has the exact schemas that will be rendered,+ # so resolve reasoning parsing again to keep empty registries, forced-tool+ # misses, and tool_choice="none" on the marker-free template branch.+ _, _sf_parse_think, _sf_reasoning_prefilled = _sf_response_protocol(gen_kwargs.get("tools"))+# Request-scoped usage/timings receptacle (filled at gen_done).stats_holder: dict = {}@@ -9200,6 +9328,14 @@ async def openai_chat_completions(_next_task = Noneif cumulative is _DONE:break+ if isinstance(cumulative, GenStreamError):+ backend.reset_generation_state()+ _msg = _friendly_gen_stream_error(cumulative)+ api_monitor.fail(monitor_id, _msg)+ yield _openai_stream_error_sse(+ {"error": {"message": _msg, "type": "server_error"}}+ )+ returnif await request.is_disconnected():cancel_event.set()backend.reset_generation_state()@@ -9349,6 +9485,11 @@ async def openai_chat_completions(try:full_text = ""for token in generate():+ if isinstance(token, GenStreamError):+ backend.reset_generation_state()+ _msg = _friendly_gen_stream_error(token)+ api_monitor.fail(monitor_id, _msg)+ raise HTTPException(status_code = 500, detail = _msg)full_text = token# Split prefilled <think> reasoning (GGUF parity); also covers MLX via@@ -9447,6 +9588,8 @@ async def openai_chat_completions(api_monitor.finish(monitor_id)return _model_json_response(response)+ except HTTPException:+ raiseexcept Exception as e:backend.reset_generation_state()logger.error(f"Error during OpenAI completion: {e}", exc_info = True)diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex 29fbb45158e..fa50cd84d6b 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -523,3 +523,169 @@ def test_mlx_generate_text_forwards_kwargs_into_template_helper(monkeypatch):assert render["kwargs"]["enable_thinking"] is Trueassert render["kwargs"]["reasoning_effort"] == "medium"assert render["kwargs"]["preserve_thinking"] is True+++def test_mlx_text_normalizes_native_reasoning_and_close_releases_lock(monkeypatch):+ _install_fake_mlx(monkeypatch)+ from core.inference.mlx_inference import MLXInferenceBackend++ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",+ lambda *_args, **_kwargs: "prompt",+ raising = True,+ )+ monkeypatch.setattr(+ "core.inference.chat_template_helpers.render_with_native_template_fallback",+ lambda formatted_prompt, **_kwargs: SimpleNamespace(+ prompt = formatted_prompt,+ reasoning_channel_markers = ("<|channel>thought\n", "<channel|>"),+ ),+ raising = True,+ )++ mlx_lm_pkg = types.ModuleType("mlx_lm")+ mlx_lm_sample = types.ModuleType("mlx_lm.sample_utils")+ mlx_lm_sample.make_sampler = lambda **_kw: object()+ mlx_lm_sample.make_logits_processors = lambda **_kw: None++ class _Resp:+ def __init__(self, text, tok):+ self.text = text+ self.token = tok++ def _stream_generate(_model, _tokenizer, **_kw):+ yield _Resp("<|channel>thought\n", 10)+ yield _Resp("r", 11)+ yield _Resp("<channel|>", 12)+ yield _Resp("a", 13)++ mlx_lm_pkg.stream_generate = _stream_generate+ monkeypatch.setitem(sys.modules, "mlx_lm", mlx_lm_pkg)+ monkeypatch.setitem(sys.modules, "mlx_lm.sample_utils", mlx_lm_sample)++ backend = MLXInferenceBackend()+ backend._model = object()+ backend._tokenizer = SimpleNamespace(all_special_tokens = [])+ backend._is_vlm = False++ assert list(+ backend.generate_chat_response(+ messages = [{"role": "user", "content": "ping"}],+ max_new_tokens = 4,+ )+ ) == ["<think>", "<think>r", "<think>r</think>", "<think>r</think>a"]++ gen = backend.generate_chat_response(+ messages = [{"role": "user", "content": "ping"}],+ max_new_tokens = 4,+ )+ assert next(gen) == "<think>"+ assert backend._generation_lock.locked()+ gen.close()+ assert not backend._generation_lock.locked()+++def test_mlx_text_native_metadata_preserves_prefilled_think_snapshots(monkeypatch):+ _install_fake_mlx(monkeypatch)+ from core.inference.mlx_inference import MLXInferenceBackend++ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",+ lambda *_args, **_kwargs: "prompt<think>\n",+ raising = True,+ )+ monkeypatch.setattr(+ "core.inference.chat_template_helpers.render_with_native_template_fallback",+ lambda formatted_prompt, **_kwargs: SimpleNamespace(+ prompt = formatted_prompt,+ reasoning_channel_markers = ("<|channel>thought", "<channel|>"),+ ),+ raising = True,+ )++ mlx_lm_pkg = types.ModuleType("mlx_lm")+ mlx_lm_sample = types.ModuleType("mlx_lm.sample_utils")+ mlx_lm_sample.make_sampler = lambda **_kw: object()+ mlx_lm_sample.make_logits_processors = lambda **_kw: None++ class _Resp:+ def __init__(self, text, tok):+ self.text = text+ self.token = tok++ def _stream_generate(_model, _tokenizer, **_kw):+ yield _Resp("reason", 10)+ yield _Resp("</think>", 11)+ yield _Resp("answer", 12)++ mlx_lm_pkg.stream_generate = _stream_generate+ monkeypatch.setitem(sys.modules, "mlx_lm", mlx_lm_pkg)+ monkeypatch.setitem(sys.modules, "mlx_lm.sample_utils", mlx_lm_sample)++ backend = MLXInferenceBackend()+ backend._model = object()+ backend._tokenizer = SimpleNamespace(all_special_tokens = [])+ backend._is_vlm = False++ snapshots = list(+ backend.generate_chat_response(+ messages = [{"role": "user", "content": "ping"}],+ max_new_tokens = 3,+ )+ )+ assert snapshots == [+ "<think>\n",+ "<think>\nreason",+ "<think>\nreason</think>",+ "<think>\nreason</think>answer",+ ]+ assert all(current.startswith(previous) for previous, current in zip(snapshots, snapshots[1:]))+++def test_mlx_vlm_normalizes_native_reasoning_channels(monkeypatch):+ _install_fake_mlx(monkeypatch)+ from core.inference.mlx_inference import MLXInferenceBackend++ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",+ lambda *_args, **_kwargs: "prompt",+ raising = True,+ )++ mlx_vlm_pkg = types.ModuleType("mlx_vlm")++ class _Resp:+ def __init__(self, text, tok):+ self.text = text+ self.token = tok++ def _stream_generate(_model, _processor, _prompt, _images, **_kw):+ yield _Resp("<|channel>thought\n", 10)+ yield _Resp("vision", 11)+ yield _Resp("<channel|>", 12)+ yield _Resp(" answer", 13)++ mlx_vlm_pkg.stream_generate = _stream_generate+ monkeypatch.setitem(sys.modules, "mlx_vlm", mlx_vlm_pkg)++ backend = MLXInferenceBackend()+ backend._model = SimpleNamespace(config = SimpleNamespace())+ backend._processor = SimpleNamespace(+ chat_template = "<|channel>thought\n...<channel|>",+ all_special_tokens = [],+ apply_chat_template = lambda *_args, **_kwargs: "prompt",+ )+ backend._is_vlm = True++ assert list(+ backend.generate_chat_response(+ messages = [{"role": "user", "content": "describe"}],+ image = object(),+ max_new_tokens = 4,+ )+ ) == [+ "<think>",+ "<think>vision",+ "<think>vision</think>",+ "<think>vision</think> answer",+ ]diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex 5300a485576..8725b28ac83 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -1054,7 +1054,7 @@ class TestChatCompletionRequestToolFields:monkeypatch.setattr(inference_route,"_detect_safetensors_features",- lambda backend, chat_template: {"supports_tools": True},+ lambda backend, chat_template, tools = None: {"supports_tools": True},)monitor = ApiMonitor(max_entries = 3)monkeypatch.setattr(inference_route, "api_monitor", monitor)@@ -6620,6 +6620,29 @@ class TestApiMonitorAudioInput:assert entry["reply"] == "hello world"assert monitor.active_count() == 0+ def failing_chunks():+ yield "partial"+ raise RuntimeError("generation failed")++ self._patch_audio_backend(monkeypatch, failing_chunks())+ error_monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inf_mod, "api_monitor", error_monitor)+ error_response = await openai_chat_completions(+ payload,+ request = request,+ current_subject = "test",+ )+ error_chunks = [+ chunk.decode() if isinstance(chunk, bytes) else chunk+ async for chunk in error_response.body_iterator+ ]++ assert '"type": "server_error"' in error_chunks[-1]+ assert error_chunks[-1].endswith("data: [DONE]\n\n")+ [error_entry] = error_monitor.snapshot()+ assert error_entry["status"] == "error"+ assert error_monitor.active_count() == 0+asyncio.run(_run())def test_non_gguf_tts_auto_route_records_monitor(self, monkeypatch):diff --git a/studio/backend/tests/test_safetensors_capability_advertise.py b/studio/backend/tests/test_safetensors_capability_advertise.pyindex 0ed670ac015..bd3d8d16b90 100644--- a/studio/backend/tests/test_safetensors_capability_advertise.py+++ b/studio/backend/tests/test_safetensors_capability_advertise.py@@ -417,6 +417,59 @@ def test_detect_safetensors_features_gemma_native_tool_call_keeps_tools_on():assert flags["supports_tools"] is True+def test_detect_safetensors_features_gemma_native_reasoning_is_parseable_not_prefilled():+ """Native Gemma channels are normalized to <think>, then split by the route."""+ from routes.inference import _detect_safetensors_features, _sf_reasoning_prefill_mode++ tpl_with_gemma_native = "{% if add_generation_prompt %}<|channel>thought\n<channel|>{% endif %}"+ backend = SimpleNamespace(+ active_model_name = "unsloth/gemma-4-E2B-it",+ models = {+ "unsloth/gemma-4-E2B-it": {+ "native_chat_template": tpl_with_gemma_native,+ "chat_template_info": {"template": "override has no native markers"},+ }+ },+ )+ flags = _detect_safetensors_features(backend, "override has no native markers")+ missing_arg_flags = _detect_safetensors_features(backend, None)++ assert flags["supports_reasoning"] is True+ assert flags["reasoning_always_on"] is True+ assert missing_arg_flags["supports_reasoning"] is True+ assert _sf_reasoning_prefill_mode(flags, None, tpl_with_gemma_native) is False+++def test_detect_safetensors_features_selects_native_reasoning_from_tool_template():+ """Request tools select a marker-bearing named template without affecting default chat."""+ from routes.inference import _detect_safetensors_features++ named_template = {+ "default": "plain default template",+ "tool_use": "{% if tools %}<|channel>thought\n<channel|>{% endif %}",+ }+ backend = SimpleNamespace(+ active_model_name = "custom/named-native-reasoning",+ models = {+ "custom/named-native-reasoning": {+ "native_chat_template": named_template,+ "chat_template_info": {"template": "{% if tools %}<tool_call>{% endif %}"},+ }+ },+ )++ default_flags = _detect_safetensors_features(backend, "plain override")+ tool_flags = _detect_safetensors_features(+ backend,+ "plain override",+ tools = [{"type": "function"}],+ )++ assert default_flags["supports_reasoning"] is False+ assert tool_flags["supports_reasoning"] is True+ assert tool_flags["reasoning_always_on"] is True++# Qwen3.5 family pin: the live GGUF + safetensors templates both wrap tool# calls as ``<tool_call>\n<function=name>...``. Faithful slice so the# classifier never silently regresses for this family.diff --git a/studio/backend/tests/test_safetensors_reasoning_stream.py b/studio/backend/tests/test_safetensors_reasoning_stream.pyindex 4e708139b7c..af5a05d266e 100644--- a/studio/backend/tests/test_safetensors_reasoning_stream.py+++ b/studio/backend/tests/test_safetensors_reasoning_stream.py@@ -215,3 +215,135 @@ def test_s6_reasoning_effort_none_disables_prefill_for_enable_thinking_effort():swallowed = _replay_sf_reasoning_stream(events, prefilled = True)assert swallowed["visible"] == ""assert swallowed["reasoning"] == "The capital of France is Paris."+++def test_native_reasoning_streamer_selected_and_errors_raise():+ import threading+ import pytest++ torch = pytest.importorskip("torch")+ inf = pytest.importorskip("core.inference.inference")++ class Batch(dict):+ def to(self, _device):+ return self++ class Tok:+ chat_template = "<|channel>thought\n...<channel|>"+ all_special_tokens = []+ eos_token_id = 1+ pad_token_id = None+ pieces = {10: "<|channel>thought\n", 11: "r", 12: "<channel|>", 13: "a"}++ def __call__(self, *_args, **_kwargs):+ return Batch({"input_ids": torch.zeros((1, 1), dtype = torch.long)})++ def decode(self, ids, **_kwargs):+ return "".join(self.pieces.get(int(token_id), "") for token_id in ids)++ class Model:+ device = "cpu"+ generation_config = type("Cfg", (), {"eos_token_id": 1})()+ config = generation_config++ def __init__(self, fail = False):+ self.fail = fail+ self.kwargs = None++ def generate(self, **kwargs):+ self.kwargs = kwargs+ streamer = kwargs["streamer"]+ streamer.put(torch.zeros((1, 1), dtype = torch.long))+ for token_id in [10, 11, 12, 13]:+ streamer.put(torch.tensor([token_id]))+ if self.fail:+ raise RuntimeError("boom")++ backend = inf.InferenceBackend.__new__(inf.InferenceBackend)+ backend.active_model_name = "gemma-test"+ backend._generation_lock = threading.Lock()+ backend.models = {"gemma-test": {"model": Model(), "tokenizer": Tok()}}++ assert list(backend.generate_stream("prompt", max_new_tokens = 4))[-1] == "<think>r</think>a"++ backend.models["gemma-test"]["model"] = Model(fail = True)++ with pytest.raises(inf._GenerationThreadError, match = "boom"):+ list(backend.generate_stream("prompt", max_new_tokens = 4))+++def test_text_only_vlm_fallback_resolves_native_markers_off():+ import threading+ import pytest++ torch = pytest.importorskip("torch")+ inf = pytest.importorskip("core.inference.inference")++ class Batch(dict):+ def to(self, _device):+ return self++ class Tokenizer:+ all_special_tokens = []+ eos_token_id = 1+ pad_token_id = None++ def __call__(self, *_args, **_kwargs):+ return Batch({"input_ids": torch.zeros((1, 1), dtype = torch.long)})++ class Processor:+ chat_template = "<|channel>thought\n...<channel|>"+ tokenizer = Tokenizer()++ class Model:+ device = "cpu"+ generation_config = type("Cfg", (), {"eos_token_id": 1})()+ config = generation_config++ def generate(self, **_kwargs):+ return None++ class EmptyStreamer:+ def __next__(self):+ raise StopIteration++ def end(self):+ return None++ captured = {}+ backend = inf.InferenceBackend.__new__(inf.InferenceBackend)+ backend.active_model_name = "vision-test"+ backend._generation_lock = threading.Lock()+ backend.models = {+ "vision-test": {+ "model": Model(),+ "processor": Processor(),+ "tokenizer": Processor(),+ }+ }+ backend.format_chat_prompt = lambda *_args, **_kwargs: "manual text-only prompt"++ def make_streamer(*_args, **kwargs):+ captured.update(kwargs)+ return EmptyStreamer()++ backend._make_text_streamer = make_streamer++ assert (+ list(+ backend._generate_vision_response(+ messages = [{"role": "user", "content": "hello"}],+ system_prompt = "",+ image = None,+ temperature = 0.7,+ top_p = 0.9,+ top_k = 40,+ min_p = 0.0,+ max_new_tokens = 1,+ repetition_penalty = 1.0,+ )+ )+ == []+ )+ assert captured["reasoning_channel_markers"] is None+ assert captured["reasoning_channel_markers_resolved"] is Truediff --git a/studio/backend/tests/test_sf_client_tools_passthrough.py b/studio/backend/tests/test_sf_client_tools_passthrough.pyindex 01905b712cd..f91eec98176 100644--- a/studio/backend/tests/test_sf_client_tools_passthrough.py+++ b/studio/backend/tests/test_sf_client_tools_passthrough.py@@ -177,6 +177,15 @@ def _sse_objects(chunks):# ── Non-streaming ─────────────────────────────────────────────────+def test_non_reasoning_backend_keeps_literal_think_tags(monkeypatch):+ backend = _ScriptedBackend(_fixed("show <think>example</think> tags"))+ response = _call(_request(stream = False), monkeypatch, backend, supports_tools = False)++ message = _json_body(response)["choices"][0]["message"]+ assert message["content"] == "show <think>example</think> tags"+ assert message["reasoning_content"] is None++def test_xml_healed_to_tool_calls_non_streaming(monkeypatch):backend = _ScriptedBackend(_fixed(_CALL_XML))payload = _request(tools = [LOOKUP_TOOL], stream = False)@@ -485,6 +494,52 @@ def test_streaming_no_tools_verbatim(monkeypatch):assert finishes == ["stop"]+def test_streaming_gen_stream_error_is_not_model_text(monkeypatch):+ from core.inference.orchestrator import GenStreamError++ class _ErrorAfterPartial(_ScriptedBackend):+ def __init__(self):+ super().__init__(_fixed())++ def generate_chat_response(self, **_kwargs):+ yield "<think>partial"+ yield GenStreamError("Error: /tmp/secret traceback")++ backend = _ErrorAfterPartial()+ payload = _request(stream = True)+ response = _call(payload, monkeypatch, backend, supports_tools = False)+ chunks = _collect_sse(response)+ objs = _sse_objects(chunks)++ deltas = [o.get("choices", [{}])[0].get("delta", {}) for o in objs if o.get("choices")]+ assert any("partial" in json.dumps(delta) for delta in deltas)+ assert not any("/tmp/secret" in json.dumps(delta) for delta in deltas)+ errors = [o["error"]["message"] for o in objs if "error" in o]+ assert errors == ["An internal error occurred."]+ assert any(+ "data: [DONE]" in (chunk.decode() if isinstance(chunk, bytes) else chunk)+ for chunk in chunks+ )+++def test_server_tool_streaming_invalid_event_is_error(monkeypatch):+ class _InvalidEventBackend(_ScriptedBackend):+ def __init__(self):+ super().__init__(_fixed())++ def generate_chat_completion_with_tools(self, **_kwargs):+ yield {"type": "content", "text": "partial"}+ yield "not-an-event"++ backend = _InvalidEventBackend()+ payload = _request(tools = [LOOKUP_TOOL], enable_tools = True, stream = True)+ response = _call(payload, monkeypatch, backend)+ objs = _sse_objects(_collect_sse(response))++ errors = [o["error"]["message"] for o in objs if "error" in o]+ assert errors == ["An internal error occurred."]++def test_streaming_repeated_snapshot_no_duplicate_call(monkeypatch):# Repeated then shrunk cumulative snapshots must not double-heal.backend = _ScriptedBackend(_fixed(_CALL_XML, _CALL_XML, _CALL_XML[:5], _CALL_XML))diff --git a/studio/backend/tests/test_think_prefill_reemit.py b/studio/backend/tests/test_think_prefill_reemit.pyindex 300ff927764..346399c3b23 100644--- a/studio/backend/tests/test_think_prefill_reemit.py+++ b/studio/backend/tests/test_think_prefill_reemit.py@@ -2,7 +2,7 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0"""-Unit tests for detect_think_prefill.+Unit tests for local reasoning-stream helpers.Reasoning templates (Qwen3.6-style) end the generation prompt with an open``<think>\\n`` so the model starts reasoning immediately. skip_prompt@@ -16,7 +16,13 @@ import sys_backend = os.path.join(os.path.dirname(__file__), "..")sys.path.insert(0, _backend)-from core.inference.chat_template_helpers import detect_think_prefill+from core.inference.chat_template_helpers import (+ ReasoningChannelNormalizer,+ detect_reasoning_channel_markers,+ detect_reasoning_channel_markers_from_model_info,+ detect_think_prefill,+ render_with_native_template_fallback,+)QWEN_PROMPT = "<|im_start|>user\nHi!<|im_end|>\n<|im_start|>assistant\n"@@ -87,3 +93,170 @@ def test_guard_emits_when_think_not_special():def test_guard_default_and_empty_keep_emitting():assert detect_think_prefill(QWEN_PROMPT + "<think>\n", None) == "<think>\n"assert detect_think_prefill(QWEN_PROMPT + "<think>\n", []) == "<think>\n"+++def test_gemma_channel_detection_uses_active_template_not_token_metadata():+ class TemplateTokenizer:+ chat_template = {"default": "...<|channel>thought\\n{{ eoc_token }}"}++ class NamedTemplateTokenizer:+ chat_template = {+ "default": "plain assistant template",+ "tool_use": "...<|channel>thought\\n{{ eoc_token }}",+ }++ class TokenMetadataOnly:+ chat_template = None+ soc_token = "<|channel>"+ eoc_token = "<channel|>"++ class NamedTemplateProcessor:+ chat_template = {+ "default": "plain processor default",+ "tool_use": "<|channel>thought\nprocessor tool template<channel|>",+ }+ tokenizer = TokenMetadataOnly()++ def apply_chat_template(self, *_args, **_kwargs):+ raise NotImplementedError++ expected = ("<|channel>thought", "<channel|>")+ assert detect_reasoning_channel_markers(TemplateTokenizer()) == expected+ assert detect_reasoning_channel_markers(NamedTemplateTokenizer()) is None+ assert (+ detect_reasoning_channel_markers(+ NamedTemplateTokenizer(), tools = [{"function": {"name": "web_search"}}]+ )+ == expected+ )+ assert detect_reasoning_channel_markers(NamedTemplateTokenizer(), tools = []) is None+ assert (+ detect_reasoning_channel_markers(+ NamedTemplateProcessor(), tools = [{"function": {"name": "web_search"}}]+ )+ is None+ )+ assert detect_reasoning_channel_markers(TokenMetadataOnly()) is None+++def test_gemma_channel_detection_tries_no_argument_getter_fallback():+ class FallbackTokenizer:+ chat_template = "plain fallback template"++ def get_chat_template(self, **kwargs):+ if kwargs:+ raise ValueError("tools are not supported")+ return "...<|channel>thought\n<channel|>"++ assert detect_reasoning_channel_markers(+ FallbackTokenizer(), tools = [{"function": {"name": "web_search"}}]+ ) == ("<|channel>thought", "<channel|>")+++def test_native_template_fallback_returns_selected_reasoning_metadata():+ from types import SimpleNamespace++ messages = [{"role": "user", "content": "hi"}]+ tools = [{"type": "function", "function": {"name": "web_search"}}]++ def render(tokenizer, msgs, *, tools, **_kw):+ body = "".join(message["content"] for message in msgs)+ suffix = "|TOOLS" if tools else ""+ return body + suffix if tokenizer.chat_template == "NATIVE <|channel>thought\n" else body++ result = render_with_native_template_fallback(+ formatted_prompt = "hi",+ tokenizer = SimpleNamespace(chat_template = "OVERRIDE"),+ model_info = {+ "native_chat_template": "NATIVE <|channel>thought\n",+ "tokenizer": SimpleNamespace(chat_template = "OVERRIDE"),+ },+ active_model_name = "gemma-test",+ messages = messages,+ tools = tools,+ apply_fn = render,+ return_metadata = True,+ )++ assert result.prompt == "hi|TOOLS"+ assert result.reasoning_channel_markers == ("<|channel>thought", "<channel|>")+++def test_cached_native_template_metadata_recovers_reasoning_markers_without_tools():+ from types import SimpleNamespace++ model_info = {"chat_template_info": {"template": "native <|channel>thought\n<channel|>"}}++ assert detect_reasoning_channel_markers_from_model_info(+ SimpleNamespace(chat_template = "override has no native markers"),+ model_info,+ tools = None,+ ) == ("<|channel>thought", "<channel|>")+ result = render_with_native_template_fallback(+ formatted_prompt = "prompt from override",+ tokenizer = SimpleNamespace(chat_template = "override has no native markers"),+ model_info = model_info,+ active_model_name = "gemma-test",+ messages = [{"role": "user", "content": "hi"}],+ tools = None,+ return_metadata = True,+ )+ assert result.prompt == "prompt from override"+ assert result.reasoning_channel_markers == ("<|channel>thought", "<channel|>")+++def test_cached_native_markers_do_not_describe_live_tool_template():+ from types import SimpleNamespace++ tools = [{"type": "function", "function": {"name": "web_search"}}]++ class LiveTokenizer:+ chat_template = "live tool template without native markers"++ def render(_tokenizer, _messages, *, tools, **_kwargs):+ return "prompt with tools" if tools else "prompt without tools"++ result = render_with_native_template_fallback(+ formatted_prompt = "prompt with tools",+ tokenizer = LiveTokenizer(),+ model_info = {+ "chat_template_info": {"template": "native <|channel>thought\n<channel|>"},+ "tokenizer": SimpleNamespace(),+ },+ active_model_name = "gemma-test",+ messages = [{"role": "user", "content": "hi"}],+ tools = tools,+ apply_fn = render,+ return_metadata = True,+ )++ assert result.prompt == "prompt with tools"+ assert result.reasoning_channel_markers is None+++def test_gemma_channel_normalization_is_prefix_monotonic_and_preserves_tools():+ parser = ReasoningChannelNormalizer("<|channel>thought", "<channel|>")+ output = ""+ snapshots = []+ for chunk in (+ "<|chan",+ "nel>thought",+ "\nReason",+ "<chan",+ "nel|><|tool_call>web_search<tool_call|>",+ ):+ delta = parser.feed(chunk)+ if delta:+ output += delta+ snapshots.append(output)++ assert snapshots == [+ "<think>",+ "<think>Reason",+ "<think>Reason</think><|tool_call>web_search<tool_call|>",+ ]+ assert snapshots[1].startswith(snapshots[0])+ compact = ReasoningChannelNormalizer("<|channel>thought", "<channel|>")+ assert compact.feed("<|channel>thought<channel|>answer") + compact.finish() == (+ "<think></think>answer"+ )