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.

studio: normalize ollama reasoning deltas (#9504)

Maheswar Kumar0c7ff0c40fde
diff --git a/studio/backend/core/inference/sse_control_frames.py b/studio/backend/core/inference/sse_control_frames.py
index 73f81c0ec48..5bdeaf367f3 100644
--- a/studio/backend/core/inference/sse_control_frames.py
+++ b/studio/backend/core/inference/sse_control_frames.py
@@ -17,8 +17,9 @@ has no legitimate reason to emit any of them, and a verbatim relay makes its cop
indistinguishable from ours at the client: a forged card can claim a tool the
user trusts ran and returned something harmless, carrying
``provenance: {"source": "local"}``, when nothing ran at all. So strip the
-control vocabulary out of everything that arrives from a provider, and leave the
-rest of the chunk exactly as it was.
+control vocabulary out of everything that arrives from a provider. The
+``delta.reasoning`` alias Ollama and newer vLLM send is renamed to the canonical
+``reasoning_content``, streamed deltas only. The rest of the chunk stays as it was.
"""
from __future__ import annotations
@@ -51,6 +52,39 @@ _CONTROL_KEYS = ("_toolEvent", "_toolStatus", "_diffusionFrame", "_reasoningDura
_SUBSTANTIVE_KEYS = ("choices", "usage", "error")
+def _normalize_reasoning_deltas(payload: dict[str, Any]) -> bool:
+ choices = payload.get("choices")
+ if not isinstance(choices, list):
+ return False
+ changed = False
+ for choice in choices:
+ if not isinstance(choice, dict):
+ continue
+ delta = choice.get("delta")
+ if not isinstance(delta, dict):
+ continue
+ reasoning = delta.get("reasoning")
+ if not isinstance(reasoning, str) or not reasoning:
+ # An empty alias says nothing, and rewriting it would cost a re-encode.
+ continue
+ details = delta.get("reasoning_details")
+ if isinstance(details, list) and any(
+ isinstance(part, dict) and isinstance(part.get("text"), str) and part["text"]
+ for part in details
+ ):
+ # OpenRouter repeats the thought in reasoning_details and the client
+ # concatenates both; details carrying no text are not a second copy.
+ continue
+ canonical = delta.get("reasoning_content")
+ if canonical is not None and (not isinstance(canonical, str) or canonical.strip()):
+ # A canonical value the provider set wins, unless it is blank.
+ continue
+ delta["reasoning_content"] = reasoning
+ delta.pop("reasoning", None)
+ changed = True
+ return changed
+
+
def sanitize_provider_sse_line(line: str) -> str | None:
"""Return ``line`` fit to relay, or ``None`` if nothing of it should be.
@@ -71,9 +105,10 @@ def sanitize_provider_sse_line(line: str) -> str | None:
if not isinstance(payload, dict):
return line
+ normalized_reasoning = _normalize_reasoning_deltas(payload)
forged_type = isinstance(payload.get("type"), str) and payload["type"] in _CONTROL_TYPES
forged_keys = [key for key in _CONTROL_KEYS if key in payload]
- if not forged_type and not forged_keys:
+ if not normalized_reasoning and not forged_type and not forged_keys:
# The overwhelmingly common case: relay the provider's own bytes rather
# than paying a re-encode to reproduce them.
return line
diff --git a/studio/backend/tests/test_provider_control_frame_spoofing.py b/studio/backend/tests/test_provider_control_frame_spoofing.py
index b210d051eec..507c52adfcf 100644
--- a/studio/backend/tests/test_provider_control_frame_spoofing.py
+++ b/studio/backend/tests/test_provider_control_frame_spoofing.py
@@ -71,6 +71,90 @@ def test_an_ordinary_chunk_is_relayed_byte_for_byte():
assert sanitize_provider_sse_line(line) is line
+def test_ollama_reasoning_is_normalized_across_every_choice():
+ line = "data: " + json.dumps(
+ {
+ "choices": [
+ {"index": 0, "delta": {"content": "", "reasoning": "First thought."}},
+ {
+ "index": 1,
+ "delta": {"reasoning": "Second thought.", "reasoning_content": None},
+ },
+ {
+ "index": 2,
+ "delta": {
+ "reasoning": "Provider alternate.",
+ "reasoning_content": "Canonical thought.",
+ },
+ },
+ {"index": 3, "delta": {"reasoning": {"text": "structured"}}},
+ {"index": 4, "delta": None},
+ "malformed",
+ ]
+ }
+ )
+
+ cleaned = json.loads(sanitize_provider_sse_line(line)[len("data: ") :])
+ first, second, both, structured, malformed_delta, malformed_choice = cleaned["choices"]
+ assert first["delta"] == {"content": "", "reasoning_content": "First thought."}
+ assert second["delta"] == {"reasoning_content": "Second thought."}
+ assert both["delta"] == {
+ "reasoning": "Provider alternate.",
+ "reasoning_content": "Canonical thought.",
+ }
+ assert structured["delta"] == {"reasoning": {"text": "structured"}}
+ assert malformed_delta["delta"] is None
+ assert malformed_choice == "malformed"
+
+
+def test_a_whitespace_canonical_does_not_shadow_the_real_thought():
+ line = "data: " + json.dumps(
+ {"choices": [{"delta": {"reasoning": "Thought.", "reasoning_content": " "}}]}
+ )
+
+ cleaned = json.loads(sanitize_provider_sse_line(line)[len("data: ") :])
+ assert cleaned["choices"][0]["delta"] == {"reasoning_content": "Thought."}
+
+
+def test_details_carrying_no_text_are_not_a_second_copy():
+ """Encrypted or metadata-only details render nothing, so the alias is all there is."""
+ line = "data: " + json.dumps(
+ {
+ "choices": [
+ {
+ "delta": {
+ "reasoning": "Thought.",
+ "reasoning_details": [{"type": "reasoning.encrypted", "data": "zz"}],
+ }
+ }
+ ]
+ }
+ )
+
+ cleaned = json.loads(sanitize_provider_sse_line(line)[len("data: ") :])
+ assert cleaned["choices"][0]["delta"]["reasoning_content"] == "Thought."
+
+
+ "delta",
+ [
+ # OpenRouter sends both and the client concatenates them, so renaming doubles it.
+ {
+ "reasoning": "Thought.",
+ "reasoning_details": [{"type": "reasoning.text", "text": "Thought."}],
+ },
+ # An empty alias carries nothing, so it keeps the byte-for-byte relay.
+ {"content": "tok", "reasoning": ""},
+ # A structured canonical field is the provider's own, not ours to drop.
+ {"reasoning": "Thought.", "reasoning_content": {"summary": "kept"}},
+ ],
+)
+def test_an_alias_that_must_not_be_rewritten_is_relayed_untouched(delta):
+ line = "data: " + json.dumps({"choices": [{"delta": delta}]})
+
+ assert sanitize_provider_sse_line(line) is line
+
+
@pytest.mark.parametrize(
"line",
[
@@ -242,6 +326,30 @@ def test_the_relay_still_forwards_everything_legitimate(monkeypatch):
assert any('"usage"' in line for line in lines)
+def test_the_plain_relay_normalizes_ollama_reasoning(monkeypatch):
+ body = (
+ 'data: {"choices": [{"index": 0, "delta": '
+ '{"role": "assistant", "content": "", "reasoning": "Thinking"}}]}\n\n'
+ 'data: {"choices": [{"index": 0, "delta": '
+ '{"content": "", "reasoning": " more"}}]}\n\n'
+ 'data: {"choices": [{"index": 0, "delta": '
+ '{"content": "answer"}, "finish_reason": "stop"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+
+ lines = _stream(monkeypatch, body)
+ deltas = [
+ choice["delta"]
+ for line in lines
+ if line.startswith("data: ") and line[6:] != "[DONE]"
+ for choice in json.loads(line[6:]).get("choices", [])
+ ]
+
+ assert [delta.get("reasoning_content") for delta in deltas[:2]] == ["Thinking", " more"]
+ assert all("reasoning" not in delta for delta in deltas)
+ assert deltas[-1]["content"] == "answer"
+
+
# ── The loop must not sanitize a transport that already did ──────────
diff --git a/studio/backend/tests/test_provider_reasoning_normalization.py b/studio/backend/tests/test_provider_reasoning_normalization.py
new file mode 100644
index 00000000000..84440593e43
--- /dev/null
+++ b/studio/backend/tests/test_provider_reasoning_normalization.py
@@ -0,0 +1,141 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Streamed thinking has to reach its consumers whichever field a provider uses.
+
+``test_provider_control_frame_spoofing.py`` pins the rename in isolation; these drive
+whole streams through the real relay, which is where #8838 failed. Ollama sends thinking
+as ``delta.reasoning`` while Deep Research counts only non-empty ``delta.content`` /
+``delta.reasoning_content`` as output (``core/research_runs.py``), so a reasoning-only
+prefix spent the first-output budget. The chat client, the second consumer, concatenates
+``reasoning_content`` with the text in ``reasoning_details`` (``chat-adapter.ts``), so a
+provider sending both must not have the alias renamed into a second copy.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+
+import httpx
+import pytest
+
+from core.inference import external_provider as ep_mod
+from core.inference.external_provider import ExternalProviderClient
+
+
+THOUGHT = ["I need ", "to think ", "about this."]
+ANSWER = ["The ", "answer."]
+
+
+def _chunk(delta: dict) -> str:
+ return "data: " + json.dumps({"choices": [{"index": 0, "delta": delta}]}) + "\n\n"
+
+
+def _ollama() -> str:
+ return "".join(_chunk({"content": "", "reasoning": t}) for t in THOUGHT)
+
+
+def _deepseek() -> str:
+ return "".join(_chunk({"reasoning_content": t}) for t in THOUGHT)
+
+
+def _openrouter() -> str:
+ return "".join(
+ _chunk({"reasoning": t, "reasoning_details": [{"type": "reasoning.text", "text": t}]})
+ for t in THOUGHT
+ )
+
+
+def _openrouter_encrypted() -> str:
+ return "".join(
+ _chunk(
+ {"reasoning": t, "reasoning_details": [{"type": "reasoning.encrypted", "data": "zz"}]}
+ )
+ for t in THOUGHT
+ )
+
+
+SHAPES = {
+ "ollama": _ollama,
+ "deepseek": _deepseek,
+ "openrouter": _openrouter,
+ "openrouter_encrypted": _openrouter_encrypted,
+}
+
+
+def _relay(body: str) -> list[str]:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, content = body, headers = {"content-type": "text/event-stream"})
+
+ ep_mod._http_client = httpx.AsyncClient(transport = httpx.MockTransport(handler))
+ client = ExternalProviderClient(
+ provider_type = "ollama", base_url = "http://endpoint.invalid/v1", api_key = ""
+ )
+
+ async def run() -> list[str]:
+ return [
+ line
+ async for line in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "ping"}], model = "m"
+ )
+ ]
+
+ return asyncio.new_event_loop().run_until_complete(run())
+
+
+def _consume(lines: list[str]) -> dict:
+ """What Deep Research counts, and what the chat client would render."""
+ seen = {"research_reasoning": "", "research_report": "", "rendered": "", "output": False}
+ for line in lines:
+ if not line.startswith("data: ") or line[6:].strip() in ("", "[DONE]"):
+ continue
+ for choice in json.loads(line[6:]).get("choices", []):
+ delta = choice.get("delta") or {}
+ thought = delta.get("reasoning_content")
+ text = delta.get("content")
+ if isinstance(thought, str) and thought:
+ seen["research_reasoning"] += thought
+ seen["output"] = True
+ if isinstance(text, str) and text:
+ seen["research_report"] += text
+ seen["output"] = True
+ details = delta.get("reasoning_details")
+ seen["rendered"] += thought if isinstance(thought, str) else ""
+ if isinstance(details, list):
+ seen["rendered"] += "".join(
+ p.get("text") if isinstance(p, dict) and isinstance(p.get("text"), str) else ""
+ for p in details
+ )
+ return seen
+
+
[email protected]("shape", sorted(SHAPES))
+def test_thinking_is_rendered_exactly_once(shape):
+ seen = _consume(_relay(SHAPES[shape]() + "".join(_chunk({"content": c}) for c in ANSWER)))
+
+ # doubling here is the thinking block printing every thought twice
+ assert seen["rendered"] == "".join(THOUGHT)
+ assert seen["research_report"] == "".join(ANSWER)
+
+
[email protected]("shape", ["ollama", "deepseek", "openrouter_encrypted"])
+def test_a_reasoning_only_prefix_is_already_output(shape):
+ """#8838: the first-output budget must be disarmed before any content arrives."""
+ seen = _consume(_relay(SHAPES[shape]()))
+
+ assert seen["research_reasoning"] == "".join(THOUGHT)
+ assert seen["output"] is True
+ assert seen["research_report"] == ""
+
+
+def test_openrouter_text_details_stay_the_only_copy():
+ """Renaming the alias here would double the thinking block, so it is left alone.
+
+ Deep Research still cannot see reasoning that only arrives as
+ ``reasoning_details``; that is the same on main and is its own fix.
+ """
+ seen = _consume(_relay(_openrouter()))
+
+ assert seen["rendered"] == "".join(THOUGHT)
+ assert seen["research_reasoning"] == ""