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: preserve local reasoning across chat turns (#8366)

oobaboogaaf53029c1401
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 50a6b67f8ba..e73b441d7d8 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -2240,8 +2240,16 @@ class InferenceBackend:
for msg in messages:
role = msg.get("role", "")
content = content_to_text(msg.get("content", ""))
+ reasoning_content = msg.get("reasoning_content")
+ has_reasoning_content = (
+ role == "assistant"
+ and isinstance(reasoning_content, str)
+ and bool(reasoning_content.strip())
+ )
- if role in ["system", "user", "assistant"] and content.strip():
+ if role in ["system", "user", "assistant"] and (
+ content.strip() or has_reasoning_content
+ ):
if role == last_role:
logger.debug(f"Skipping consecutive {role} message to maintain alternation")
continue
@@ -2252,8 +2260,11 @@ class InferenceBackend:
if clean_content:
chat_messages.append({"role": role, "content": clean_content})
last_role = role
- elif role == "assistant" and content.strip():
- chat_messages.append({"role": role, "content": content})
+ elif role == "assistant":
+ assistant_message = {"role": role, "content": content}
+ if has_reasoning_content:
+ assistant_message["reasoning_content"] = reasoning_content
+ chat_messages.append(assistant_message)
last_role = role
elif role == "system":
continue
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 2910fa38f4b..2395216a89b 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1019,6 +1019,13 @@ class ChatMessage(BaseModel):
content: Optional[Union[str, list[ContentPart]]] = Field(
None, description = "Message content (string or multimodal parts)"
)
+ reasoning_content: Optional[str] = Field(
+ None,
+ description = (
+ "Assistant reasoning from an earlier turn, replayed to local chat templates "
+ "that consume the OpenAI-compatible reasoning_content field."
+ ),
+ )
tool_call_id: Optional[str] = Field(
None,
description = "OpenAI tool-result messages: id of the tool call this result belongs to.",
@@ -1040,6 +1047,14 @@ class ChatMessage(BaseModel):
),
)
+ @field_validator("reasoning_content", mode = "before")
+ @classmethod
+ def _ignore_non_string_reasoning(cls, value):
+ # This field used to be ignored as an unknown key. Some compatible
+ # gateways send structured reasoning, so declaring the string form must
+ # not turn those previously accepted requests into validation errors.
+ return value if isinstance(value, str) else None
+
@model_validator(mode = "after")
def _validate_role_shape(self) -> "ChatMessage":
if self.tool_calls is not None and self.role != "assistant":
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 5ff81cc050e..495ff1be5b9 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -562,6 +562,17 @@ def _estimate_message_tokens(msg: dict) -> int:
return 1
+def _estimate_messages_tokens(messages: list) -> int:
+ """Conservatively estimate a complete message list.
+
+ Templates disagree about when historical ``reasoning_content`` renders,
+ and arbitrary GGUFs can carry custom templates. Counting the serialized
+ field avoids a retry that still exceeds context. The overflow recovery path
+ clips large reasoning traces before it evicts conversation turns.
+ """
+ return sum(_estimate_message_tokens(msg) for msg in messages)
+
+
def _truncate_middle_messages(messages: list, keep_ratio: float):
"""Drop whole turn-groups from the middle of an OpenAI message list.
@@ -595,7 +606,8 @@ def _truncate_middle_messages(messages: list, keep_ratio: float):
if len(groups) <= 1 + protected_tail:
return messages, 0
- total_est = sum(_estimate_message_tokens(m) for m in messages)
+ estimates = {id(msg): _estimate_message_tokens(msg) for msg in messages}
+ total_est = sum(estimates[id(msg)] for msg in messages)
target_est = int(total_est * keep_ratio)
anchor = groups[0]
@@ -609,7 +621,7 @@ def _truncate_middle_messages(messages: list, keep_ratio: float):
while kept_middle and current_est > target_est:
victim = kept_middle.pop(0)
dropped += len(victim)
- current_est -= sum(_estimate_message_tokens(m) for m in victim)
+ current_est -= sum(estimates[id(msg)] for msg in victim)
if dropped == 0:
return messages, 0
@@ -627,6 +639,26 @@ _CLIP_MARKER = "\n[... truncated by context_overflow=truncate_middle ...]\n"
_CLIP_KEEP_CHARS = (1500, 400)
+def _clip_reasoning_contents(messages: list, keep: int = _CLIP_KEEP_CHARS[-1]) -> int:
+ """Clip oversized assistant reasoning before sizing an overflow retry.
+
+ Reasoning can live in the protected anchor or tail where group eviction
+ cannot reach it. It is also the least useful history to preserve after the
+ server has already reported an overflow, so shrink it before dropping whole
+ conversation turns.
+ """
+ clipped = 0
+ for msg in messages:
+ if msg.get("role") != "assistant":
+ continue
+ reasoning = msg.get("reasoning_content")
+ if not isinstance(reasoning, str) or len(reasoning) <= 2 * keep + len(_CLIP_MARKER):
+ continue
+ msg["reasoning_content"] = reasoning[:keep] + _CLIP_MARKER + reasoning[-keep:]
+ clipped += 1
+ return clipped
+
+
def _clip_long_contents(messages: list, target_est: int) -> int:
"""Clip oversized string contents middle-out until ``target_est`` is met.
@@ -644,7 +676,7 @@ def _clip_long_contents(messages: list, target_est: int) -> int:
clipped = 0
for keep in _CLIP_KEEP_CHARS:
for msg in _candidates():
- if sum(_estimate_message_tokens(m) for m in messages) <= target_est:
+ if _estimate_messages_tokens(messages) <= target_est:
return clipped
content = msg.get("content")
if not isinstance(content, str) or len(content) <= 2 * keep + len(_CLIP_MARKER):
@@ -660,10 +692,21 @@ def _apply_overflow_truncation(body: dict, err_text: str) -> bool:
to the generation headroom. Returns False when nothing could shrink."""
counts = _parse_overflow_counts(err_text)
messages = body.get("messages") or []
- total_est = sum(_estimate_message_tokens(m) for m in messages)
+ pre_clip_est = _estimate_messages_tokens(messages)
+ clipped = _clip_reasoning_contents(messages)
+ total_est = _estimate_messages_tokens(messages)
if counts:
n_prompt, n_ctx = counts
- keep_ratio = min(0.95, (_OVERFLOW_PROMPT_TARGET_FRACTION * n_ctx) / max(1, n_prompt))
+ prompt_target = _OVERFLOW_PROMPT_TARGET_FRACTION * n_ctx
+ if clipped:
+ # The server counted the body before the retry-only clip. Rescale
+ # using this estimator's pre/post ratio so the removed trace is not
+ # charged again by middle eviction.
+ n_prompt = n_prompt * total_est / max(1, pre_clip_est)
+ if clipped and n_prompt <= prompt_target:
+ keep_ratio = 1.0
+ else:
+ keep_ratio = min(0.95, prompt_target / max(1.0, n_prompt))
else:
n_ctx = None
keep_ratio = 0.6 # no counts in the error; cut conservatively
@@ -673,9 +716,8 @@ def _apply_overflow_truncation(body: dict, err_text: str) -> bool:
new_messages, dropped = _truncate_middle_messages(messages, keep_ratio)
if dropped:
body["messages"] = new_messages
- clipped = 0
- if sum(_estimate_message_tokens(m) for m in body.get("messages") or []) > target_est:
- clipped = _clip_long_contents(body.get("messages") or [], target_est)
+ if _estimate_messages_tokens(body.get("messages") or []) > target_est:
+ clipped += _clip_long_contents(body.get("messages") or [], target_est)
if not dropped and not clipped:
return False
if n_ctx:
@@ -9580,7 +9622,8 @@ def _extract_content_parts(messages: list) -> tuple[str, list[dict], "Optional[s
Returns:
system_prompt: System message text (empty string if none).
- chat_messages: Non-system messages with content flattened to strings.
+ chat_messages: Non-system messages with content flattened to strings and
+ assistant reasoning_content preserved.
image_base64: Base64 of the *first* image found, or ``None``.
"""
system_parts: list[str] = []
@@ -9598,9 +9641,10 @@ def _extract_content_parts(messages: list) -> tuple[str, list[dict], "Optional[s
continue
# ── User / assistant messages ─────────────────────────
+ combined_text: Optional[str] = None
if isinstance(msg.content, str):
# Plain string content — pass through
- chat_messages.append({"role": msg.role, "content": msg.content})
+ combined_text = msg.content
elif isinstance(msg.content, list):
# Multimodal content parts
text_parts: list[str] = []
@@ -9615,7 +9659,17 @@ def _extract_content_parts(messages: list) -> tuple[str, list[dict], "Optional[s
else:
logger.warning(f"Remote image URLs not yet supported: {url[:80]}...")
combined_text = "\n".join(text_parts) if text_parts else ""
- chat_messages.append({"role": msg.role, "content": combined_text})
+ elif msg.role == "assistant" and msg.reasoning_content:
+ # A reasoning-only turn has no visible content, but still needs a
+ # message for templates that consume reasoning_content.
+ combined_text = ""
+
+ if combined_text is None:
+ continue
+ chat_message = {"role": msg.role, "content": combined_text}
+ if msg.role == "assistant" and msg.reasoning_content:
+ chat_message["reasoning_content"] = msg.reasoning_content
+ chat_messages.append(chat_message)
return "\n\n".join(p for p in system_parts if p), chat_messages, first_image_b64
@@ -18642,16 +18696,32 @@ async def _anthropic_passthrough_non_streaming(
# =====================================================================
+def _normalize_local_assistant_message(message: dict) -> Optional[dict]:
+ """Enforce the local backend's assistant-message wire contract.
+
+ Bare assistant messages are Stop-button sentinels and must disappear.
+ A reasoning-only completed turn is real history, but llama.cpp checks for a
+ ``content`` or ``tool_calls`` key before reading ``reasoning_content``. Give
+ that turn an empty content key without mutating the caller's dictionary.
+ """
+ if message.get("role") != "assistant":
+ return message
+ if message.get("content") or message.get("tool_calls"):
+ return message
+ if message.get("reasoning_content"):
+ if message.get("content") == "":
+ return message
+ return {**message, "content": ""}
+ return None
+
+
def _drop_empty_assistant_sentinels(messages: list[dict]) -> list[dict]:
- """Drop bare ``{"role":"assistant"}`` Stop-button sentinels; passthrough backends reject them."""
+ """Drop Stop-button sentinels and normalize reasoning-only turns."""
out: list[dict] = []
- for m in messages:
- if m.get("role") == "assistant":
- has_content = bool(m.get("content"))
- has_tool_calls = bool(m.get("tool_calls"))
- if not has_content and not has_tool_calls:
- continue
- out.append(m)
+ for message in messages:
+ normalized = _normalize_local_assistant_message(message)
+ if normalized is not None:
+ out.append(normalized)
return out
@@ -18701,6 +18771,57 @@ _LOCAL_SERVER_BUILTIN_TOOL_NAMES = frozenset(
)
+def _merge_stranded_local_assistant_turns(messages: list[tuple[dict, bool]]) -> list[dict]:
+ """Fold scrubbed provider-tool fragments into their visible answer.
+
+ Removing a provider-synthetic call and its tool result can expose adjacent
+ assistant messages that were one logical response. Strict local templates
+ reject that role sequence. A small state machine carries a stranded fragment
+ through any number of synthetic rounds, preserving text-part lists and
+ reasoning oldest-first, until the next assistant message completes it.
+ """
+ out: list[dict] = []
+ pending: Optional[dict] = None
+
+ for message, message_is_stranded in messages:
+ if pending is None:
+ if message_is_stranded:
+ pending = message
+ else:
+ out.append(message)
+ continue
+
+ if message.get("role") != "assistant":
+ out.append(pending)
+ pending = None
+ out.append(message)
+ continue
+
+ merged = dict(message)
+ old_content = pending.get("content")
+ new_content = merged.get("content")
+ if old_content or new_content:
+ merged["content"] = _merge_user_content(old_content, new_content)
+
+ old_reasoning = pending.get("reasoning_content")
+ new_reasoning = merged.get("reasoning_content")
+ reasoning_parts = [
+ value for value in (old_reasoning, new_reasoning) if isinstance(value, str) and value
+ ]
+ if reasoning_parts:
+ merged["reasoning_content"] = "\n\n".join(reasoning_parts)
+
+ if message_is_stranded:
+ pending = merged
+ else:
+ out.append(merged)
+ pending = None
+
+ if pending is not None:
+ out.append(pending)
+ return out
+
+
def _strip_provider_synthetic_tool_history(messages: list[dict]) -> list[dict]:
"""Drop synthetic provider-side tool_calls + matching role=tool replies on
the local-backend (llama-server / GGUF) dispatch path.
@@ -18716,10 +18837,10 @@ def _strip_provider_synthetic_tool_history(messages: list[dict]) -> list[dict]:
sees an orphan tool_call_id.
"""
dropped_ids: set[str] = set()
- sanitized_assistant: list[dict] = []
+ sanitized_assistant: list[tuple[dict, bool]] = []
for m in messages:
if m.get("role") != "assistant":
- sanitized_assistant.append(m)
+ sanitized_assistant.append((m, False))
continue
tool_calls = m.get("tool_calls")
if not isinstance(tool_calls, list) or not tool_calls:
@@ -18731,7 +18852,7 @@ def _strip_provider_synthetic_tool_history(messages: list[dict]) -> list[dict]:
# dropped); round-22 added it, which made this leak possible.
if "extra_content" in m:
m = {k: v for k, v in m.items() if k != "extra_content"}
- sanitized_assistant.append(m)
+ sanitized_assistant.append((m, False))
continue
cleaned: list[dict] = []
for tc in tool_calls:
@@ -18777,22 +18898,26 @@ def _strip_provider_synthetic_tool_history(messages: list[dict]) -> list[dict]:
m_clean["tool_calls"] = cleaned
else:
m_clean.pop("tool_calls", None)
- if not m_clean.get("content") and not m_clean.get("tool_calls"):
+ is_stranded = bool(m.get("tool_calls")) and not cleaned
+ if (
+ not m_clean.get("content")
+ and not m_clean.get("reasoning_content")
+ and not m_clean.get("tool_calls")
+ ):
continue # assistant turn now empty, drop
- sanitized_assistant.append(m_clean)
+ sanitized_assistant.append((m_clean, is_stranded))
- if not dropped_ids:
- return sanitized_assistant
- out: list[dict] = []
- for m in sanitized_assistant:
+ out: list[tuple[dict, bool]] = []
+ for m, is_stranded in sanitized_assistant:
if (
m.get("role") == "tool"
and isinstance(m.get("tool_call_id"), str)
and m["tool_call_id"] in dropped_ids
):
continue
- out.append(m)
- return out
+ out.append((m, is_stranded))
+ merged = _merge_stranded_local_assistant_turns(out)
+ return _drop_empty_assistant_sentinels(merged)
def _splice_image_into_last_user(messages: list[dict], image_part: dict) -> None:
diff --git a/studio/backend/tests/test_chat_template_continuation.py b/studio/backend/tests/test_chat_template_continuation.py
index dc617669d64..c8e7ad85546 100644
--- a/studio/backend/tests/test_chat_template_continuation.py
+++ b/studio/backend/tests/test_chat_template_continuation.py
@@ -526,6 +526,47 @@ def test_the_manual_formatters_resume_instead_of_opening_a_new_turn(format_type,
)
+def test_native_fallback_preserves_assistant_reasoning_content():
+ InferenceBackend = _inference_backend()
+ seen = {}
+
+ class _Tokenizer:
+ chat_template = "template"
+
+ def apply_chat_template(self, messages, **_kwargs):
+ seen["messages"] = messages
+ return "rendered"
+
+ backend = InferenceBackend.__new__(InferenceBackend)
+ backend.active_model_name = "m"
+ backend.models = {
+ "m": {
+ "tokenizer": _Tokenizer(),
+ "chat_template_info": {"has_template": False},
+ }
+ }
+
+ assert (
+ backend.format_chat_prompt(
+ [
+ {"role": "user", "content": "What is the answer?"},
+ {
+ "role": "assistant",
+ "content": "",
+ "reasoning_content": "The answer is forty-two.",
+ },
+ {"role": "user", "content": "Explain why."},
+ ]
+ )
+ == "rendered"
+ )
+ assert seen["messages"][1] == {
+ "role": "assistant",
+ "content": "",
+ "reasoning_content": "The answer is forty-two.",
+ }
+
+
def test_a_text_part_partial_merges_rather_than_doubling_the_turn():
"""The merge follows the same rule as the prompt boundary.
diff --git a/studio/backend/tests/test_context_overflow_truncation.py b/studio/backend/tests/test_context_overflow_truncation.py
index 4f4c2409341..58bf8b4290d 100644
--- a/studio/backend/tests/test_context_overflow_truncation.py
+++ b/studio/backend/tests/test_context_overflow_truncation.py
@@ -275,3 +275,35 @@ def test_v1_models_exposes_real_context_window(monkeypatch):
# The REAL (post /props readback) window, not the requested one.
assert entry["context_length"] == 67584
assert entry["max_context_length"] == 262144
+
+
+def _conversation_with_big_reasoning(trace_chars: int = 40000) -> list[dict]:
+ messages = [{"role": "system", "content": "sys"}]
+ for index in range(8):
+ messages.append({"role": "user", "content": f"question {index} " + "u" * 200})
+ messages.append({"role": "assistant", "content": f"answer {index} " + "a" * 200})
+ messages[-1]["reasoning_content"] = "t" * trace_chars
+ messages.append({"role": "user", "content": "final question"})
+ return messages
+
+
+def test_reasoning_clip_shrinks_a_protected_turn():
+ messages = _conversation_with_big_reasoning()
+ before = routes_mod._estimate_messages_tokens(messages)
+
+ assert routes_mod._clip_reasoning_contents(messages) == 1
+ assert _CLIP_MARKER in messages[-2]["reasoning_content"]
+ assert routes_mod._estimate_messages_tokens(messages) < before / 5
+
+
+def test_reasoning_clip_alone_prevents_middle_eviction():
+ body = {"messages": _conversation_with_big_reasoning()}
+ before = len(body["messages"])
+ error = '{"n_prompt_tokens":12000,"n_ctx":8192}'
+
+ assert _apply_overflow_truncation(body, error) is True
+ assert len(body["messages"]) == before
+ assert _CLIP_MARKER in body["messages"][-2]["reasoning_content"]
+ assert body["max_tokens"] == max(
+ 1024, int(8192 * (1.0 - routes_mod._OVERFLOW_PROMPT_TARGET_FRACTION))
+ )
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 0d4692c63a4..9ac15f61b8e 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -74,6 +74,7 @@ from routes.inference import (
_SameTaskStreamingResponse,
_OPENAI_COMPAT_STREAM_STALL_TIMEOUT_ENV,
_set_or_prepend_system_message,
+ _strip_provider_synthetic_tool_history,
openai_completions,
openai_embeddings,
openai_chat_completions,
@@ -1864,6 +1865,160 @@ class TestDropEmptyAssistantSentinels:
for m in out:
assert m.get("content"), m
+ def test_local_message_builders_preserve_assistant_reasoning(self):
+ req = ChatCompletionRequest(
+ model = "default",
+ messages = [
+ {"role": "user", "content": "hi"},
+ {
+ "role": "assistant",
+ "content": "hello back",
+ "reasoning_content": "Answer the greeting briefly.",
+ },
+ {"role": "user", "content": "why is quantum mechanics random?"},
+ ],
+ )
+
+ assert req.messages[1].reasoning_content == "Answer the greeting briefly."
+ passthrough = _openai_messages_for_passthrough(req)
+ gguf, _ = _openai_messages_for_gguf_chat(req, is_vision = False)
+ _, standard_local, _ = _extract_content_parts(req.messages)
+ assert passthrough[1]["reasoning_content"] == "Answer the greeting briefly."
+ assert gguf[1]["reasoning_content"] == "Answer the greeting briefly."
+ assert standard_local[1]["reasoning_content"] == "Answer the greeting briefly."
+
+ def test_standard_local_builder_preserves_reasoning_only_assistant_turn(self):
+ req = ChatCompletionRequest(
+ model = "default",
+ messages = [
+ {"role": "user", "content": "What is the answer?"},
+ {
+ "role": "assistant",
+ "content": None,
+ "reasoning_content": "The answer is forty-two.",
+ },
+ {"role": "user", "content": "Explain why."},
+ ],
+ )
+
+ _, messages, _ = _extract_content_parts(req.messages)
+
+ assert messages == [
+ {"role": "user", "content": "What is the answer?"},
+ {
+ "role": "assistant",
+ "content": "",
+ "reasoning_content": "The answer is forty-two.",
+ },
+ {"role": "user", "content": "Explain why."},
+ ]
+
+ def test_reasoning_only_assistant_turn_is_not_treated_as_a_stop_sentinel(self):
+ req = ChatCompletionRequest(
+ model = "default",
+ messages = [
+ {"role": "user", "content": "hi"},
+ {
+ "role": "assistant",
+ "content": "",
+ "reasoning_content": "The response stopped before its final answer.",
+ },
+ {"role": "user", "content": "continue"},
+ ],
+ )
+
+ passthrough = _openai_messages_for_passthrough(req)
+ gguf, _ = _openai_messages_for_gguf_chat(req, is_vision = False)
+ assert [message["role"] for message in passthrough] == ["user", "assistant", "user"]
+ assert [message["role"] for message in gguf] == ["user", "assistant", "user"]
+ assert passthrough[1]["content"] == ""
+ assert gguf[1]["content"] == ""
+
+ def test_reasoning_only_dict_gains_llama_cpp_content_key(self):
+ messages = _drop_empty_assistant_sentinels(
+ [{"role": "assistant", "reasoning_content": "A completed answer."}]
+ )
+ assert messages == [
+ {
+ "role": "assistant",
+ "content": "",
+ "reasoning_content": "A completed answer.",
+ }
+ ]
+
+ def test_chained_synthetic_tool_fragments_collapse_into_visible_answer(self):
+ def _synthetic_call(call_id: str) -> dict:
+ return {
+ "id": call_id,
+ "type": "function",
+ "function": {
+ "name": "web_search",
+ "arguments": '{"_server_tool": true}',
+ },
+ }
+
+ messages = [
+ {"role": "user", "content": "Find it."},
+ {
+ "role": "assistant",
+ "content": [{"type": "text", "text": "Searching first."}],
+ "reasoning_content": "first trace",
+ "tool_calls": [_synthetic_call("call-1")],
+ },
+ {"role": "tool", "tool_call_id": "call-1", "content": "first result"},
+ {
+ "role": "assistant",
+ "reasoning_content": "second trace",
+ "tool_calls": [_synthetic_call("call-2")],
+ },
+ {"role": "tool", "tool_call_id": "call-2", "content": "second result"},
+ {
+ "role": "assistant",
+ "content": "Here is the answer.",
+ "reasoning_content": "final trace",
+ },
+ {"role": "user", "content": "Thanks."},
+ ]
+
+ out = _strip_provider_synthetic_tool_history(messages)
+
+ assert [message["role"] for message in out] == ["user", "assistant", "user"]
+ assert out[1]["content"] == [
+ {"type": "text", "text": "Searching first."},
+ {"type": "text", "text": "Here is the answer."},
+ ]
+ assert out[1]["reasoning_content"] == "first trace\n\nsecond trace\n\nfinal trace"
+
+ def test_synthetic_reasoning_fragment_before_user_stays_valid(self):
+ messages = [
+ {"role": "user", "content": "Find it."},
+ {
+ "role": "assistant",
+ "reasoning_content": "I should search.",
+ "tool_calls": [
+ {
+ "id": "call-1",
+ "type": "function",
+ "function": {
+ "name": "web_search",
+ "arguments": '{"_server_tool": true}',
+ },
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call-1", "content": "result"},
+ {"role": "user", "content": "Try another query."},
+ ]
+
+ out = _strip_provider_synthetic_tool_history(messages)
+
+ assert [message["role"] for message in out] == ["user", "assistant", "user"]
+ assert out[1] == {
+ "role": "assistant",
+ "content": "",
+ "reasoning_content": "I should search.",
+ }
+
class TestGgufVisionMessages:
_PNG_B64 = (
diff --git a/studio/backend/tests/test_tool_message_empty_content.py b/studio/backend/tests/test_tool_message_empty_content.py
index 636a35f5a96..3a1c424175f 100644
--- a/studio/backend/tests/test_tool_message_empty_content.py
+++ b/studio/backend/tests/test_tool_message_empty_content.py
@@ -51,3 +51,19 @@ def test_user_message_still_requires_content():
def test_assistant_empty_content_still_collapses_to_none():
msg = ChatMessage(role = "assistant", content = "")
assert msg.content is None
+
+
+def test_assistant_reasoning_content_round_trips():
+ msg = ChatMessage(
+ role = "assistant",
+ content = "answer",
+ reasoning_content = "step-by-step trace",
+ )
+ assert msg.model_dump(exclude_none = True)["reasoning_content"] == "step-by-step trace"
+
+
[email protected]("structured", [[{"type": "reasoning", "text": "x"}], {"text": "x"}, 42])
+def test_non_string_reasoning_is_ignored_instead_of_rejected(structured):
+ msg = ChatMessage(role = "assistant", content = "answer", reasoning_content = structured)
+ assert msg.reasoning_content is None
+ assert "reasoning_content" not in msg.model_dump(exclude_none = True)
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 7aafc27a4c0..d66a337e7c7 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -5337,9 +5337,10 @@ const CancelledIndicator: FC = () => {
/** Text of an assistant turn: what a continuation resumes from.
*
- * Text parts only, matching replay: reasoning is not sent back. Joined with nothing,
- * like the backend's `trailing_assistant_text`: a turn split around a reasoning part
- * never had a newline between its halves, and inventing one moves the boundary. */
+ * Text parts only: a continuation resumes the visible answer, not its private reasoning.
+ * Joined with nothing, like the backend's `trailing_assistant_text`: a turn split around
+ * a reasoning part never had a newline between its halves, and inventing one moves the
+ * boundary. */
function assistantMessageText(content: readonly unknown[] | undefined): string {
if (!content) {
return "";
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 8b8b4666c05..271152d820f 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -144,6 +144,7 @@ import {
CONTINUE_INSTRUCTION,
type IncompleteReason,
joinContinuation,
+ readIncompleteInfo,
readContinuationRequest,
rejectsAssistantPrefill,
resumesExactly,
@@ -829,6 +830,7 @@ function isAnthropicRefusalMessage(message: RunMessage): boolean {
type SerializedMessage = {
role: "system" | "user" | "assistant" | "tool";
content: OpenAIMessageContent | null;
+ reasoning_content?: string;
tool_calls?: Array<{
id: string;
type: "function";
@@ -1176,6 +1178,7 @@ function attachAssistantThoughtSignature(
function serializeAssistantReplayMessages(
message: RunMessage,
+ includeReasoningContent = false,
): SerializedMessage[] {
if (isAnthropicRefusalMessage(message)) {
// Prune refused assistant turn from outbound history; the
@@ -1186,6 +1189,7 @@ function serializeAssistantReplayMessages(
const imageParts = collectImageParts(message);
const messages: SerializedMessage[] = [];
const pendingTextParts: string[] = [];
+ const pendingReasoningParts: string[] = [];
let pendingToolCalls: SerializedToolCall[] = [];
let pendingToolResults: SerializedToolResult[] = [];
let imagePartsPending = imageParts.length > 0;
@@ -1197,8 +1201,16 @@ function serializeAssistantReplayMessages(
const includeImageParts = imagePartsPending ? imageParts : [];
const hasContent = textContent.length > 0 || includeImageParts.length > 0;
const hasToolCalls = pendingToolCalls.length > 0;
-
- if (!force && !hasContent && !hasToolCalls) {
+ const reasoningContent = pendingReasoningParts.join("\n");
+ const reasoningOnlyTurnIsComplete =
+ message.status?.type !== "incomplete" &&
+ readIncompleteInfo((message as { metadata?: unknown }).metadata) === null;
+ const hasReasoningContent =
+ includeReasoningContent &&
+ reasoningContent.length > 0 &&
+ (hasContent || hasToolCalls || reasoningOnlyTurnIsComplete);
+
+ if (!force && !hasContent && !hasToolCalls && !hasReasoningContent) {
return;
}
@@ -1217,6 +1229,9 @@ function serializeAssistantReplayMessages(
assistantMessage.content = null;
}
}
+ if (hasReasoningContent) {
+ assistantMessage.reasoning_content = reasoningContent;
+ }
messages.push(assistantMessage);
if (pendingToolResults.length > 0) {
@@ -1224,12 +1239,21 @@ function serializeAssistantReplayMessages(
}
pendingTextParts.length = 0;
+ pendingReasoningParts.length = 0;
pendingToolCalls = [];
pendingToolResults = [];
imagePartsPending = false;
};
for (const part of message.content ?? []) {
+ if (part.type === "reasoning") {
+ if (pendingToolCalls.length > 0) {
+ flushAssistantAndToolResults();
+ }
+ pendingReasoningParts.push(part.text);
+ continue;
+ }
+
if (part.type === "text") {
if (pendingToolCalls.length > 0) {
flushAssistantAndToolResults();
@@ -1272,7 +1296,10 @@ function serializeAssistantReplayMessages(
return messages;
}
-function toOpenAIMessages(message: RunMessage): SerializedMessage[] {
+function toOpenAIMessages(
+ message: RunMessage,
+ includeReasoningContent = false,
+): SerializedMessage[] {
if (
message.role !== "system" &&
message.role !== "user" &&
@@ -1282,7 +1309,7 @@ function toOpenAIMessages(message: RunMessage): SerializedMessage[] {
}
if (message.role === "assistant") {
- return serializeAssistantReplayMessages(message);
+ return serializeAssistantReplayMessages(message, includeReasoningContent);
}
const textContent = collectTextParts(message).join("\n");
@@ -1444,7 +1471,7 @@ export async function buildOutboundMessagesForTokenCount(
}
const outboundMessages = survivingMessages
- .flatMap(toOpenAIMessages)
+ .flatMap((message) => toOpenAIMessages(message, true))
.filter((message): message is NonNullable<typeof message> =>
Boolean(message),
);
@@ -3991,7 +4018,9 @@ export function createOpenAIStreamAdapter(
// follow-ups; the backend Gemini translator rebuilds the
// functionCall / functionResponse parts (with thoughtSignature).
const outboundMessages = survivingMessages
- .flatMap(toOpenAIMessages)
+ .flatMap((message) =>
+ toOpenAIMessages(message, !isExternalRequest),
+ )
.filter((message): message is NonNullable<typeof message> =>
Boolean(message),
);
diff --git a/studio/frontend/tests/local-reasoning-replay.test.ts b/studio/frontend/tests/local-reasoning-replay.test.ts
new file mode 100644
index 00000000000..9e44c5a8f41
--- /dev/null
+++ b/studio/frontend/tests/local-reasoning-replay.test.ts
@@ -0,0 +1,228 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import ts from "typescript";
+
+const adapterPath = fileURLToPath(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+);
+const source = readFileSync(adapterPath, "utf8");
+const start = source.indexOf("function serializeAssistantReplayMessages(");
+const end = source.indexOf("\nfunction toOpenAIMessages(", start);
+assert.ok(
+ start >= 0 && end > start,
+ "assistant replay serializer was not found",
+);
+const declaration = source.slice(start, end);
+
+const serializeAssistantReplayMessages = new Function(
+ "isAnthropicRefusalMessage",
+ "collectImageParts",
+ "sanitizeAssistantReplayText",
+ "buildReplayContent",
+ "serializeAssistantToolCallPart",
+ "serializeToolResultPart",
+ "canReplayToolCallWithoutRoleTool",
+ "shouldFlushCompletedLocalToolPair",
+ "attachAssistantThoughtSignature",
+ "collectAssistantTextThoughtSignature",
+ "readIncompleteInfo",
+ `${
+ ts.transpileModule(declaration, {
+ compilerOptions: { target: ts.ScriptTarget.ES2020 },
+ }).outputText
+ }; return serializeAssistantReplayMessages;`,
+)(
+ () => false,
+ () => [],
+ (text: string) => text,
+ (text: string) => text,
+ (part: {
+ type?: string;
+ toolCallId?: string;
+ toolName?: string;
+ args?: unknown;
+ }) =>
+ part.type === "tool-call"
+ ? {
+ id: part.toolCallId,
+ type: "function",
+ function: {
+ name: part.toolName,
+ arguments: JSON.stringify(part.args ?? {}),
+ },
+ }
+ : null,
+ (part: {
+ type?: string;
+ toolCallId?: string;
+ toolName?: string;
+ result?: unknown;
+ }) =>
+ part.type === "tool-call" && part.result !== undefined
+ ? {
+ role: "tool",
+ content: String(part.result),
+ tool_call_id: part.toolCallId,
+ name: part.toolName,
+ }
+ : null,
+ () => false,
+ (part: { type?: string; result?: unknown }) =>
+ part.type === "tool-call" && part.result !== undefined,
+ () => undefined,
+ () => undefined,
+ (metadata: unknown) => {
+ const custom = (
+ metadata as { custom?: Record<string, unknown> } | undefined
+ )?.custom;
+ return custom?.incomplete ?? null;
+ },
+) as (
+ message: {
+ role: "assistant";
+ status?: { type: string; reason?: string };
+ metadata?: { custom?: Record<string, unknown> };
+ content: Array<{
+ type: string;
+ text?: string;
+ toolCallId?: string;
+ toolName?: string;
+ args?: unknown;
+ result?: unknown;
+ }>;
+ },
+ includeReasoningContent?: boolean,
+) => Array<Record<string, unknown>>;
+
+const assistantTurn = {
+ role: "assistant" as const,
+ content: [
+ { type: "reasoning", text: "First inspect the premise." },
+ { type: "reasoning", text: "Then answer clearly." },
+ { type: "text", text: "Here is the answer." },
+ ],
+};
+
+test("local replay preserves structured assistant reasoning", () => {
+ assert.deepEqual(serializeAssistantReplayMessages(assistantTurn, true), [
+ {
+ role: "assistant",
+ content: "Here is the answer.",
+ reasoning_content: "First inspect the premise.\nThen answer clearly.",
+ },
+ ]);
+});
+
+test("external replay does not add the local reasoning extension", () => {
+ assert.deepEqual(serializeAssistantReplayMessages(assistantTurn, false), [
+ { role: "assistant", content: "Here is the answer." },
+ ]);
+});
+
+test("a completed reasoning-only turn preserves its answer", () => {
+ assert.deepEqual(
+ serializeAssistantReplayMessages(
+ {
+ role: "assistant",
+ status: { type: "complete" },
+ content: [{ type: "reasoning", text: "The answer is forty-two." }],
+ },
+ true,
+ ),
+ [
+ {
+ role: "assistant",
+ content: "",
+ reasoning_content: "The answer is forty-two.",
+ },
+ ],
+ );
+});
+
+test("an incomplete reasoning-only turn remains an empty sentinel", () => {
+ assert.deepEqual(
+ serializeAssistantReplayMessages(
+ {
+ role: "assistant",
+ status: { type: "incomplete", reason: "cancelled" },
+ content: [{ type: "reasoning", text: "An unfinished thought." }],
+ },
+ true,
+ ),
+ [{ role: "assistant", content: "" }],
+ );
+});
+
+test("a rehydrated incomplete reasoning-only turn remains an empty sentinel", () => {
+ assert.deepEqual(
+ serializeAssistantReplayMessages(
+ {
+ role: "assistant",
+ status: { type: "complete" },
+ metadata: {
+ custom: { incomplete: { reason: "cancelled" } },
+ },
+ content: [{ type: "reasoning", text: "An unfinished thought." }],
+ },
+ true,
+ ),
+ [{ role: "assistant", content: "" }],
+ );
+});
+
+test("reasoning stays with the assistant segment around a local tool call", () => {
+ assert.deepEqual(
+ serializeAssistantReplayMessages(
+ {
+ role: "assistant",
+ content: [
+ { type: "reasoning", text: "I should inspect the file." },
+ {
+ type: "tool-call",
+ toolCallId: "call-1",
+ toolName: "read_file",
+ args: { path: "notes.txt" },
+ result: "contents",
+ },
+ { type: "reasoning", text: "The file answers the question." },
+ { type: "text", text: "Here is the answer." },
+ ],
+ },
+ true,
+ ),
+ [
+ {
+ role: "assistant",
+ content: null,
+ reasoning_content: "I should inspect the file.",
+ tool_calls: [
+ {
+ id: "call-1",
+ type: "function",
+ function: {
+ name: "read_file",
+ arguments: '{"path":"notes.txt"}',
+ },
+ },
+ ],
+ },
+ {
+ role: "tool",
+ content: "contents",
+ tool_call_id: "call-1",
+ name: "read_file",
+ },
+ {
+ role: "assistant",
+ content: "Here is the answer.",
+ reasoning_content: "The file answers the question.",
+ },
+ ],
+ );
+});