Skip to content

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.

fix(studio): derive reasoning-channel state from the rendered prompt (#8410)

Long Yixingbf6799c4a918
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.py
index 7bc7b13bc87..b001024bdb2 100644
--- a/studio/backend/core/inference/chat_template_helpers.py
+++ b/studio/backend/core/inference/chat_template_helpers.py
@@ -1983,18 +1983,32 @@ class ReasoningChannelNormalizer:
available to downstream parsers.
"""
- def __init__(self, opening_marker: str, closing_marker: str):
+ def __init__(
+ self,
+ opening_marker: str,
+ closing_marker: str,
+ *,
+ in_reasoning: bool = False,
+ ):
self._opening_marker = opening_marker
self._closing_marker = closing_marker
self._buffer = ""
- self._in_reasoning = False
+ self._in_reasoning = in_reasoning
self._reasoning_done = False
+ # Only a generated opener carries the protocol newline; from the prompt it is
+ # already consumed, so a streamed newline is content.
self._skip_opening_newline = False
+ # A prompt-supplied opener never reaches the stream, so <think> is owed to the
+ # first delta carrying text.
+ self._pending_open = in_reasoning
def feed(self, text: str) -> str:
"""Consume a raw text delta and return the stable canonical delta."""
self._buffer += text or ""
output: list[str] = []
+ if self._pending_open and self._buffer:
+ output.append(_THINK_OPEN)
+ self._pending_open = False
while self._buffer:
if self._reasoning_done:
output.append(self._buffer)
@@ -2031,7 +2045,10 @@ class ReasoningChannelNormalizer:
"""Flush a naturally completed stream and close an open think block."""
output = self.drain()
if self._in_reasoning:
- output += _THINK_CLOSE
+ # Nothing generated: no block at all, rather than a close with no opener.
+ if not self._pending_open:
+ output += _THINK_CLOSE
+ self._pending_open = False
self._in_reasoning = False
self._reasoning_done = True
return output
@@ -2043,12 +2060,46 @@ class ReasoningChannelNormalizer:
return output
+def prompt_opens_reasoning_channel(
+ prompt: Optional[str],
+ markers: Optional[tuple[str, str]],
+ continued: bool = False,
+) -> bool:
+ """Whether a rendered prompt *ends* by opening the native reasoning channel.
+
+ Gemma-style templates end a post-tool generation prompt with the opener, so
+ generation starts inside reasoning and emits only the closing marker.
+
+ Only the tail decides -- the rule ``strip_open_reasoning_prefill`` already uses
+ for ``<think>``. Position alone cannot tell a template's own prefill from
+ replayed history, which keeps this markup through
+ ``neutralize_control_markup_in_messages``, so an opener with content after it
+ reads as closed; otherwise history could hide a plain answer in a think block.
+ The cost is that a spliced continuation resuming inside a channel also reads as
+ closed, leaving its reasoning visible as it was before.
+
+ ``continued`` means this render resumed a trailing assistant turn, so the prompt
+ ends on client text whose tail proves nothing. It is the render's own state, not
+ the request flag, which outlives the continuation: the next tool-loop pass keeps
+ the flag but renders an ordinary post-tool prompt that must still be read.
+ """
+ if continued or not prompt or not markers:
+ return False
+ opening_marker = markers[0]
+ opened_at = prompt.rfind(opening_marker)
+ if opened_at < 0:
+ return False
+ return not prompt[opened_at + len(opening_marker) :].strip()
+
+
def normalize_reasoning_snapshots(
stream,
tokenizer = None,
cancel_event = None,
markers: Optional[tuple[str, str]] = None,
tools = None,
+ prompt: Optional[str] = None,
+ continued: bool = False,
):
"""Normalize a prefix-monotonic cumulative text stream when supported."""
markers = markers or detect_reasoning_channel_markers(tokenizer, tools = tools)
@@ -2056,7 +2107,10 @@ def normalize_reasoning_snapshots(
yield from stream
return
- normalizer = ReasoningChannelNormalizer(*markers)
+ normalizer = ReasoningChannelNormalizer(
+ *markers,
+ in_reasoning = prompt_opens_reasoning_channel(prompt, markers, continued),
+ )
raw_output = ""
normalized_output = ""
for snapshot in stream:
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 4495b318bc4..46137fd1bbc 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -39,6 +39,8 @@ from core.inference.chat_template_helpers import (
detect_think_prefill,
neutralize_control_markup_in_messages,
neutralize_tts_prompt_text,
+ prompt_opens_reasoning_channel,
+ trailing_assistant_text,
)
from core.inference.presence_penalty import _make_presence_penalty_processor
from io import StringIO
@@ -206,11 +208,12 @@ class ReasoningTextIteratorStreamer(TextIteratorStreamer):
skip_prompt: bool = True,
timeout: float = 0.2,
cancel_event = None,
+ in_reasoning: bool = False,
**decode_kwargs,
):
decode_kwargs["skip_special_tokens"] = False
super().__init__(tokenizer, skip_prompt = skip_prompt, timeout = timeout, **decode_kwargs)
- self._normalizer = ReasoningChannelNormalizer(*markers)
+ self._normalizer = ReasoningChannelNormalizer(*markers, in_reasoning = in_reasoning)
self._cancel_event = cancel_event
self._aborted = False
@@ -1260,6 +1263,7 @@ class InferenceBackend:
presence_penalty = presence_penalty,
reasoning_channel_markers = reasoning_channel_markers,
reasoning_channel_markers_resolved = reasoning_channel_markers_resolved,
+ continued = bool(continue_final_message and trailing_assistant_text(template_messages)),
)
def _generate_vision_response(
@@ -1393,6 +1397,8 @@ class InferenceBackend:
if image
else None,
reasoning_channel_markers_resolved = True,
+ prompt = prompt_text,
+ continued = bool(continue_partial),
skip_prompt = True,
timeout = 0.2,
cancel_event = cancel_event,
@@ -1741,6 +1747,8 @@ class InferenceBackend:
protocol_source = None,
reasoning_channel_markers = None,
reasoning_channel_markers_resolved: bool = False,
+ prompt: Optional[str] = None,
+ continued: bool = False,
skip_prompt: bool = True,
timeout: float = 0.2,
cancel_event = None,
@@ -1776,6 +1784,7 @@ class InferenceBackend:
skip_prompt = skip_prompt,
timeout = timeout,
cancel_event = cancel_event,
+ in_reasoning = prompt_opens_reasoning_channel(prompt, markers, continued),
)
return TextIteratorStreamer(
tokenizer,
@@ -1828,6 +1837,7 @@ class InferenceBackend:
presence_penalty: float = 0.0,
reasoning_channel_markers = None,
reasoning_channel_markers_resolved: bool = False,
+ continued: bool = False,
) -> Generator[str, None, None]:
"""Generate a streaming text response (text models only).
@@ -1868,6 +1878,8 @@ class InferenceBackend:
protocol_source = model_info.get("tokenizer"),
reasoning_channel_markers = reasoning_channel_markers,
reasoning_channel_markers_resolved = reasoning_channel_markers_resolved,
+ prompt = prompt,
+ continued = continued,
skip_prompt = True,
timeout = 0.2,
cancel_event = cancel_event,
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 61c2f9dc5e6..8607e8142ef 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -18,6 +18,7 @@ from core.inference.chat_template_helpers import (
markup_for_tokenizer,
neutralize_control_markup_in_messages,
normalize_reasoning_snapshots,
+ prompt_opens_reasoning_channel,
strip_open_reasoning_prefill,
trailing_assistant_text,
)
@@ -1561,6 +1562,9 @@ class MLXInferenceBackend:
)
prompt = render_result.prompt
reasoning_channel_markers = render_result.reasoning_channel_markers
+ # Not the request flag: a later tool-loop pass keeps it but renders an
+ # ordinary post-tool prompt.
+ _resumed_partial = bool(continue_final_message and trailing_assistant_text(messages))
# An open <think> prefilled by the template lives in the prompt, not
# the generated tokens; re-emit it so the frontend renders the block.
@@ -1593,7 +1597,12 @@ class MLXInferenceBackend:
preserve_native_channels = reasoning_channel_markers is not None
token_ids = []
normalizer = (
- ReasoningChannelNormalizer(*reasoning_channel_markers)
+ ReasoningChannelNormalizer(
+ *reasoning_channel_markers,
+ in_reasoning = prompt_opens_reasoning_channel(
+ prompt, reasoning_channel_markers, _resumed_partial
+ ),
+ )
if reasoning_channel_markers is not None
else None
)
@@ -1876,7 +1885,12 @@ class MLXInferenceBackend:
)
yield from normalize_reasoning_snapshots(
- _stream_vlm_snapshots(), chat_target, cancel_event, tools = tools
+ _stream_vlm_snapshots(),
+ chat_target,
+ cancel_event,
+ tools = tools,
+ prompt = prompt,
+ continued = bool(continue_final_message and trailing_assistant_text(messages)),
)
def generate_audio_input_response(
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index b698060d2ec..b1d52a69c48 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -948,6 +948,92 @@ def test_mlx_text_normalizes_native_reasoning_and_close_releases_lock(monkeypatc
assert not backend._generation_lock.locked()
+def test_mlx_text_post_tool_prompt_opens_reasoning_channel(monkeypatch):
+ """Gemma-style templates open the thought channel in the POST-TOOL prompt.
+
+ Generation then emits only the closing marker, so a parser assuming it starts
+ outside reasoning would leak the post-tool reasoning and a raw ``<channel|>``
+ into the visible answer.
+ """
+ _install_fake_mlx(monkeypatch)
+ from core.inference.mlx_inference import MLXInferenceBackend
+
+ post_tool_prompt = (
+ "<|turn>model\n<|tool_response>response:web_search{}<tool_response|><|channel>thought\n"
+ )
+ # Give the pre-fallback render a non-opening tail, so state read from the wrong
+ # prompt fails here.
+ monkeypatch.setattr(
+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",
+ lambda *_args, **_kwargs: "<|turn>model\n",
+ raising = True,
+ )
+ monkeypatch.setattr(
+ "core.inference.chat_template_helpers.render_with_native_template_fallback",
+ lambda formatted_prompt, **_kwargs: SimpleNamespace(
+ prompt = post_tool_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("The search says 18C.", 10)
+ yield _Resp("<channel|>", 11)
+ yield _Resp("It is 18C.", 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": "weather?"}],
+ max_new_tokens = 3,
+ )
+ )
+ assert snapshots[-1] == "<think>The search says 18C.</think>It is 18C."
+ assert "<channel|>" not in snapshots[-1]
+ assert all(later.startswith(earlier) for earlier, later in zip(snapshots, snapshots[1:]))
+
+ # The flag survives into the next pass, but the tool result is the trailing turn,
+ # so nothing was resumed and the prompt must still be read.
+ resumed_then_tool = [
+ {"role": "user", "content": "weather?"},
+ {
+ "role": "assistant",
+ "content": "partial",
+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "web_search"}}],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "18C"},
+ ]
+ assert (
+ list(
+ backend.generate_chat_response(
+ messages = resumed_then_tool,
+ max_new_tokens = 3,
+ continue_final_message = True,
+ )
+ )[-1]
+ == "<think>The search says 18C.</think>It is 18C."
+ )
+
+
def test_mlx_text_native_metadata_preserves_prefilled_think_snapshots(monkeypatch):
_install_fake_mlx(monkeypatch)
from core.inference.mlx_inference import MLXInferenceBackend
@@ -1054,6 +1140,53 @@ def test_mlx_vlm_normalizes_native_reasoning_channels(monkeypatch):
]
+def test_mlx_vlm_post_tool_prompt_opens_reasoning_channel(monkeypatch):
+ """The VLM snapshot path must derive channel state from its rendered prompt too."""
+ _install_fake_mlx(monkeypatch)
+ from core.inference.mlx_inference import MLXInferenceBackend
+
+ post_tool_prompt = "<|tool_response>response:web_search{}<tool_response|><|channel>thought\n"
+ monkeypatch.setattr(
+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",
+ lambda *_args, **_kwargs: post_tool_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("looking at it", 10)
+ yield _Resp("<channel|>", 11)
+ yield _Resp("A cat.", 12)
+
+ 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: post_tool_prompt,
+ )
+ backend._is_vlm = True
+
+ snapshots = list(
+ backend.generate_chat_response(
+ messages = [{"role": "user", "content": "describe"}],
+ image = object(),
+ max_new_tokens = 3,
+ )
+ )
+ assert snapshots[-1] == "<think>looking at it</think>A cat."
+ assert "<channel|>" not in snapshots[-1]
+
+
class _FakeLRUPromptCache:
def __init__(
self,
diff --git a/studio/backend/tests/test_safetensors_reasoning_stream.py b/studio/backend/tests/test_safetensors_reasoning_stream.py
index af5a05d266e..d73b9ce88ae 100644
--- a/studio/backend/tests/test_safetensors_reasoning_stream.py
+++ b/studio/backend/tests/test_safetensors_reasoning_stream.py
@@ -272,6 +272,53 @@ def test_native_reasoning_streamer_selected_and_errors_raise():
list(backend.generate_stream("prompt", max_new_tokens = 4))
+def test_native_reasoning_streamer_starts_inside_prompt_opened_channel():
+ """A post-tool prompt opens the channel, so generation emits only its close."""
+ 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 = {11: "reasoned", 12: "<channel|>", 13: "answer"}
+
+ 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 generate(self, **kwargs):
+ streamer = kwargs["streamer"]
+ streamer.put(torch.zeros((1, 1), dtype = torch.long))
+ for token_id in [11, 12, 13]:
+ streamer.put(torch.tensor([token_id]))
+
+ 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()}}
+
+ post_tool_prompt = "<|tool_response>response:web_search{}<tool_response|><|channel>thought\n"
+ assert list(backend.generate_stream(post_tool_prompt, max_new_tokens = 4))[-1] == (
+ "<think>reasoned</think>answer"
+ )
+
+
def test_text_only_vlm_fallback_resolves_native_markers_off():
import threading
import pytest
@@ -347,3 +394,5 @@ def test_text_only_vlm_fallback_resolves_native_markers_off():
)
assert captured["reasoning_channel_markers"] is None
assert captured["reasoning_channel_markers_resolved"] is True
+ # No markers on this branch, so this pins forwarding only.
+ assert captured["prompt"] == "manual text-only prompt"
diff --git a/studio/backend/tests/test_think_prefill_reemit.py b/studio/backend/tests/test_think_prefill_reemit.py
index 346399c3b23..99ef1878927 100644
--- a/studio/backend/tests/test_think_prefill_reemit.py
+++ b/studio/backend/tests/test_think_prefill_reemit.py
@@ -21,7 +21,10 @@ from core.inference.chat_template_helpers import (
detect_reasoning_channel_markers,
detect_reasoning_channel_markers_from_model_info,
detect_think_prefill,
+ normalize_reasoning_snapshots,
+ prompt_opens_reasoning_channel,
render_with_native_template_fallback,
+ trailing_assistant_text,
)
@@ -260,3 +263,168 @@ def test_gemma_channel_normalization_is_prefix_monotonic_and_preserves_tools():
assert compact.feed("<|channel>thought<channel|>answer") + compact.finish() == (
"<think></think>answer"
)
+
+
+GEMMA_MARKERS = ("<|channel>thought", "<channel|>")
+GEMMA_TOOL_TAIL = '<|tool_response>response:web_search{value:<|"|>18C<|"|>}<tool_response|>'
+GEMMA_POST_TOOL_PROMPT = "<|turn>model\n" + GEMMA_TOOL_TAIL + "<|channel>thought\n"
+
+
+def test_prompt_opens_reasoning_channel_tracks_generation_prompt_state():
+ """Open only when nothing but whitespace follows the prompt's last opener."""
+ assert prompt_opens_reasoning_channel(GEMMA_POST_TOOL_PROMPT, GEMMA_MARKERS)
+ # History closes its own channel before the post-tool opener.
+ assert prompt_opens_reasoning_channel(
+ "<|turn>model\n<|channel>thought\nearlier\n<channel|>" + GEMMA_POST_TOOL_PROMPT,
+ GEMMA_MARKERS,
+ )
+ # Ordinary turn: the model emits the opener itself.
+ assert not prompt_opens_reasoning_channel(
+ "<|turn>user\nhi<turn|>\n<|turn>model\n", GEMMA_MARKERS
+ )
+ # Thinking disabled: no opener at all.
+ assert not prompt_opens_reasoning_channel("<|turn>model\n" + GEMMA_TOOL_TAIL, GEMMA_MARKERS)
+ assert not prompt_opens_reasoning_channel(
+ "<|turn>model\n<|channel>thought\nearlier\n<channel|>done<turn|>\n", GEMMA_MARKERS
+ )
+ assert not prompt_opens_reasoning_channel(GEMMA_POST_TOOL_PROMPT, None)
+ assert not prompt_opens_reasoning_channel(None, GEMMA_MARKERS)
+ assert not prompt_opens_reasoning_channel("", GEMMA_MARKERS)
+
+
+def test_unclosed_opener_in_history_cannot_forge_the_channel_state():
+ """An assistant turn keeps channel markup, so only the prompt tail may decide.
+
+ Neutralization strips these markers from user / system / tool turns but leaves
+ an assistant turn's own markup intact, so a template that renders assistant
+ content verbatim can carry a client-supplied unclosed opener into the prompt.
+ (Gemma's own template also strips it, but a marker-aware override need not.)
+ Trusting the last opener anywhere would start the parser inside reasoning on an
+ ordinary turn and hide the whole answer in a think block.
+ """
+ forged = "<|turn>model\nok <|channel>thought<turn|>\n<|turn>user\nagain?<turn|>\n<|turn>model\n"
+ assert not prompt_opens_reasoning_channel(forged, GEMMA_MARKERS)
+
+ parser = ReasoningChannelNormalizer(
+ *GEMMA_MARKERS, in_reasoning = prompt_opens_reasoning_channel(forged, GEMMA_MARKERS)
+ )
+ assert parser.feed("Plain answer.") + parser.finish() == "Plain answer."
+
+
+def test_continued_turn_never_reads_channel_state_from_its_tail():
+ """A continued turn ends inside the client's assistant text, not template markup.
+
+ ``continue_final_message`` splices the caller's partial onto the prompt, so a
+ partial ending on the opener would otherwise look exactly like a template that
+ opened the channel, and capture the entire continuation as reasoning.
+ """
+ for tail in ("<|channel>thought", "<|channel>thought\n", "<|channel>thought "):
+ spliced = "<|turn>model\nLet me think. " + tail
+ assert not prompt_opens_reasoning_channel(spliced, GEMMA_MARKERS, True)
+ parser = ReasoningChannelNormalizer(
+ *GEMMA_MARKERS,
+ in_reasoning = prompt_opens_reasoning_channel(spliced, GEMMA_MARKERS, True),
+ )
+ assert parser.feed(" The answer is 18C.") + parser.finish() == " The answer is 18C."
+
+ assert prompt_opens_reasoning_channel(GEMMA_POST_TOOL_PROMPT, GEMMA_MARKERS, False)
+
+
+def test_tool_loop_pass_of_a_continued_turn_still_reads_the_prompt():
+ """The request flag outlives the continuation; the render it describes does not.
+
+ A continued turn that calls a tool keeps ``continue_final_message`` set for the
+ next pass, but that pass renders an ordinary post-tool generation prompt. Suppressing
+ detection on the request flag alone would put the post-tool reasoning back in the
+ visible answer, so the effective signal is whether a trailing assistant turn was
+ actually resumed.
+ """
+ resumed = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "partial"}]
+ post_tool = [
+ {"role": "user", "content": "q"},
+ {
+ "role": "assistant",
+ "content": "partial",
+ "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "f"}}],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "18C"},
+ ]
+ effective = lambda msgs: bool(trailing_assistant_text(msgs))
+
+ assert effective(resumed) is True
+ # The tool result is the trailing turn now, so nothing was resumed.
+ assert effective(post_tool) is False
+ assert prompt_opens_reasoning_channel(
+ GEMMA_POST_TOOL_PROMPT, GEMMA_MARKERS, effective(post_tool)
+ )
+
+
+def test_prompt_opened_channel_normalizes_post_tool_reasoning():
+ """Post-tool generation emits only the closing marker; it is still reasoning."""
+ parser = ReasoningChannelNormalizer(*GEMMA_MARKERS, in_reasoning = True)
+ output = ""
+ snapshots = []
+ # Split across chunks, as a token stream splits it.
+ for chunk in ("The search ", "returned 18C.", "<chan", "nel|>", "It is 18C in Paris."):
+ delta = parser.feed(chunk)
+ if delta:
+ output += delta
+ snapshots.append(output)
+ output += parser.finish()
+
+ assert output == "<think>The search returned 18C.</think>It is 18C in Paris."
+ assert "<channel|>" not in output
+ assert all(later.startswith(earlier) for earlier, later in zip(snapshots, snapshots[1:]))
+
+ # Streaming X from a prompt-opened channel must match generating the opener plus X:
+ # a streamed leading newline is content, unlike the protocol newline after an opener.
+ for streamed, expected in (
+ ("reasoned<channel|>answer", "<think>reasoned</think>answer"),
+ ("\nreasoned<channel|>answer", "<think>\nreasoned</think>answer"),
+ ):
+ generated = ReasoningChannelNormalizer(*GEMMA_MARKERS)
+ prefilled = ReasoningChannelNormalizer(*GEMMA_MARKERS, in_reasoning = True)
+ assert (
+ generated.feed("<|channel>thought\n" + streamed) + generated.finish()
+ == prefilled.feed(streamed) + prefilled.finish()
+ == expected
+ )
+
+
+def test_prompt_opened_channel_without_generated_text_emits_no_think_block():
+ """A cancelled or empty post-tool turn must not emit an orphan </think>."""
+ empty = ReasoningChannelNormalizer(*GEMMA_MARKERS, in_reasoning = True)
+ assert empty.feed("") == ""
+ assert empty.finish() == ""
+
+ cancelled = ReasoningChannelNormalizer(*GEMMA_MARKERS, in_reasoning = True)
+ # Hold back a partial closing marker, so drain() has real buffered text.
+ assert cancelled.feed("partial reasoning<chan") == "<think>partial reasoning"
+ assert cancelled.drain() == "<chan"
+
+
+def test_normalize_reasoning_snapshots_derives_state_from_prompt():
+ def _stream(pieces):
+ cumulative = ""
+ for piece in pieces:
+ cumulative += piece
+ yield cumulative
+
+ post_tool = list(
+ normalize_reasoning_snapshots(
+ _stream(["reasoning", "<channel|>", "answer"]),
+ markers = GEMMA_MARKERS,
+ prompt = GEMMA_POST_TOOL_PROMPT,
+ )
+ )
+ assert post_tool[-1] == "<think>reasoning</think>answer"
+
+ # Without a prompt-opened channel the model supplies both markers as before.
+ first_turn = list(
+ normalize_reasoning_snapshots(
+ _stream(["<|channel>thought\n", "reasoning", "<channel|>", "answer"]),
+ markers = GEMMA_MARKERS,
+ prompt = "<|turn>model\n",
+ )
+ )
+ assert first_turn[-1] == "<think>reasoning</think>answer"