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: Forward thinking controls and return reasoning on /v1/messages and /v1/responses (#9107)

Nilay43bf5ea81c37
diff --git a/studio/backend/core/inference/anthropic_compat.py b/studio/backend/core/inference/anthropic_compat.py
index a32e372d731..f02c2bfa2a2 100644
--- a/studio/backend/core/inference/anthropic_compat.py
+++ b/studio/backend/core/inference/anthropic_compat.py
@@ -70,13 +70,21 @@ def _anthropic_image_block_to_openai_part(block: dict) -> Optional[dict]:
def anthropic_messages_to_openai(
- messages: list[dict], system: Optional[Union[str, list]] = None
+ messages: list[dict],
+ system: Optional[Union[str, list]] = None,
+ preserve_thinking: bool = False,
) -> list[dict]:
"""Convert Anthropic messages + system to OpenAI-format message dicts.
User messages with ``image`` blocks are emitted as OpenAI multimodal
content arrays (``[{type: "text", ...}, {type: "image_url", ...}]``) so
they flow through llama-server's native vision pathway.
+
+ ``preserve_thinking`` keeps replayed assistant ``thinking`` blocks as
+ ``reasoning_content`` on the converted message, so templates that render
+ historical reasoning (Qwen3.6-style ``preserve_thinking``) actually receive
+ it; otherwise thinking is dropped from the prompt. ``redacted_thinking``
+ carries only ciphertext and is always dropped.
"""
result: list[dict] = []
@@ -103,14 +111,20 @@ def anthropic_messages_to_openai(
continue
if role == "assistant":
- # Assistant content: text + tool_use only (no images in Anthropic's model).
+ # Assistant content: text + tool_use (no images in Anthropic's model),
+ # plus replayed thinking when preservation is requested.
text_parts: list[str] = []
tool_calls: list[dict] = []
+ thinking_parts: list[str] = []
for block in content:
b = block if isinstance(block, dict) else block.model_dump()
btype = b.get("type", "")
if btype == "text":
text_parts.append(b["text"])
+ elif btype == "thinking" and preserve_thinking:
+ t = b.get("thinking") or ""
+ if t:
+ thinking_parts.append(t)
elif btype == "tool_use":
tool_calls.append(
{
@@ -125,6 +139,8 @@ def anthropic_messages_to_openai(
msg_dict: dict[str, Any] = {"role": "assistant"}
if text_parts:
msg_dict["content"] = "\n".join(text_parts)
+ if thinking_parts:
+ msg_dict["reasoning_content"] = "\n\n".join(thinking_parts)
if tool_calls:
msg_dict["tool_calls"] = tool_calls
result.append(msg_dict)
@@ -379,23 +395,74 @@ def _message_delta_usage(usage: Optional[dict]) -> dict:
}
+def _partial_tag_suffix_len(text: str, tag: str) -> int:
+ """Length of the longest proper prefix of ``tag`` that ends ``text``.
+
+ A streamed delta can cut a ``<think>`` tag anywhere; the caller holds that
+ suffix back until the next delta settles whether it was markup or prose.
+ """
+ for k in range(min(len(text), len(tag) - 1), 0, -1):
+ if text.endswith(tag[:k]):
+ return k
+ return 0
+
+
class AnthropicStreamEmitter:
"""Converts generate_chat_completion_with_tools() events into Anthropic
Messages SSE strings."""
- def __init__(self) -> None:
+ def __init__(
+ self,
+ parse_think: bool = True,
+ think_provenance: Optional[dict] = None,
+ ) -> None:
+ # Off when the route knows reasoning markup cannot be genuine (thinking
+ # disabled or a non-reasoning model): literal <think> in prose then
+ # streams as ordinary text instead of being consumed as a trace.
+ self._parse_think = parse_think
self.block_index: int = 0
+ self._block_index_used: bool = False
self._text_block_open: bool = False
+ self._thinking_block_open: bool = False
self._open_tool_call_id: Optional[str] = None
# The mapped Anthropic ``toolu_*`` id published in content_block_start,
# reused for the paired tool_result so consumers can correlate them.
self._open_tool_use_id: Optional[str] = None
self._open_tool_args_sent: bool = False
self._prev_text: str = ""
- # Net <think> minus </think> in the text emitted to the client. Tracked
- # from emitted deltas (not _prev_text, which a final bare shrink clobbers)
- # so an unclosed reasoning-only block can be balanced before close.
- self._open_think_tags: int = 0
+ # <think> routing: the generator folds reasoning_content into the
+ # cumulative text as <think>...</think> markup (the UI chat parses it),
+ # but Anthropic clients expect typed thinking blocks. Split the markup
+ # back out: text inside the tags streams as thinking_delta in a
+ # "thinking" content block, everything else as ordinary text. _tag_buf
+ # holds back a trailing partial tag until the next delta decides it.
+ self._route_mode: str = "text"
+ self._tag_buf: str = ""
+ # Leading whitespace of a thinking span, held until real reasoning
+ # arrives so a whitespace-only trace never opens a block. See
+ # _emit_thinking_delta.
+ self._thinking_ws_hold: str = ""
+ # Genuine reasoning only ever arrives as a single LEADING <think>
+ # block per synthesis turn (the generator folds reasoning_content in
+ # as a prefix). Once that block closed, or once real answer text has
+ # streamed, any later <think> is the model quoting the tag and must
+ # stay literal.
+ self._think_consumed: bool = False
+ self._turn_has_text: bool = False
+ # Live provenance from the generator: "wrapped" counts the leading
+ # <think> tags IT opened from reasoning_content. When provided, a
+ # leading tag is only parsed as reasoning if a generator wrap is
+ # available -- a model answering with literal <think> markup (and no
+ # genuine trace) keeps it as text. None falls back to the leading-tag
+ # heuristic (test doubles / callers without provenance).
+ self._think_provenance = think_provenance
+ self._wraps_consumed: int = 0
+ # Active wrap entry ({"len": N} from the generator) while a provenance
+ # -backed thinking block streams: the block spans exactly N reasoning
+ # chars, so a literal "</think>" INSIDE the trace never ends it early.
+ self._active_wrap: Optional[dict] = None
+ self._wrap_chars: int = 0
+ self._close_skip: int = 0
self._usage: dict = {}
def start(
@@ -404,7 +471,7 @@ class AnthropicStreamEmitter:
model: str,
input_tokens: int = 0,
) -> list[str]:
- """Emit message_start and open the first text content block."""
+ """Emit message_start; content blocks open lazily on first output."""
events = []
events.append(
build_anthropic_sse_event(
@@ -429,7 +496,6 @@ class AnthropicStreamEmitter:
},
)
)
- events.extend(self._open_text_block())
return events
def feed(self, event: dict) -> list[str]:
@@ -454,8 +520,18 @@ class AnthropicStreamEmitter:
) -> list[str]:
"""Close any open block and emit message_delta + message_stop."""
events = []
- if self._text_block_open or self._open_tool_call_id is not None:
- events.extend(self._close_open_think())
+ # A trailing partial tag at end-of-stream is literal output, not markup.
+ if self._tag_buf:
+ held, self._tag_buf = self._tag_buf, ""
+ if self._route_mode == "thinking":
+ events.extend(self._emit_thinking_delta(held))
+ else:
+ events.extend(self._emit_text_delta(held))
+ if (
+ self._text_block_open
+ or self._thinking_block_open
+ or self._open_tool_call_id is not None
+ ):
events.append(self._close_block())
self._open_tool_call_id = None
self._open_tool_use_id = None
@@ -483,44 +559,153 @@ class AnthropicStreamEmitter:
)
return events
- def _close_open_think(self) -> list[str]:
- """Emit a ``</think>`` delta when the streamed text left a ``<think>``
- open. This emitter diffs cumulative snapshots and drops the generator's
- final bare shrink, so a reasoning-only reply would otherwise end on an
- unclosed tag. Mirrors the chat route's reasoning extractor, which closes
- the block on finish; balances the block before it is closed."""
- if not self._text_block_open or self._open_think_tags <= 0:
+ def _handle_content(self, event: dict) -> list[str]:
+ cumulative = event.get("text", "")
+ new_text = cumulative[len(self._prev_text) :]
+ self._prev_text = cumulative
+ if not new_text:
return []
- self._open_think_tags = 0
- return [
+ return self._route_text(new_text)
+
+ def _route_text(self, new_text: str) -> list[str]:
+ """Split ``<think>`` markup out of the delta into typed blocks."""
+ if not self._parse_think:
+ return self._emit_text_delta(new_text)
+ events: list[str] = []
+ data = self._tag_buf + new_text
+ self._tag_buf = ""
+ while data:
+ if self._route_mode == "text":
+ if self._think_consumed or self._turn_has_text:
+ events.extend(self._emit_text_delta(data))
+ break
+ open_tag = "<think>"
+ i = data.find(open_tag)
+ if i == -1:
+ keep = _partial_tag_suffix_len(data, open_tag)
+ emit = data[: len(data) - keep]
+ self._tag_buf = data[len(data) - keep :] if keep else ""
+ if emit:
+ events.extend(self._emit_text_delta(emit))
+ break
+ if i:
+ events.extend(self._emit_text_delta(data[:i]))
+ # Consumed: whatever happens to the tag below, the run
+ # before it has already been delivered. Re-including it in
+ # the literal-text branch below sent it to the client twice.
+ data = data[i:]
+ i = 0
+ if self._turn_has_text:
+ # Non-space text preceded the tag, so this is not the
+ # leading reasoning block; relay the rest literally.
+ continue
+ if (
+ self._think_provenance is not None
+ and self._think_provenance.get("wrapped", 0) <= self._wraps_consumed
+ ):
+ # The generator did not wrap this tag: literal model text.
+ events.extend(self._emit_text_delta(data))
+ break
+ wraps = (
+ self._think_provenance.get("wraps")
+ if self._think_provenance is not None
+ else None
+ )
+ self._active_wrap = (
+ wraps[self._wraps_consumed]
+ if wraps and self._wraps_consumed < len(wraps)
+ else None
+ )
+ self._wrap_chars = 0
+ self._wraps_consumed += 1
+ data = data[i + len(open_tag) :]
+ self._route_mode = "thinking"
+ else:
+ if self._close_skip:
+ skip = min(self._close_skip, len(data))
+ self._close_skip -= skip
+ data = data[skip:]
+ if self._close_skip == 0:
+ self._route_mode = "text"
+ self._think_consumed = True
+ self._active_wrap = None
+ continue
+ if self._active_wrap is not None:
+ # Provenance-backed span: consume exactly the generator's
+ # reasoning length, then skip its closing tag. A literal
+ # "</think>" inside the trace stays part of the thinking.
+ remaining = int(self._active_wrap.get("len", 0)) - self._wrap_chars
+ if remaining > 0:
+ take = min(remaining, len(data))
+ events.extend(self._emit_thinking_delta(data[:take]))
+ self._wrap_chars += take
+ data = data[take:]
+ continue
+ self._close_skip = len("</think>")
+ continue
+ close_tag = "</think>"
+ i = data.find(close_tag)
+ if i == -1:
+ keep = _partial_tag_suffix_len(data, close_tag)
+ emit = data[: len(data) - keep]
+ self._tag_buf = data[len(data) - keep :] if keep else ""
+ if emit:
+ events.extend(self._emit_thinking_delta(emit))
+ break
+ if i:
+ events.extend(self._emit_thinking_delta(data[:i]))
+ data = data[i + len(close_tag) :]
+ self._route_mode = "text"
+ self._think_consumed = True
+ return events
+
+ def _emit_text_delta(self, text: str) -> list[str]:
+ if text.strip():
+ self._turn_has_text = True
+ events: list[str] = []
+ if self._thinking_block_open:
+ events.append(self._close_block())
+ if not self._text_block_open:
+ events.extend(self._open_text_block())
+ events.append(
build_anthropic_sse_event(
"content_block_delta",
{
"type": "content_block_delta",
"index": self.block_index,
- "delta": {"type": "text_delta", "text": "</think>"},
+ "delta": {"type": "text_delta", "text": text},
},
)
- ]
+ )
+ return events
- def _handle_content(self, event: dict) -> list[str]:
- cumulative = event.get("text", "")
- new_text = cumulative[len(self._prev_text) :]
- self._prev_text = cumulative
- if not new_text:
- return []
- self._open_think_tags += new_text.count("<think>") - new_text.count("</think>")
- if not self._text_block_open:
- events = self._open_text_block()
- else:
- events = []
+ def _emit_thinking_delta(self, text: str) -> list[str]:
+ if not self._thinking_block_open:
+ # A trace that is only whitespace is not a thought: Qwen3-style
+ # templates render "<think>\n\n</think>" on every reply when thinking
+ # is off, and llama-server parses that into reasoning_content, so an
+ # empty thinking block would be attached to ordinary answers. The
+ # non-streaming reducer already drops those, so hold the leading
+ # whitespace run and only open the block once real reasoning arrives;
+ # the held run is then emitted with it so the trace stays verbatim.
+ held = self._thinking_ws_hold + text
+ if not held.strip():
+ self._thinking_ws_hold = held
+ return []
+ self._thinking_ws_hold = ""
+ text = held
+ events: list[str] = []
+ if self._text_block_open:
+ events.append(self._close_block())
+ if not self._thinking_block_open:
+ events.extend(self._open_thinking_block())
events.append(
build_anthropic_sse_event(
"content_block_delta",
{
"type": "content_block_delta",
"index": self.block_index,
- "delta": {"type": "text_delta", "text": new_text},
+ "delta": {"type": "thinking_delta", "thinking": text},
},
)
)
@@ -533,8 +718,14 @@ class AnthropicStreamEmitter:
return self._tool_arguments_delta(args)
events = []
- if self._text_block_open:
- events.extend(self._close_open_think())
+ # A held partial tag is literal output once a tool call interrupts it.
+ if self._tag_buf:
+ held, self._tag_buf = self._tag_buf, ""
+ if self._route_mode == "thinking":
+ events.extend(self._emit_thinking_delta(held))
+ else:
+ events.extend(self._emit_text_delta(held))
+ if self._text_block_open or self._thinking_block_open:
events.append(self._close_block())
# Defensive: close a stale open tool_use block before starting another.
elif self._open_tool_call_id is not None:
@@ -544,7 +735,7 @@ class AnthropicStreamEmitter:
self._open_tool_args_sent = False
# Open a tool_use block.
- self.block_index += 1
+ self._alloc_block_index()
self._open_tool_call_id = tool_call_id
self._open_tool_use_id = anthropic_tool_use_id(tool_call_id)
self._open_tool_args_sent = False
@@ -608,15 +799,27 @@ class AnthropicStreamEmitter:
},
)
)
- # Open a new text block for the model's next response
- self.block_index += 1
- events.extend(self._open_text_block())
- # Reset text tracking for the next synthesis turn
+ # Reset text tracking for the next synthesis turn; the next content
+ # delta opens a fresh text (or thinking) block lazily, and the new
+ # turn may legitimately open with its own leading <think> block.
self._prev_text = ""
- self._open_think_tags = 0
+ self._tag_buf = ""
+ self._thinking_ws_hold = ""
+ self._route_mode = "text"
+ self._think_consumed = False
+ self._turn_has_text = False
+ self._active_wrap = None
+ self._wrap_chars = 0
+ self._close_skip = 0
return events
+ def _alloc_block_index(self) -> None:
+ if self._block_index_used:
+ self.block_index += 1
+ self._block_index_used = True
+
def _open_text_block(self) -> list[str]:
+ self._alloc_block_index()
self._text_block_open = True
return [
build_anthropic_sse_event(
@@ -629,8 +832,26 @@ class AnthropicStreamEmitter:
)
]
+ def _open_thinking_block(self) -> list[str]:
+ self._alloc_block_index()
+ self._thinking_block_open = True
+ return [
+ build_anthropic_sse_event(
+ "content_block_start",
+ {
+ "type": "content_block_start",
+ "index": self.block_index,
+ # signature is part of the Anthropic thinking-block shape;
+ # strict stream decoders reject the block without it. Local
+ # models have no signing key, so it stays empty.
+ "content_block": {"type": "thinking", "thinking": "", "signature": ""},
+ },
+ )
+ ]
+
def _close_block(self) -> str:
self._text_block_open = False
+ self._thinking_block_open = False
return build_anthropic_sse_event(
"content_block_stop",
{
@@ -649,7 +870,13 @@ class AnthropicPassthroughEmitter:
response back to Anthropic format without executing anything.
"""
- def __init__(self) -> None:
+ def __init__(self, reasoning_as_thinking: bool = True) -> None:
+ # When thinking is effectively off, llama-server's format parser can
+ # still shunt a literal <think> example the model was asked to produce
+ # into reasoning_content; reconstruct it as visible text instead of a
+ # typed thinking block.
+ self._reasoning_as_thinking = reasoning_as_thinking
+ self._reasoning_text_open = False
self.block_index: int = -1
self._current_block_type: Optional[str] = None # "text" | "tool_use" | None
self._tool_call_states: dict = {} # delta index -> {block_index, id, name}
@@ -727,6 +954,42 @@ class AnthropicPassthroughEmitter:
delta = choice.get("delta") or {}
finish_reason = choice.get("finish_reason")
+ # ── Reasoning ──
+ # llama-server splits <think> into reasoning_content whenever it can parse
+ # the model's reasoning format (it does so for tool-calling turns, which is
+ # every Claude Code turn). Reading only `content` drops the entire thinking
+ # trace, so the model appears not to think at all.
+ reasoning = delta.get("reasoning_content")
+ if reasoning:
+ if not self._reasoning_as_thinking:
+ prefix = "" if self._reasoning_text_open else "<think>"
+ self._reasoning_text_open = True
+ events.extend(self._emit_text_delta(prefix + reasoning))
+ else:
+ if self._current_block_type != "thinking":
+ if self._current_block_type is not None:
+ events.append(self._close_current_block())
+ events.extend(self._open_thinking_block())
+ events.append(
+ build_anthropic_sse_event(
+ "content_block_delta",
+ {
+ "type": "content_block_delta",
+ "index": self.block_index,
+ "delta": {"type": "thinking_delta", "thinking": reasoning},
+ },
+ )
+ )
+ # Reconstructed literal block ends where the answer resumes -- checked
+ # unconditionally (not elif): one chunk can carry the final reasoning
+ # fragment AND same-chunk content/tool output, and the closing tag must
+ # land between them.
+ if self._reasoning_text_open and (
+ delta.get("content") or delta.get("tool_calls") or finish_reason
+ ):
+ self._reasoning_text_open = False
+ events.extend(self._emit_text_delta("</think>"))
+
# ── Structured tool calls take precedence over healing ──
# Grammar mode worked: flush anything the healer held (it preceded the
# call in the model's output) and relay verbatim from here on.
@@ -816,6 +1079,9 @@ class AnthropicPassthroughEmitter:
def finish(self) -> list[str]:
events: list[str] = []
+ if self._reasoning_text_open:
+ self._reasoning_text_open = False
+ events.extend(self._emit_text_delta("</think>"))
if self._healer is not None:
# Last-chance heal of any held residue (e.g. an unclosed tool block).
for kind, value in self._healer.finalize():
@@ -934,6 +1200,21 @@ class AnthropicPassthroughEmitter:
)
]
+ def _open_thinking_block(self) -> list[str]:
+ self.block_index += 1
+ self._current_block_type = "thinking"
+ return [
+ build_anthropic_sse_event(
+ "content_block_start",
+ {
+ "type": "content_block_start",
+ "index": self.block_index,
+ # Empty signature keeps strict Anthropic decoders happy.
+ "content_block": {"type": "thinking", "thinking": "", "signature": ""},
+ },
+ )
+ ]
+
def _close_current_block(self) -> str:
idx = self.block_index
self._current_block_type = None
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index e710ca87cd7..9e1bc8803b5 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -22562,6 +22562,7 @@ class LlamaCppBackend:
seed: Optional[int] = None,
promote_reasoning_only: bool = True,
perf_callback: Optional[Callable[[dict], None]] = None,
+ reasoning_provenance: Optional[dict] = None,
context_overflow: Optional[str] = None,
thread_id: Optional[str] = None,
tools_withheld: bool = False,
@@ -22731,6 +22732,7 @@ class LlamaCppBackend:
buffer = ""
has_content_tokens = False
reasoning_text = ""
+ _prov_entry = None
for raw_chunk in self._iter_text_cancellable(
response,
cancel_event,
@@ -22748,6 +22750,7 @@ class LlamaCppBackend:
if has_content_tokens:
# Real thinking + content: close the tag
cumulative += "</think>"
+ _prov_entry = None
yield cumulative
else:
# Only reasoning_content, no content:
@@ -22760,6 +22763,7 @@ class LlamaCppBackend:
_metadata_finish_reason,
promote_reasoning_only,
)
+ _prov_entry = None
yield cumulative
_stream_done = True
break # exit inner while
@@ -22796,9 +22800,22 @@ class LlamaCppBackend:
if reasoning:
reasoning_text += reasoning
if not in_thinking:
+ # Provenance for think-aware consumers: a
+ # leading <think> we open here is genuine
+ # reasoning, unlike literal tags in content.
+ if reasoning_provenance is not None and not cumulative:
+ reasoning_provenance["wrapped"] = (
+ reasoning_provenance.get("wrapped", 0) + 1
+ )
+ _prov_entry = {"len": 0}
+ reasoning_provenance.setdefault("wraps", []).append(
+ _prov_entry
+ )
cumulative += "<think>"
in_thinking = True
cumulative += reasoning
+ if _prov_entry is not None:
+ _prov_entry["len"] += len(reasoning)
yield cumulative
token = delta.get("content", "")
@@ -22807,6 +22824,7 @@ class LlamaCppBackend:
if in_thinking:
cumulative += "</think>"
in_thinking = False
+ _prov_entry = None
cumulative += token
yield cumulative
except json.JSONDecodeError:
@@ -22869,6 +22887,7 @@ class LlamaCppBackend:
seed = seed,
promote_reasoning_only = promote_reasoning_only,
perf_callback = perf_callback,
+ reasoning_provenance = reasoning_provenance,
context_overflow = retry_context_overflow,
# The retry refits for the replacement window and can evict more than
# the first attempt did. Without the thread those extra turns are
@@ -22922,6 +22941,7 @@ class LlamaCppBackend:
permission_mode: Optional[str] = None,
promote_reasoning_only: bool = True,
perf_callback: Optional[Callable[[dict], None]] = None,
+ reasoning_provenance: Optional[dict] = None,
context_overflow: Optional[str] = None,
) -> Generator[dict, None, None]:
"""
@@ -23130,11 +23150,21 @@ class LlamaCppBackend:
"""Close a live-streamed <think> block (or emit the buffered reasoning
as one block if it never streamed), then append the held
content_buffer to the cumulative display text."""
- nonlocal cumulative_display, in_thinking
+ nonlocal cumulative_display, in_thinking, _prov_entry
if in_thinking:
cumulative_display += "</think>"
in_thinking = False
+ _prov_entry = None
elif reasoning_accum:
+ if (
+ reasoning_provenance is not None
+ and not cumulative_display
+ and not _suppress_visible_output
+ ):
+ reasoning_provenance["wrapped"] = reasoning_provenance.get("wrapped", 0) + 1
+ reasoning_provenance.setdefault("wraps", []).append(
+ {"len": len(reasoning_accum)}
+ )
cumulative_display += "<think>" + reasoning_accum + "</think>"
cumulative_display += content_buffer
@@ -23142,11 +23172,12 @@ class LlamaCppBackend:
"""Close a live-streamed <think> before a tool call drains, so
consumers without a reasoning extractor (Anthropic) get a balanced
block. Returns True when the caller should yield the result."""
- nonlocal cumulative_display, in_thinking, _last_emitted
+ nonlocal cumulative_display, in_thinking, _last_emitted, _prov_entry
if not in_thinking:
return False
cumulative_display += "</think>"
in_thinking = False
+ _prov_entry = None
if len(cumulative_display) > len(_last_emitted) and not _suppress_visible_output:
_last_emitted = cumulative_display
return True
@@ -23484,6 +23515,7 @@ class LlamaCppBackend:
content_buffer = "" # Raw content held during BUFFERING
content_accum = "" # All content tokens (for tool parsing)
reasoning_accum = ""
+ _prov_entry = None
# Time each reasoning pass so final answers can replace tool timing.
_reasoning_started_at = None
_reasoning_summary_emitted = False
@@ -23547,6 +23579,7 @@ class LlamaCppBackend:
if detect_state == _S_STREAMING and in_thinking:
if has_content_tokens:
cumulative_display += "</think>"
+ _prov_entry = None
if not _suppress_visible_output:
yield {
"type": "content",
@@ -23562,6 +23595,7 @@ class LlamaCppBackend:
_iter_finish_reason,
promote_reasoning_only,
)
+ _prov_entry = None
if not _suppress_visible_output:
yield {
"type": "content",
@@ -23759,9 +23793,27 @@ class LlamaCppBackend:
reasoning_accum += reasoning
if detect_state != _S_DRAINING:
if not in_thinking:
+ # Suppressed (forced-retry) iterations
+ # yield no content events, so recording
+ # their wraps would desync the ledger
+ # from the emitted stream.
+ if (
+ reasoning_provenance is not None
+ and not cumulative_display
+ and not _suppress_visible_output
+ ):
+ reasoning_provenance["wrapped"] = (
+ reasoning_provenance.get("wrapped", 0) + 1
+ )
+ _prov_entry = {"len": 0}
+ reasoning_provenance.setdefault("wraps", []).append(
+ _prov_entry
+ )
cumulative_display += "<think>"
in_thinking = True
cumulative_display += reasoning
+ if _prov_entry is not None:
+ _prov_entry["len"] += len(reasoning)
if not _suppress_visible_output:
yield {
"type": "content",
@@ -23852,6 +23904,7 @@ class LlamaCppBackend:
if in_thinking:
cumulative_display += "</think>"
in_thinking = False
+ _prov_entry = None
cumulative_display += token
cleaned = _strip_tool_markup_streaming(cumulative_display)
# Hold a trailing bare active-tool-name (split rehearsal)
@@ -24076,6 +24129,7 @@ class LlamaCppBackend:
_iter_finish_reason,
promote_reasoning_only,
)
+ _prov_entry = None
if not _suppress_visible_output:
yield {
"type": "content",
@@ -24957,6 +25011,7 @@ class LlamaCppBackend:
in_thinking = False
has_content_tokens = False
reasoning_text = ""
+ _prov_entry = None
_final_reasoning_started_at: Optional[float] = None
_final_reasoning_summary_emitted = False
_metadata_usage = None
@@ -24998,6 +25053,7 @@ class LlamaCppBackend:
yield _reasoning_summary_event(_final_reasoning_started_at)
if has_content_tokens:
cumulative += "</think>"
+ _prov_entry = None
yield {
"type": "content",
"text": _strip_tool_markup(cumulative, final = True),
@@ -25009,6 +25065,7 @@ class LlamaCppBackend:
_metadata_finish_reason,
promote_reasoning_only,
)
+ _prov_entry = None
yield {"type": "content", "text": cumulative}
_stream_done = True
break # exit inner while
@@ -25039,9 +25096,19 @@ class LlamaCppBackend:
_final_reasoning_started_at = time.monotonic()
reasoning_text += reasoning
if not in_thinking:
+ if reasoning_provenance is not None and not cumulative:
+ reasoning_provenance["wrapped"] = (
+ reasoning_provenance.get("wrapped", 0) + 1
+ )
+ _prov_entry = {"len": 0}
+ reasoning_provenance.setdefault("wraps", []).append(
+ _prov_entry
+ )
cumulative += "<think>"
in_thinking = True
cumulative += reasoning
+ if _prov_entry is not None:
+ _prov_entry["len"] += len(reasoning)
yield {"type": "content", "text": cumulative}
token = delta.get("content", "")
@@ -25056,6 +25123,7 @@ class LlamaCppBackend:
if in_thinking:
cumulative += "</think>"
in_thinking = False
+ _prov_entry = None
cumulative += token
cleaned = (
_final_answer_stripper.strip(cumulative)
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 9de58d853fb..c8891c280d8 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2557,7 +2557,12 @@ class AnthropicToolResultBlock(BaseModel):
# redacted_thinking, a provider block a resumed session replays, or a future type)
# is accepted as an unknown block and dropped by the converter, rather than 400-ing
# the whole request on strict validation.
-_KNOWN_ANTHROPIC_BLOCK_TYPES = frozenset({"text", "image", "tool_use", "tool_result"})
+_KNOWN_ANTHROPIC_BLOCK_TYPES = frozenset(
+ {"text", "image", "tool_use", "tool_result", "thinking", "redacted_thinking"}
+)
+# Thinking blocks are replayed only in assistant turns; the converter drops them
+# from user content, so accepting them there would silently lose a user turn.
+_USER_ANTHROPIC_BLOCK_TYPES = frozenset({"text", "image", "tool_use", "tool_result"})
class AnthropicUnknownBlock(BaseModel):
@@ -2574,11 +2579,29 @@ class AnthropicUnknownBlock(BaseModel):
return v
+class AnthropicThinkingBlock(BaseModel):
+ # Clients replay thinking blocks with tool results (Anthropic's tool-use
+ # protocol requires it), so the request model must accept them; conversion
+ # drops them from the prompt.
+ type: Literal["thinking"]
+ thinking: str = ""
+ signature: str = ""
+ model_config = {"extra": "allow"}
+
+
+class AnthropicRedactedThinkingBlock(BaseModel):
+ type: Literal["redacted_thinking"]
+ data: str = ""
+ model_config = {"extra": "allow"}
+
+
AnthropicContentBlock = Union[
AnthropicTextBlock,
AnthropicImageBlock,
AnthropicToolUseBlock,
AnthropicToolResultBlock,
+ AnthropicThinkingBlock,
+ AnthropicRedactedThinkingBlock,
AnthropicUnknownBlock,
]
@@ -2654,7 +2677,7 @@ class AnthropicMessage(BaseModel):
# Guard the value: a non-string type is unsupported too, and a
# membership test on an unhashable value would raise TypeError
# (escaping as a 500 instead of a clean 400).
- if not isinstance(btype, str) or btype not in _KNOWN_ANTHROPIC_BLOCK_TYPES:
+ if not isinstance(btype, str) or btype not in _USER_ANTHROPIC_BLOCK_TYPES:
raise ValueError(f"unsupported content block type {btype!r} in a user message")
return data
@@ -2669,6 +2692,18 @@ class AnthropicTool(BaseModel):
model_config = {"extra": "allow"}
+class AnthropicThinkingConfig(BaseModel):
+ # Deliberately `str`, not a Literal. Anthropic ships thinking types beyond
+ # enabled/disabled (adaptive tiers), and Claude Code sends them -- a strict
+ # Literal turns an unrecognized value into a hard 400, which is worse than
+ # the silent drop this replaced. Only "disabled" means off; treat anything
+ # else as a request to think.
+ type: str = "enabled"
+ # Accepted for wire compatibility; llama-server has no thinking budget.
+ budget_tokens: Optional[int] = None
+ model_config = {"extra": "allow"}
+
+
class AnthropicMessagesRequest(BaseModel):
model: str = "default"
max_tokens: Optional[int] = None
@@ -2694,6 +2729,17 @@ class AnthropicMessagesRequest(BaseModel):
)
enable_tools: Optional[bool] = None
enabled_tools: Optional[list[str]] = None
+ # Anthropic's native extended-thinking control. Only `type` is honored:
+ # llama-server has no thinking-token budget, so `budget_tokens` is accepted
+ # and ignored rather than 400'd (Claude Code always sends it alongside).
+ thinking: Optional[AnthropicThinkingConfig] = None
+ # [x-unsloth] reasoning controls mirroring the OpenAI endpoint. These win
+ # over `thinking` when both are present, matching enable_tools precedence.
+ enable_thinking: Optional[bool] = None
+ reasoning_effort: Optional[
+ Literal["none", "minimal", "low", "medium", "high", "max", "xhigh"]
+ ] = None
+ preserve_thinking: Optional[bool] = None
session_id: Optional[str] = None
thread_id: Optional[str] = Field(
None,
@@ -2718,6 +2764,14 @@ class AnthropicMessagesRequest(BaseModel):
)
model_config = {"extra": "allow"}
+ def resolved_enable_thinking(self) -> Optional[bool]:
+ """Effective on/off, preferring the x-unsloth field over `thinking`."""
+ if self.enable_thinking is not None:
+ return self.enable_thinking
+ if self.thinking is not None:
+ return self.thinking.type != "disabled"
+ return None
+
@model_validator(mode = "before")
@classmethod
def normalize_system_messages(cls, data: Any) -> Any:
@@ -2793,7 +2847,20 @@ class AnthropicResponseToolUseBlock(BaseModel):
input: dict
-AnthropicResponseBlock = Union[AnthropicResponseTextBlock, AnthropicResponseToolUseBlock]
+class AnthropicResponseThinkingBlock(BaseModel):
+ type: Literal["thinking"] = "thinking"
+ thinking: str
+ # Anthropic signs thinking blocks so they can be replayed on a later turn.
+ # Nothing local can produce a valid signature, so it stays empty; clients
+ # that only render the trace do not check it.
+ signature: str = ""
+
+
+AnthropicResponseBlock = Union[
+ AnthropicResponseTextBlock,
+ AnthropicResponseToolUseBlock,
+ AnthropicResponseThinkingBlock,
+]
class AnthropicMessagesResponse(BaseModel):
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index c19b936552f..f0809a175a0 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2285,6 +2285,7 @@ from models.inference import (
AnthropicMessagesRequest,
AnthropicMessagesResponse,
AnthropicResponseTextBlock,
+ AnthropicResponseThinkingBlock,
AnthropicResponseToolUseBlock,
AnthropicUsage,
CreateOpenAIContainerBody,
@@ -3045,6 +3046,122 @@ def _confirm_gate_needs_stream(payload) -> bool:
return not all(is_always_safe_tool(t) and t != "web_search" for t in enabled)
+def _anthropic_reasoning_args(payload) -> dict:
+ """Reasoning kwargs for /v1/messages generators.
+
+ `/v1/messages` accepts Anthropic's `thinking` block plus the x-unsloth
+ reasoning fields; without this the request is parsed and silently dropped,
+ so the model can never be switched out of its load-time reasoning default.
+ """
+ # Resolve in the precedence the request model documents: "[x-unsloth]
+ # reasoning controls ... win over `thinking` when both are present". Both
+ # x-unsloth controls outrank the native block, so reasoning_effort is
+ # consulted BEFORE falling back to `thinking` -- reading
+ # resolved_enable_thinking() first would let `thinking` pre-empt the effort
+ # dial and silently drop it on plain enable_thinking templates (Qwen3),
+ # whose _request_reasoning_kwargs looks at the boolean only. The
+ # effort-dial families already honor effort downstream, so this is what
+ # makes one request mean the same thing across template shapes.
+ enable_thinking = payload.enable_thinking
+ reasoning_effort = payload.reasoning_effort
+ # Mirror the /v1/responses mapping: an effort-only request still drives
+ # enable_thinking-style templates, whose only dial is the boolean --
+ # "none" means off, any named level means on. This keeps generation and
+ # the think-markup parsing gate reading the same effective controls.
+ if enable_thinking is None and reasoning_effort is not None:
+ enable_thinking = reasoning_effort != "none"
+ if enable_thinking is None:
+ # Neither x-unsloth control was sent: fall back to Anthropic's native
+ # `thinking` block (and to None when that is absent too, leaving the
+ # model in its load-time default).
+ enable_thinking = payload.resolved_enable_thinking()
+ return {
+ "enable_thinking": enable_thinking,
+ "reasoning_effort": reasoning_effort,
+ "preserve_thinking": payload.preserve_thinking,
+ }
+
+
+def _anthropic_preserve_thinking(llama_backend, payload) -> bool:
+ """Whether replayed assistant thinking survives Anthropic -> OpenAI conversion.
+
+ Three-valued on the wire: True/False are explicit request overrides, None
+ means "not specified", and llama-server then falls back per key to the
+ launch-time --chat-template-kwargs. So an omitted field leaves the template
+ in whatever preserve mode the model was LOADED in, and coercing it to False
+ here would strip the reasoning_content that same template is still being
+ told to render -- on a preserve-by-default family (Qwen3.8) the replayed
+ thinking is dropped and the model loses the history its active template
+ configuration expects.
+
+ Both /messages and /messages/count_tokens resolve through here so the count
+ keeps describing the prompt generation actually builds.
+ """
+ if payload.preserve_thinking is not None:
+ return bool(payload.preserve_thinking)
+ return bool(getattr(llama_backend, "preserve_thinking_default", False))
+
+
+def _think_parsing_expected(llama_backend, payload) -> bool:
+ """Whether <think> markup in this reply can be genuine reasoning.
+
+ Literal ``<think>`` in prose (a user asking for an XML example) must stay
+ text when the model cannot think, so the typed-thinking splitter only runs
+ when reasoning markup is expected: an always-on reasoning model, or a
+ reasoning-capable template with thinking not switched off by the request.
+ Attribute defaults keep test doubles (which lack the introspection) on the
+ parsing path.
+ """
+ if getattr(llama_backend, "reasoning_always_on", False):
+ return True
+ if not getattr(llama_backend, "supports_reasoning", True):
+ return False
+ # Decide from the SAME effective template kwargs generation renders with,
+ # not the raw request flags: effort-dial templates (gpt-oss) map
+ # enable_thinking=False to a low-but-thinking effort, so the raw boolean
+ # would disable parsing while genuine markup still streams.
+ args = _anthropic_reasoning_args(payload)
+ resolved = (
+ _reasoning_template_kwargs(
+ llama_backend,
+ args["enable_thinking"],
+ args["reasoning_effort"],
+ args["preserve_thinking"],
+ )
+ or {}
+ )
+ if "enable_thinking" in resolved:
+ return bool(resolved["enable_thinking"])
+ if "reasoning_effort" in resolved:
+ # Effort-dial templates think at every level except "none".
+ return resolved["reasoning_effort"] != "none"
+ # No explicit kwargs: the template's own default decides whether it thinks.
+ return bool(getattr(llama_backend, "reasoning_default", True))
+
+
+def _anthropic_count_template_kwargs(llama_backend, payload):
+ """Resolved reasoning chat_template_kwargs for prompt-token counting."""
+ args = _anthropic_reasoning_args(payload)
+ return _reasoning_template_kwargs(
+ llama_backend, args["enable_thinking"], args["reasoning_effort"], args["preserve_thinking"]
+ )
+
+
+def _reasoning_template_kwargs(llama_backend, enable_thinking, reasoning_effort, preserve_thinking):
+ """chat_template_kwargs matching the loaded model's reasoning style.
+
+ The backend knows whether the template takes ``enable_thinking`` or
+ ``reasoning_effort`` and whether reasoning is always-on; fall back to the
+ plain flag when that introspection isn't available.
+ """
+ resolver = getattr(llama_backend, "_request_reasoning_kwargs", None)
+ if resolver is not None:
+ return resolver(enable_thinking, reasoning_effort, preserve_thinking)
+ if enable_thinking is None:
+ return None
+ return {"enable_thinking": bool(enable_thinking)}
+
+
# Cancel registry. Proxies (e.g. Colab) can swallow client fetch aborts so
# is_disconnected() never fires. POST /inference/cancel looks up in-flight
# cancel_events here by cancel_id (per-run) or session_id / completion_id
@@ -3898,6 +4015,93 @@ def _strip_tool_xml_for_display(
return strip_outside_think(text, _strip_segment)
+class _ReasoningSpanGuard:
+ """Display strip that never edits a provenance-recorded reasoning trace.
+
+ ``_THINK_TAG_RE`` closes on the FIRST ``</think>``, so a trace quoting the literal tag
+ leaves its own tail exposed to the cleaner while ``wrap["len"]`` still measures the
+ unstripped trace; the emitter/splitter then consume the real terminator and the answer as
+ thinking. Provenance records the true length, so the recorded span is protected and only
+ the answer after it is cleaned. Mirrors the emitter's wrap ledger: a tool loop's later
+ synthesis turn opens its own leading ``<think>`` backed by the NEXT wrap entry, so the
+ span is claimed per turn rather than always from ``wraps[0]``.
+ """
+
+ _OPEN = "<think>"
+ _CLOSE = "</think>"
+
+ def __init__(self, think_provenance = None):
+ self._prov = think_provenance
+ self._consumed = 0
+ self._turn_wrap = None
+ self._claimed = False
+
+ @property
+ def claimed(self) -> bool:
+ """True once the current turn's leading tag is backed by a generator wrap."""
+ return self._claimed
+
+ @property
+ def claimed_wrap(self):
+ """The wrap entry claimed for the current turn (may be ``None`` when the
+ ledger recorded the count but not the span)."""
+ return self._turn_wrap
+
+ def tool_end(self) -> None:
+ # The next synthesis turn restarts its cumulative text and may open a fresh wrap.
+ self._turn_wrap = None
+ self._claimed = False
+
+ def _wrap_for(
+ self,
+ text: str,
+ wrapped_so_far = None,
+ ):
+ if self._claimed:
+ return self._turn_wrap
+ if not self._prov or not text.startswith(self._OPEN):
+ return None
+ # ``wrapped_so_far`` is the ledger as it stood when THIS event was produced.
+ # The streamed path reads the live dict, so it can never hand a later
+ # synthesis turn's wrap to an earlier turn; a reducer running after the
+ # drain sees only the final aggregate and would. See
+ # _collect_anthropic_events.
+ _wrapped = int(self._prov.get("wrapped", 0))
+ if wrapped_so_far is not None:
+ _wrapped = min(_wrapped, int(wrapped_so_far))
+ if _wrapped <= self._consumed:
+ # The generator did not wrap this tag: literal model text.
+ return None
+ wraps = self._prov.get("wraps") or []
+ self._turn_wrap = wraps[self._consumed] if self._consumed < len(wraps) else None
+ self._consumed += 1
+ self._claimed = True
+ return self._turn_wrap
+
+ def strip(
+ self,
+ text: str,
+ *,
+ auto_heal_tool_calls: bool,
+ enabled_tool_names: Optional[set] = None,
+ wrapped_so_far = None,
+ ) -> str:
+ wrap = self._wrap_for(text, wrapped_so_far)
+ if wrap is None:
+ return _strip_tool_xml_for_display(
+ text,
+ auto_heal_tool_calls = auto_heal_tool_calls,
+ enabled_tool_names = enabled_tool_names,
+ )
+ # Clamp: mid-stream the close tag has not arrived yet, so the whole text is trace.
+ end = min(len(self._OPEN) + int(wrap.get("len", 0)) + len(self._CLOSE), len(text))
+ return text[:end] + _strip_tool_xml_for_display(
+ text[end:],
+ auto_heal_tool_calls = auto_heal_tool_calls,
+ enabled_tool_names = enabled_tool_names,
+ )
+
+
def _strip_tool_xml(text: str, enabled_tool_names: Optional[set] = None) -> str:
# Mistral balanced-brace pre-strip (kept explicit so the regression guards see it), then
# the shared think-aware display strip -- the one raw _TOOL_XML_RE.sub lives inside
@@ -20723,6 +20927,7 @@ async def anthropic_count_tokens(
openai_messages = anthropic_messages_to_openai(
[m.model_dump() for m in payload.messages],
payload.system,
+ preserve_thinking = _anthropic_preserve_thinking(llama_backend, payload),
)
# Apply the same sanitization /messages does before generation, so the count
# matches the prompt the real request would build (otherwise empty-assistant
@@ -20735,13 +20940,25 @@ async def anthropic_count_tokens(
)
openai_tools = anthropic_tools_to_openai(payload.tools or []) or None
+ # Render with the same reasoning controls generation will use: on switchable
+ # templates thinking / reasoning_effort / preserve_thinking change the
+ # rendered prompt, so counting the load-time default would under- or
+ # over-count the request the client is about to send.
+ _reasoning_args = _anthropic_reasoning_args(payload)
try:
count = await asyncio.to_thread(
- llama_backend.count_chat_tokens,
- openai_messages,
- None,
- openai_tools,
- strict = True,
+ lambda: llama_backend.count_chat_tokens(
+ openai_messages,
+ None,
+ openai_tools,
+ strict = True,
+ chat_template_kwargs = _reasoning_template_kwargs(
+ llama_backend,
+ _reasoning_args["enable_thinking"],
+ _reasoning_args["reasoning_effort"],
+ _reasoning_args["preserve_thinking"],
+ ),
+ )
)
except Exception:
raise HTTPException(
@@ -20912,6 +21129,7 @@ async def anthropic_messages(
openai_messages = anthropic_messages_to_openai(
[m.model_dump() for m in payload.messages],
payload.system,
+ preserve_thinking = _anthropic_preserve_thinking(llama_backend, payload),
)
# Strip synthetic provider-side builtin tool history (web_search,
# web_fetch, code_execution, image_generation cards tagged with
@@ -21280,6 +21498,8 @@ async def anthropic_messages(
cancel_id = payload.cancel_id,
disable_parallel_tool_use = _disable_parallel,
auto_heal_tool_calls = payload.auto_heal_tool_calls,
+ parse_think = _think_parsing_expected(llama_backend, payload),
+ **_anthropic_reasoning_args(payload),
)
)
return await _admitted_anthropic(
@@ -21303,9 +21523,16 @@ async def anthropic_messages(
nudge_tool_calls = payload.nudge_tool_calls,
request = request,
cancel_event = cancel_event,
+ parse_think = _think_parsing_expected(llama_backend, payload),
+ **_anthropic_reasoning_args(payload),
)
)
+ # Shared provenance: the generator counts the leading <think> wraps it
+ # created from reasoning_content, so the emitters can tell genuine traces
+ # from a model answering with literal <think> markup.
+ _think_prov: dict = {"wrapped": 0}
+
if server_tools:
# Bypass Permissions suppresses confirm, so both flags together is fine.
if bool(getattr(payload, "confirm_tool_calls", False)) and not bool(
@@ -21369,6 +21596,7 @@ async def anthropic_messages(
def _run_tool_gen():
return llama_backend.generate_chat_completion_with_tools(
+ reasoning_provenance = _think_prov,
messages = openai_messages,
tools = openai_tools,
temperature = temperature,
@@ -21396,6 +21624,7 @@ async def anthropic_messages(
monitor_id,
llama_backend.context_length,
),
+ **_anthropic_reasoning_args(payload),
)
if payload.stream:
@@ -21410,6 +21639,9 @@ async def anthropic_messages(
openai_messages = openai_messages,
openai_tools = openai_tools,
disable_parallel_tool_use = _disable_parallel,
+ parse_think = _think_parsing_expected(llama_backend, payload),
+ think_provenance = _think_prov,
+ count_template_kwargs = _anthropic_count_template_kwargs(llama_backend, payload),
)
)
return await _admitted_anthropic(
@@ -21419,6 +21651,8 @@ async def anthropic_messages(
model_name,
disable_parallel_tool_use = _disable_parallel,
openai_tools = openai_tools,
+ parse_think = _think_parsing_expected(llama_backend, payload),
+ think_provenance = _think_prov,
cancel_event = cancel_event,
)
)
@@ -21426,6 +21660,7 @@ async def anthropic_messages(
# ── No-tool path ──────────────────────────────────────────
def _run_plain_gen():
return llama_backend.generate_chat_completion(
+ reasoning_provenance = _think_prov,
messages = openai_messages,
temperature = temperature,
top_p = top_p,
@@ -21441,6 +21676,7 @@ async def anthropic_messages(
monitor_id,
llama_backend.context_length,
),
+ **_anthropic_reasoning_args(payload),
)
if payload.stream:
@@ -21453,6 +21689,9 @@ async def anthropic_messages(
model_name,
llama_backend = llama_backend,
openai_messages = openai_messages,
+ parse_think = _think_parsing_expected(llama_backend, payload),
+ think_provenance = _think_prov,
+ count_template_kwargs = _anthropic_count_template_kwargs(llama_backend, payload),
)
)
return await _admitted_anthropic(
@@ -21460,6 +21699,8 @@ async def anthropic_messages(
_run_plain_gen,
message_id,
model_name,
+ parse_think = _think_parsing_expected(llama_backend, payload),
+ think_provenance = _think_prov,
cancel_event = cancel_event,
)
)
@@ -21475,6 +21716,9 @@ async def _anthropic_tool_stream(
openai_messages = None,
openai_tools = None,
disable_parallel_tool_use = False,
+ parse_think = True,
+ think_provenance = None,
+ count_template_kwargs = None,
):
"""Streaming response for the tool-calling path."""
_sentinel = object()
@@ -21490,7 +21734,12 @@ async def _anthropic_tool_stream(
input_tokens = 0
if llama_backend is not None and openai_messages is not None:
input_tokens = await asyncio.to_thread(
- llama_backend.count_chat_tokens, openai_messages, None, openai_tools
+ lambda: llama_backend.count_chat_tokens(
+ openai_messages,
+ None,
+ openai_tools,
+ chat_template_kwargs = count_template_kwargs,
+ )
)
async def _stream():
@@ -21501,7 +21750,9 @@ async def _anthropic_tool_stream(
_tracker = _TrackedCancel(cancel_event, model = model_name, kind = "messages")
_tracker.__enter__()
try:
- emitter = AnthropicStreamEmitter()
+ emitter = AnthropicStreamEmitter(
+ parse_think = parse_think, think_provenance = think_provenance
+ )
for line in emitter.start(message_id, model_name, input_tokens = input_tokens):
yield line
@@ -21511,6 +21762,7 @@ async def _anthropic_tool_stream(
ends_on_tool_use = False
tool_blocks_emitted = 0
drop_until_tool_end = False
+ _span_guard = _ReasoningSpanGuard(think_provenance)
# Last drop-branch keepalive, seeded to stream start so a chatty tool busy past the
# stall window still gets one though its events are dropped.
_last_drop_keepalive = time.monotonic()
@@ -21573,7 +21825,7 @@ async def _anthropic_tool_stream(
# [TOOL_CALLS] trailing prose, which a raw sub corrupts.
if etype == "content":
event = dict(event)
- event["text"] = _strip_tool_xml_for_display(
+ event["text"] = _span_guard.strip(
event["text"],
auto_heal_tool_calls = True,
enabled_tool_names = _display_names,
@@ -21587,6 +21839,7 @@ async def _anthropic_tool_stream(
ends_on_tool_use = True
elif etype == "tool_end":
tool_blocks_emitted += 1
+ _span_guard.tool_end()
# Unsloth ran the tool server-side, so the response no longer ends on a pending
# client action; otherwise stop_reason "tool_use" tells the client to run it again.
ends_on_tool_use = False
@@ -21632,6 +21885,9 @@ async def _anthropic_plain_stream(
model_name,
llama_backend = None,
openai_messages = None,
+ parse_think = True,
+ think_provenance = None,
+ count_template_kwargs = None,
):
"""Streaming response for the no-tool path."""
_sentinel = object()
@@ -21640,7 +21896,11 @@ async def _anthropic_plain_stream(
# makes blocking HTTP calls to llama-server, so run it off the event loop.
input_tokens = 0
if llama_backend is not None and openai_messages is not None:
- input_tokens = await asyncio.to_thread(llama_backend.count_chat_tokens, openai_messages)
+ input_tokens = await asyncio.to_thread(
+ lambda: llama_backend.count_chat_tokens(
+ openai_messages, chat_template_kwargs = count_template_kwargs
+ )
+ )
async def _stream():
# Registered like the tool stream above: this default /v1/messages path decodes on
@@ -21648,7 +21908,9 @@ async def _anthropic_plain_stream(
_tracker = _TrackedCancel(cancel_event, model = model_name, kind = "messages")
_tracker.__enter__()
try:
- emitter = AnthropicStreamEmitter()
+ emitter = AnthropicStreamEmitter(
+ parse_think = parse_think, think_provenance = think_provenance
+ )
for line in emitter.start(message_id, model_name, input_tokens = input_tokens):
yield line
@@ -21737,12 +21999,35 @@ def _anthropic_map_generation_error(e: Exception) -> HTTPException:
return HTTPException(status_code = 500, detail = _friendly_error(e))
-def _collect_anthropic_events(run_gen) -> list:
+_WRAPPED_SO_FAR = "_wrapped_so_far"
+
+
+def _collect_anthropic_events(run_gen, think_provenance = None) -> list:
"""Drain the generator into a list, mapping an upstream 4xx / context
- overflow to a clean Anthropic 400 instead of leaking a 500."""
+ overflow to a clean Anthropic 400 instead of leaking a 500.
+
+ ``think_provenance`` is filled in BY the generator as it runs, so the
+ streamed emitter only ever sees the wraps recorded up to the event it is
+ feeding. A reducer runs after the drain and would instead see the final
+ aggregate -- in a tool loop that lets an early turn's literal ``<think>``
+ claim a later turn's genuine wrap. Stamp the live count on each event so the
+ reducer replays the same ledger the streamed path saw.
+ """
+
+ def _drain():
+ for event in run_gen():
+ if (
+ think_provenance is not None
+ and isinstance(event, dict)
+ and event.get("type") == "content"
+ ):
+ # Content events are freshly built per yield, so stamping them
+ # cannot leak into any shared event constant.
+ event[_WRAPPED_SO_FAR] = int(think_provenance.get("wrapped", 0))
+ yield event
try:
- return list(run_gen())
+ return list(_drain())
except HTTPException:
raise
except Exception as e:
@@ -21768,12 +22053,66 @@ def _anthropic_message_json_response(
)
+def _split_think_segments(text: str, wrap: Optional[dict] = None) -> list:
+ """Ordered ``("thinking" | "text", segment)`` pairs from ``<think>`` markup.
+
+ The local generator folds reasoning_content into the visible text as a
+ single LEADING ``<think>...</think>`` prefix per synthesis turn -- that is
+ the only provenance genuine reasoning ever has. Only that leading block is
+ parsed; any later ``<think>`` is the model quoting the tag (e.g. an XML
+ example) and stays literal text. An unclosed leading ``<think>`` runs to
+ the end of the string (a length-truncated thought has no closing tag).
+ """
+ stripped = text.lstrip()
+ if not stripped.startswith("<think>"):
+ return [("text", text)] if text else []
+ lead_ws = text[: len(text) - len(stripped)]
+ rest = stripped[len("<think>") :]
+ if wrap is not None:
+ # Provenance-backed span: the generator recorded the exact reasoning
+ # length, so a literal "</think>" INSIDE the trace never ends it early.
+ n = int(wrap.get("len", 0))
+ thinking, after = rest[:n], rest[n:]
+ if after.startswith("</think>"):
+ after = after[len("</think>") :]
+ else:
+ close = rest.find("</think>")
+ if close == -1:
+ thinking, after = rest, ""
+ else:
+ thinking, after = rest[:close], rest[close + len("</think>") :]
+ segments: list = []
+ if lead_ws:
+ segments.append(("text", lead_ws))
+ if thinking:
+ segments.append(("thinking", thinking))
+ if after:
+ segments.append(("text", after))
+ return segments
+
+
+def _think_markup_to_blocks(text: str, wrap: Optional[dict] = None) -> list:
+ """Expand one text run into ordered thinking / text response blocks."""
+ blocks: list = []
+ for kind, seg in _split_think_segments(text, wrap):
+ if kind == "thinking":
+ if seg.strip():
+ blocks.append(AnthropicResponseThinkingBlock(thinking = seg))
+ elif seg.strip():
+ # Whitespace only decides emptiness; the delivered text stays
+ # verbatim so formatting-sensitive replies match the streamed path.
+ blocks.append(AnthropicResponseTextBlock(text = seg))
+ return blocks
+
+
def _anthropic_tool_response_from_events(
events,
message_id,
model_name,
disable_parallel_tool_use = False,
openai_tools = None,
+ parse_think = True,
+ think_provenance = None,
):
"""Reduce collected tool events into one non-streaming response.
@@ -21799,12 +22138,21 @@ def _anthropic_tool_response_from_events(
# trailing text. See the stop_reason mapping below.
ends_on_tool_use = False
+ _span_guard = _ReasoningSpanGuard(think_provenance)
+ # Which wrap the guard claimed for the turn that produced each text block.
+ # Presence of the key means "genuine reasoning"; the value may still be None
+ # when the ledger recorded the count but not the span.
+ _block_wrap: dict = {}
+
for event in events:
etype = event.get("type", "")
if etype == "content":
# Strip leaked tool XML (protected helper keeps think rehearsal and trailing prose).
- clean = _strip_tool_xml_for_display(
- event["text"], auto_heal_tool_calls = True, enabled_tool_names = _display_names
+ clean = _span_guard.strip(
+ event["text"],
+ auto_heal_tool_calls = True,
+ enabled_tool_names = _display_names,
+ wrapped_so_far = event.get(_WRAPPED_SO_FAR),
)
new = clean[len(prev_text) :]
prev_text = clean
@@ -21814,6 +22162,11 @@ def _anthropic_tool_response_from_events(
content_blocks[-1].text += new
else:
content_blocks.append(AnthropicResponseTextBlock(text = new))
+ # The wrap belongs to the block that OPENS this turn's span,
+ # not to a later block of the same turn (a client tool_use
+ # can interrupt one turn's text).
+ if _span_guard.claimed and new.startswith("<think>"):
+ _block_wrap[len(content_blocks) - 1] = _span_guard.claimed_wrap
elif etype == "tool_start":
tool_call_id = event["tool_call_id"]
arguments = event.get("arguments", {})
@@ -21835,6 +22188,7 @@ def _anthropic_tool_response_from_events(
ends_on_tool_use = True
elif etype == "tool_end":
prev_text = ""
+ _span_guard.tool_end()
# Server-executed: no longer pending a client action (see above).
ends_on_tool_use = False
elif etype == "metadata":
@@ -21843,6 +22197,28 @@ def _anthropic_tool_response_from_events(
if _fr is not None:
captured_finish_reason = _fr
+ # Split <think> markup out of the accumulated text into typed thinking
+ # blocks, preserving position relative to tool_use blocks. With provenance,
+ # the wrap is the one the span guard already claimed FOR THAT TURN above --
+ # re-deriving it here from the final aggregate would let an earlier turn's
+ # literal <think> consume a later turn's genuine wrap. Without provenance
+ # (test doubles / backends that record none) the leading-tag heuristic
+ # stands.
+ if parse_think:
+ _expanded: list = []
+ for _i, block in enumerate(content_blocks):
+ if think_provenance is None:
+ if isinstance(block, AnthropicResponseTextBlock) and block.text.lstrip().startswith(
+ "<think>"
+ ):
+ _expanded.extend(_think_markup_to_blocks(block.text, None))
+ continue
+ elif _i in _block_wrap:
+ _expanded.extend(_think_markup_to_blocks(block.text, _block_wrap[_i]))
+ continue
+ _expanded.append(block)
+ content_blocks = _expanded
+
# disable_parallel_tool_use: cap the response to at most one tool_use
# block. Keep the first tool_use and drop any later ones.
if disable_parallel_tool_use:
@@ -21875,17 +22251,21 @@ async def _anthropic_tool_non_streaming(
model_name,
disable_parallel_tool_use = False,
openai_tools = None,
+ parse_think = True,
+ think_provenance = None,
cancel_event = None,
):
"""Generate and reduce a tool response entirely off the event loop."""
def _drain_and_build():
return _anthropic_tool_response_from_events(
- _collect_anthropic_events(run_gen),
+ _collect_anthropic_events(run_gen, think_provenance),
message_id,
model_name,
disable_parallel_tool_use = disable_parallel_tool_use,
openai_tools = openai_tools,
+ parse_think = parse_think,
+ think_provenance = think_provenance,
)
return await _run_blocking_generation(
@@ -21896,7 +22276,13 @@ async def _anthropic_tool_non_streaming(
)
-def _anthropic_plain_response_from_events(events, message_id, model_name):
+def _anthropic_plain_response_from_events(
+ events,
+ message_id,
+ model_name,
+ parse_think = True,
+ think_provenance = None,
+):
"""Reduce collected plain events into one non-streaming response."""
text_parts = []
usage = {}
@@ -21917,9 +22303,17 @@ def _anthropic_plain_response_from_events(events, message_id, model_name):
text_parts.append(new)
full_text = "".join(text_parts)
- content_blocks = []
- if full_text:
- content_blocks.append(AnthropicResponseTextBlock(text = full_text))
+ # With provenance, only parse the leading <think> the generator actually
+ # wrapped from reasoning_content; a literal leading tag stays text.
+ _wrapped = think_provenance is None or think_provenance.get("wrapped", 0) > 0
+ _wrap_entries = (think_provenance or {}).get("wraps") or []
+ content_blocks: list = []
+ if full_text and parse_think and _wrapped:
+ content_blocks = _think_markup_to_blocks(
+ full_text, _wrap_entries[0] if _wrap_entries else None
+ )
+ elif full_text:
+ content_blocks = [AnthropicResponseTextBlock(text = full_text)]
stop_reason = openai_finish_to_anthropic_stop(captured_finish_reason, had_tool_calls = False)
@@ -21932,6 +22326,8 @@ async def _anthropic_plain_non_streaming(
run_gen,
message_id,
model_name,
+ parse_think = True,
+ think_provenance = None,
cancel_event = None,
):
"""Generate and reduce a plain response entirely off the event loop."""
@@ -21941,6 +22337,8 @@ async def _anthropic_plain_non_streaming(
_collect_anthropic_events(run_gen),
message_id,
model_name,
+ parse_think = parse_think,
+ think_provenance = think_provenance,
)
return await _run_blocking_generation(
@@ -22233,6 +22631,10 @@ async def _anthropic_passthrough_stream(
cancel_id = None,
disable_parallel_tool_use = False,
auto_heal_tool_calls = None,
+ enable_thinking = None,
+ reasoning_effort = None,
+ preserve_thinking = None,
+ parse_think = True,
):
"""Streaming client-side pass-through: forward tools to llama-server and
translate its stream to Anthropic SSE without executing anything."""
@@ -22250,6 +22652,9 @@ async def _anthropic_passthrough_stream(
repetition_penalty = repetition_penalty,
presence_penalty = presence_penalty,
tool_choice = tool_choice,
+ chat_template_kwargs = _reasoning_template_kwargs(
+ llama_backend, enable_thinking, reasoning_effort, preserve_thinking
+ ),
backend_ctx = llama_backend.context_length,
stream_options = {"include_usage": True},
markup = getattr(llama_backend, "markup_profile", None),
@@ -22258,9 +22663,18 @@ async def _anthropic_passthrough_stream(
# Prompt-token count for message_start.usage.input_tokens. count_chat_tokens
# makes blocking HTTP calls to llama-server, so run it off the event loop.
# Pass the tools through so tool-schema tokens are counted (otherwise the
- # streaming input_tokens undercounts vs the non-stream / count_tokens paths).
+ # streaming input_tokens undercounts vs the non-stream / count_tokens paths),
+ # and the same reasoning kwargs generation renders with, so the count
+ # describes the actual prompt on switchable reasoning templates.
input_tokens = await asyncio.to_thread(
- llama_backend.count_chat_tokens, openai_messages, None, openai_tools
+ lambda: llama_backend.count_chat_tokens(
+ openai_messages,
+ None,
+ openai_tools,
+ chat_template_kwargs = _reasoning_template_kwargs(
+ llama_backend, enable_thinking, reasoning_effort, preserve_thinking
+ ),
+ )
)
# cancel_id mirrors the OpenAI passthrough so a per-run cancel POST
@@ -22282,7 +22696,7 @@ async def _anthropic_passthrough_stream(
# registered until restart, 409-ing every swap. Ahead of the first yield, so
# the opening lines are covered as well.
_tracker.__enter__()
- emitter = AnthropicPassthroughEmitter()
+ emitter = AnthropicPassthroughEmitter(reasoning_as_thinking = parse_think)
# Promote text-form tool calls (declared client tools only) into tool_use blocks;
# verbatim when healing is off or no tools. tool_choice is already OpenAI-shaped.
# Sanitized catalog, not the caller's: a tool dropped for unsafe markup never reached
@@ -22471,6 +22885,10 @@ async def _anthropic_passthrough_non_streaming(
nudge_tool_calls = None,
request: Optional[Request] = None,
cancel_event = None,
+ enable_thinking = None,
+ reasoning_effort = None,
+ preserve_thinking = None,
+ parse_think = True,
):
"""Non-streaming client-side pass-through.
@@ -22493,6 +22911,9 @@ async def _anthropic_passthrough_non_streaming(
repetition_penalty = repetition_penalty,
presence_penalty = presence_penalty,
tool_choice = tool_choice,
+ chat_template_kwargs = _reasoning_template_kwargs(
+ llama_backend, enable_thinking, reasoning_effort, preserve_thinking
+ ),
backend_ctx = llama_backend.context_length,
markup = getattr(llama_backend, "markup_profile", None),
)
@@ -22593,6 +23014,20 @@ async def _anthropic_passthrough_non_streaming(
content_blocks = []
tool_calls = []
+ # Reasoning first: llama-server splits <think> into reasoning_content on any
+ # turn whose format it can parse, and Anthropic orders thinking ahead of the
+ # answer. Reading only `content` drops the trace and the model looks like it
+ # never thought.
+ reasoning = message.get("reasoning_content") or ""
+ if reasoning.strip():
+ if parse_think:
+ content_blocks.append(AnthropicResponseThinkingBlock(thinking = reasoning))
+ else:
+ # Thinking effectively off: the parser shunted a literal
+ # example into reasoning_content; reconstruct it as text.
+ content_blocks.append(
+ AnthropicResponseTextBlock(text = f"<think>{reasoning}</think>")
+ )
if healed_events:
emitted_tool_uses = 0
for kind, value in healed_events:
diff --git a/studio/backend/tests/test_active_generations.py b/studio/backend/tests/test_active_generations.py
index d089e9ccf7e..670d62395fd 100644
--- a/studio/backend/tests/test_active_generations.py
+++ b/studio/backend/tests/test_active_generations.py
@@ -1753,7 +1753,7 @@ def test_anthropic_passthrough_registers_nothing_until_its_body_starts():
llama_backend = SimpleNamespace(
base_url = "http://127.0.0.1:8080",
context_length = 4096,
- count_chat_tokens = lambda messages, _unused, tools: 7,
+ count_chat_tokens = lambda messages, _unused, tools, **_kwargs: 7,
)
async def _build():
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index adb5322ec60..cc867535122 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -70,9 +70,24 @@ def _emitter_client_text(events: list[str]) -> str:
return text
-def test_anthropic_emitter_closes_reasoning_only_think_block():
+def _emitter_client_thinking(events):
+ thinking = ""
+ for line in events:
+ for raw in line.split("\n"):
+ raw = raw.strip()
+ if not raw.startswith("data: "):
+ continue
+ data = json.loads(raw[len("data: ") :])
+ delta = data.get("delta", {})
+ if delta.get("type") == "thinking_delta":
+ thinking += delta.get("thinking", "")
+ return thinking
+
+
+def test_anthropic_emitter_reasoning_only_becomes_thinking_block():
# Anthropic asks the GGUF generator not to promote reasoning into a duplicate
- # visible fallback, so its final cumulative snapshot only balances the block.
+ # visible fallback; the balanced <think> markup becomes one typed thinking
+ # block with no literal tags leaking to the client.
emitter = AnthropicStreamEmitter()
events = emitter.start("msg_1", "m")
events += emitter.feed({"type": "content", "text": "<think>The capital"})
@@ -82,19 +97,319 @@ def test_anthropic_emitter_closes_reasoning_only_think_block():
)
events += emitter.finish()
- assert _emitter_client_text(events) == "<think>The capital of France is Paris.</think>"
+ assert _emitter_client_thinking(events) == "The capital of France is Paris."
+ assert _emitter_client_text(events) == ""
+ thinking_start = next(e for e in events if '"type": "thinking"' in e)
+ # signature is part of the Anthropic thinking-block shape; strict stream
+ # decoders reject the block start without it.
+ assert '"signature": ""' in thinking_start
-def test_anthropic_emitter_does_not_double_close_balanced_think():
- # A reasoning-then-answer reply already closes its own </think>; the balancer
- # must not append a second one.
+def test_anthropic_emitter_splits_think_from_answer():
+ # A reasoning-then-answer reply: the trace streams as a thinking block, the
+ # answer as a separate text block, tags consumed by the splitter.
emitter = AnthropicStreamEmitter()
events = emitter.start("msg_1", "m")
events += emitter.feed({"type": "content", "text": "<think>Thinking."})
events += emitter.feed({"type": "content", "text": "<think>Thinking.</think>Answer."})
events += emitter.finish()
- assert _emitter_client_text(events) == "<think>Thinking.</think>Answer."
+ assert _emitter_client_thinking(events) == "Thinking."
+ assert _emitter_client_text(events) == "Answer."
+
+
+def test_anthropic_emitter_parse_think_off_keeps_literal_tags():
+ # A non-reasoning model quoting <think> markup (e.g. an XML example) must
+ # deliver it verbatim as text, not have it consumed into a thinking block.
+ emitter = AnthropicStreamEmitter(parse_think = False)
+ events = emitter.start("msg_1", "m")
+ events += emitter.feed({"type": "content", "text": "Use <think>like this</think> tags."})
+ events += emitter.finish()
+
+ assert _emitter_client_thinking(events) == ""
+ assert _emitter_client_text(events) == "Use <think>like this</think> tags."
+
+
+def test_think_parsing_expected_gates_on_capability_and_request():
+ from routes.inference import _think_parsing_expected
+
+ class _Backend:
+ def __init__(
+ self,
+ supports = True,
+ always_on = False,
+ default = True,
+ ):
+ self.supports_reasoning = supports
+ self.reasoning_always_on = always_on
+ self.reasoning_default = default
+
+ # Non-reasoning model never parses; always-on always does.
+ assert _think_parsing_expected(_Backend(supports = False), _basic_payload()) is False
+ assert (
+ _think_parsing_expected(_Backend(supports = False, always_on = True), _basic_payload()) is True
+ )
+ # Request-level off wins on a switchable model.
+ assert _think_parsing_expected(_Backend(), _basic_payload(enable_thinking = False)) is False
+ assert _think_parsing_expected(_Backend(), _basic_payload(reasoning_effort = "none")) is False
+ # Unspecified follows the template default; explicit on parses.
+ assert _think_parsing_expected(_Backend(default = False), _basic_payload()) is False
+ assert _think_parsing_expected(_Backend(), _basic_payload()) is True
+ assert _think_parsing_expected(_Backend(), _basic_payload(enable_thinking = True)) is True
+
+ # Effort-dial templates (gpt-oss) map enable_thinking=False to a
+ # low-but-thinking effort; the gate must follow the RESOLVED kwargs and
+ # keep parsing on, disabling only for a genuine "none".
+ class _EffortBackend(_Backend):
+ def _request_reasoning_kwargs(self, enable_thinking, reasoning_effort, preserve_thinking):
+ if reasoning_effort == "none":
+ return {"reasoning_effort": "none"}
+ return {"reasoning_effort": "low" if enable_thinking is False else "high"}
+
+ assert _think_parsing_expected(_EffortBackend(), _basic_payload(enable_thinking = False)) is True
+ assert (
+ _think_parsing_expected(_EffortBackend(), _basic_payload(reasoning_effort = "none")) is False
+ )
+
+
+def test_anthropic_reasoning_args_maps_effort_only_to_enable_thinking():
+ # Effort-only requests must drive enable_thinking-style templates the same
+ # way /v1/responses does: "none" is off, a named level is on. Generation
+ # and the parsing gate read these same args, so they cannot disagree.
+ from routes.inference import _anthropic_reasoning_args
+
+ assert (
+ _anthropic_reasoning_args(_basic_payload(reasoning_effort = "none"))["enable_thinking"]
+ is False
+ )
+ assert (
+ _anthropic_reasoning_args(_basic_payload(reasoning_effort = "high"))["enable_thinking"]
+ is True
+ )
+ assert _anthropic_reasoning_args(_basic_payload())["enable_thinking"] is None
+ # An explicit boolean always wins over the effort mapping.
+ assert (
+ _anthropic_reasoning_args(_basic_payload(enable_thinking = True, reasoning_effort = "none"))[
+ "enable_thinking"
+ ]
+ is True
+ )
+
+
+# thinking x reasoning_effort, every combination. The request model documents
+# "[x-unsloth] reasoning controls ... win over `thinking` when both are
+# present", so reasoning_effort must be resolved BEFORE the native block: an
+# effort decides whenever it is sent, and `thinking` only speaks when neither
+# x-unsloth control did. Pinned as a full cross product so the precedence
+# cannot silently flip back -- reading resolved_enable_thinking() first made
+# `thinking: enabled` + `reasoning_effort: "none"` still think on Qwen3.
+_THINKING_EFFORT_MATRIX = [
+ # (thinking, reasoning_effort, expected enable_thinking)
+ (None, None, None),
+ (None, "none", False),
+ (None, "low", True),
+ (None, "high", True),
+ ("enabled", None, True),
+ ("enabled", "none", False),
+ ("enabled", "low", True),
+ ("enabled", "high", True),
+ ("disabled", None, False),
+ ("disabled", "none", False),
+ ("disabled", "low", True),
+ ("disabled", "high", True),
+]
+
+
[email protected]("thinking_type, effort, expected", _THINKING_EFFORT_MATRIX)
+def test_reasoning_effort_outranks_native_thinking(thinking_type, effort, expected):
+ from routes.inference import _anthropic_reasoning_args
+
+ fields = {}
+ if thinking_type is not None:
+ fields["thinking"] = {"type": thinking_type}
+ if effort is not None:
+ fields["reasoning_effort"] = effort
+ args = _anthropic_reasoning_args(_basic_payload(**fields))
+
+ assert args["enable_thinking"] is expected
+ # The raw effort still reaches effort-dial templates untouched.
+ assert args["reasoning_effort"] == effort
+ # Precedence resolution must not touch preserve_thinking (three-valued:
+ # None keeps llama-server on the load-time --chat-template-kwargs).
+ assert args["preserve_thinking"] is None
+
+
[email protected]("thinking_type, effort, expected", _THINKING_EFFORT_MATRIX)
+def test_thinking_effort_matrix_reaches_enable_thinking_templates(thinking_type, effort, expected):
+ """The matrix as the chat_template_kwargs a Qwen3-style template receives.
+
+ Plain ``enable_thinking`` templates have no effort dial, so
+ _request_reasoning_kwargs reads the boolean only -- if the effort loses to
+ `thinking` upstream it is dropped here with nothing downstream to recover
+ it, and a request that asked for no reasoning gets reasoning anyway.
+ """
+ from routes.inference import _anthropic_reasoning_args, _reasoning_template_kwargs
+
+ class _QwenStyleBackend:
+ """Mirrors LlamaCppBackend._request_reasoning_kwargs for reasoning_style
+ 'enable_thinking': the boolean is the only dial, effort is ignored."""
+
+ def _request_reasoning_kwargs(self, enable_thinking, reasoning_effort, preserve_thinking):
+ kwargs = {}
+ if enable_thinking is not None:
+ kwargs["enable_thinking"] = enable_thinking
+ if preserve_thinking is not None:
+ kwargs["preserve_thinking"] = preserve_thinking
+ return kwargs or None
+
+ fields = {}
+ if thinking_type is not None:
+ fields["thinking"] = {"type": thinking_type}
+ if effort is not None:
+ fields["reasoning_effort"] = effort
+ args = _anthropic_reasoning_args(_basic_payload(**fields))
+ resolved = _reasoning_template_kwargs(
+ _QwenStyleBackend(),
+ args["enable_thinking"],
+ args["reasoning_effort"],
+ args["preserve_thinking"],
+ )
+
+ if expected is None:
+ assert resolved is None
+ else:
+ assert resolved == {"enable_thinking": expected}
+
+
+def test_x_unsloth_enable_thinking_still_outranks_effort_and_thinking():
+ # Precedence WITHIN the x-unsloth group is unchanged: the explicit boolean
+ # is the most specific control and beats both the effort dial and the
+ # native block.
+ from routes.inference import _anthropic_reasoning_args
+
+ args = _anthropic_reasoning_args(
+ _basic_payload(
+ thinking = {"type": "disabled"},
+ enable_thinking = True,
+ reasoning_effort = "none",
+ )
+ )
+ assert args["enable_thinking"] is True
+ args = _anthropic_reasoning_args(
+ _basic_payload(
+ thinking = {"type": "enabled"},
+ enable_thinking = False,
+ reasoning_effort = "high",
+ )
+ )
+ assert args["enable_thinking"] is False
+
+
+def test_replayed_thinking_preserved_only_when_requested():
+ from core.inference.anthropic_compat import anthropic_messages_to_openai
+
+ messages = [
+ {"role": "user", "content": "hi"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "prior trace", "signature": ""},
+ {"type": "text", "text": "the answer"},
+ ],
+ },
+ ]
+ dropped = anthropic_messages_to_openai(messages)
+ assert "reasoning_content" not in dropped[-1]
+ kept = anthropic_messages_to_openai(messages, preserve_thinking = True)
+ assert kept[-1]["reasoning_content"] == "prior trace"
+ assert kept[-1]["content"] == "the answer"
+
+
+def test_anthropic_emitter_only_leading_think_is_reasoning():
+ # Genuine reasoning is only ever a single leading <think> block; a model
+ # quoting the tag mid-answer (an XML example) keeps it as literal text,
+ # even with parsing enabled.
+ emitter = AnthropicStreamEmitter()
+ events = emitter.start("msg_1", "m")
+ events += emitter.feed({"type": "content", "text": "<think>why</think>Use "})
+ events += emitter.feed(
+ {"type": "content", "text": "<think>why</think>Use <think>like this</think> tags."}
+ )
+ events += emitter.finish()
+
+ assert _emitter_client_thinking(events) == "why"
+ assert _emitter_client_text(events) == "Use <think>like this</think> tags."
+
+
+def test_anthropic_emitter_no_leading_think_keeps_all_tags_literal():
+ emitter = AnthropicStreamEmitter()
+ events = emitter.start("msg_1", "m")
+ events += emitter.feed({"type": "content", "text": "Wrap it in <think>"})
+ events += emitter.feed({"type": "content", "text": "Wrap it in <think>...</think> please."})
+ events += emitter.finish()
+
+ assert _emitter_client_thinking(events) == ""
+ assert _emitter_client_text(events) == "Wrap it in <think>...</think> please."
+
+
+def test_split_think_segments_only_parses_leading_block():
+ from routes.inference import _split_think_segments
+ assert _split_think_segments("<think>why</think>Use <think>x</think> tags.") == [
+ ("thinking", "why"),
+ ("text", "Use <think>x</think> tags."),
+ ]
+ assert _split_think_segments("Use <think>x</think> tags.") == [
+ ("text", "Use <think>x</think> tags.")
+ ]
+
+
+def test_anthropic_emitter_keeps_embedded_close_tag_in_trace():
+ # Genuine reasoning ABOUT the </think> syntax contains the literal tag; the
+ # generator-recorded length keeps the whole trace in the thinking block and
+ # the real closing marker never leaks into the answer.
+ trace = "the tag </think> ends a block"
+ prov = {"wrapped": 1, "wraps": [{"len": 0}]}
+ emitter = AnthropicStreamEmitter(think_provenance = prov)
+ events = emitter.start("msg_1", "m")
+ prov["wraps"][0]["len"] = len("the tag </think>")
+ events += emitter.feed({"type": "content", "text": "<think>the tag </think>"})
+ prov["wraps"][0]["len"] = len(trace)
+ events += emitter.feed({"type": "content", "text": f"<think>{trace}"})
+ events += emitter.feed({"type": "content", "text": f"<think>{trace}</think>Answer."})
+ events += emitter.finish()
+
+ assert _emitter_client_thinking(events) == trace
+ assert _emitter_client_text(events) == "Answer."
+
+
+def test_split_think_segments_wrap_length_beats_embedded_tag():
+ from routes.inference import _split_think_segments
+
+ trace = "quote </think> inside"
+ text = f"<think>{trace}</think>Visible."
+ assert _split_think_segments(text, {"len": len(trace)}) == [
+ ("thinking", trace),
+ ("text", "Visible."),
+ ]
+ # Without provenance the first marker still closes (heuristic fallback).
+ assert _split_think_segments(text) == [
+ ("thinking", "quote "),
+ ("text", " inside</think>Visible."),
+ ]
+
+
+def test_anthropic_emitter_holds_back_partial_think_tag():
+ # A tag split across deltas must not leak fragments into the wrong block.
+ emitter = AnthropicStreamEmitter()
+ events = emitter.start("msg_1", "m")
+ events += emitter.feed({"type": "content", "text": "<th"})
+ events += emitter.feed({"type": "content", "text": "<think>Deep"})
+ events += emitter.feed({"type": "content", "text": "<think>Deep</th"})
+ events += emitter.feed({"type": "content", "text": "<think>Deep</think>Out"})
+ events += emitter.finish()
+
+ assert _emitter_client_thinking(events) == "Deep"
+ assert _emitter_client_text(events) == "Out"
def test_streamed_anthropic_tool_use_records_api_monitor_reply(monkeypatch):
@@ -710,20 +1025,22 @@ class TestBuildAnthropicSSEEvent:
class TestAnthropicStreamEmitter:
- def test_start_emits_message_start_and_content_block_start(self):
+ def test_start_emits_message_start_only(self):
+ # Content blocks open lazily on first output, so a turn that begins
+ # with thinking gets a thinking block first, not an empty text block.
e = AnthropicStreamEmitter()
events = e.start("msg_123", "test-model")
- assert len(events) == 2
+ assert len(events) == 1
assert "message_start" in events[0]
- assert "content_block_start" in events[1]
- assert '"type": "text"' in events[1]
- def test_content_delta_emits_text_delta(self):
+ def test_content_delta_opens_text_block_and_emits_delta(self):
e = AnthropicStreamEmitter()
e.start("msg_1", "m")
events = e.feed({"type": "content", "text": "Hello"})
- assert len(events) == 1
- parsed = json.loads(events[0].split("data: ")[1])
+ assert len(events) == 2
+ assert "content_block_start" in events[0]
+ assert '"type": "text"' in events[0]
+ parsed = json.loads(events[1].split("data: ")[1])
assert parsed["delta"]["type"] == "text_delta"
assert parsed["delta"]["text"] == "Hello"
@@ -828,19 +1145,18 @@ class TestAnthropicStreamEmitter:
"result": "done",
}
)
- # content_block_stop (tool) + tool_result + content_block_start (new text)
- assert len(events) == 3
+ # content_block_stop (tool) + tool_result; the next text opens its own block.
+ assert len(events) == 2
assert "content_block_stop" in events[0]
assert "tool_result" in events[1]
parsed = json.loads(events[1].split("data: ")[1])
assert parsed["content"] == "done"
assert parsed["tool_use_id"] == tool_use_id
- assert "content_block_start" in events[2]
- assert '"type": "text"' in events[2]
def test_finish_emits_stop_events(self):
e = AnthropicStreamEmitter()
e.start("msg_1", "m")
+ e.feed({"type": "content", "text": "Hi"})
events = e.finish("end_turn")
# content_block_stop + message_delta + message_stop
assert len(events) == 3
@@ -849,6 +1165,14 @@ class TestAnthropicStreamEmitter:
assert "end_turn" in events[1]
assert "message_stop" in events[2]
+ def test_finish_without_content_skips_block_stop(self):
+ e = AnthropicStreamEmitter()
+ e.start("msg_1", "m")
+ events = e.finish("end_turn")
+ assert len(events) == 2
+ assert "message_delta" in events[0]
+ assert "message_stop" in events[1]
+
def test_metadata_captured_in_finish_usage(self):
e = AnthropicStreamEmitter()
e.start("msg_1", "m")
@@ -878,14 +1202,15 @@ class TestAnthropicStreamEmitter:
)
end_events = e.finish("end_turn")
- assert len(start_events) == 2
- assert len(content_events) == 1
+ assert len(start_events) == 1
+ assert len(content_events) == 2
assert meta_events == []
assert len(end_events) == 3
def test_block_index_increments(self):
e = AnthropicStreamEmitter()
e.start("msg_1", "m")
+ e.feed({"type": "content", "text": "Before"})
assert e.block_index == 0
e.feed(
{
@@ -904,6 +1229,7 @@ class TestAnthropicStreamEmitter:
"result": "ok",
}
)
+ e.feed({"type": "content", "text": "After"})
assert e.block_index == 2
def test_text_after_tool_resets_prev_text(self):
@@ -926,9 +1252,11 @@ class TestAnthropicStreamEmitter:
"result": "ok",
}
)
- # After tool_end, prev_text should be reset
+ # After tool_end, prev_text should be reset; the content opens a fresh
+ # text block and diffs against an empty baseline.
events = e.feed({"type": "content", "text": "After tool"})
- parsed = json.loads(events[0].split("data: ")[1])
+ assert "content_block_start" in events[0]
+ parsed = json.loads(events[1].split("data: ")[1])
assert parsed["delta"]["text"] == "After tool"
@@ -1457,6 +1785,267 @@ class TestAnthropicPassthroughStreamAdapter:
assert message_delta["usage"]["input_tokens"] == 2
assert message_delta["usage"]["output_tokens"] == 4
+ @pytest.mark.parametrize(
+ "reasoning_kwargs, expected",
+ [
+ ({}, None),
+ ({"enable_thinking": True}, {"enable_thinking": True}),
+ ({"enable_thinking": False}, {"enable_thinking": False}),
+ (
+ {"enable_thinking": True, "reasoning_effort": "high"},
+ {"enable_thinking": True, "reasoning_effort": "high"},
+ ),
+ ],
+ )
+ def test_stream_forwards_reasoning_to_llama_server(
+ self, monkeypatch, reasoning_kwargs, expected
+ ):
+ """Without this the reasoning request is dropped and the model stays in
+ its load-time default -- thinking can never be switched on."""
+ import routes.inference as inf_mod
+
+ captured = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ captured["body"] = json.loads(request.content.decode())
+ content = 'data: {"choices": [{"delta": {"content": "hi"}}]}\n\ndata: [DONE]\n\n'
+ return httpx.Response(
+ 200,
+ content = content.encode(),
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ transport = httpx.MockTransport(handler)
+ real_async_client = httpx.AsyncClient
+
+ def _client(*args, **kwargs):
+ return real_async_client(transport = transport, timeout = kwargs.get("timeout", 600))
+
+ monkeypatch.setattr(inf_mod.httpx, "AsyncClient", _client)
+ # Echo the request kwargs back the way the real backend does, so the
+ # test covers the route wiring rather than the backend's style logic.
+ backend = SimpleNamespace(
+ base_url = "http://llama.test",
+ context_length = 4096,
+ count_chat_tokens = lambda *args, **kwargs: 2,
+ _request_reasoning_kwargs = lambda et, re_, pt: (
+ {
+ k: v
+ for k, v in (
+ ("enable_thinking", et),
+ ("reasoning_effort", re_),
+ ("preserve_thinking", pt),
+ )
+ if v is not None
+ }
+ or None
+ ),
+ )
+
+ async def run():
+ response = await _anthropic_passthrough_stream(
+ self._Request(),
+ threading.Event(),
+ backend,
+ [{"role": "user", "content": "hi"}],
+ [{"type": "function", "function": {"name": "lookup", "parameters": {}}}],
+ 0.7,
+ 0.95,
+ 20,
+ 16,
+ "msg_1",
+ "test-model",
+ **reasoning_kwargs,
+ )
+ return await self._collect(response)
+
+ asyncio.run(run())
+ assert captured["body"].get("chat_template_kwargs") == expected
+
+
+class TestReasoningContentReachesTheClient:
+ """llama-server puts the thinking trace in `reasoning_content`, not `content`.
+ Reading only `content` drops it and the model looks like it never thought --
+ which is what every Claude Code turn hit, since tool turns always split."""
+
+ def test_stream_emits_thinking_block(self):
+ from core.inference.anthropic_compat import AnthropicPassthroughEmitter
+
+ emitter = AnthropicPassthroughEmitter()
+ emitter.start("msg_1", "test-model")
+ out = emitter.feed_chunk({"choices": [{"delta": {"reasoning_content": "step one"}}]})
+ out += emitter.feed_chunk({"choices": [{"delta": {"content": "the answer"}}]})
+ blob = "".join(out)
+
+ assert '"type": "thinking"' in blob
+ assert "thinking_delta" in blob
+ assert "step one" in blob
+ # Thinking must open before the text block, the order Anthropic defines.
+ assert blob.index("thinking_delta") < blob.index("text_delta")
+
+ def test_stream_thinking_only_still_emits(self):
+ """A reasoning-only reply must not come back as an empty message."""
+ from core.inference.anthropic_compat import AnthropicPassthroughEmitter
+
+ emitter = AnthropicPassthroughEmitter()
+ emitter.start("msg_1", "test-model")
+ blob = "".join(emitter.feed_chunk({"choices": [{"delta": {"reasoning_content": "only"}}]}))
+ assert "thinking_delta" in blob and "only" in blob
+
+ def test_stream_reasoning_reconstructed_as_text_when_thinking_off(self):
+ """Thinking effectively off: llama-server may still shunt a literal
+ <think> example into reasoning_content; the client asked for those
+ bytes, so they come back as text with the tags restored."""
+ from core.inference.anthropic_compat import AnthropicPassthroughEmitter
+
+ emitter = AnthropicPassthroughEmitter(reasoning_as_thinking = False)
+ emitter.start("msg_1", "test-model")
+ out = emitter.feed_chunk({"choices": [{"delta": {"reasoning_content": "like this"}}]})
+ out += emitter.feed_chunk({"choices": [{"delta": {"content": " is the syntax"}}]})
+ out += emitter.finish()
+ blob = "".join(out)
+
+ assert "thinking_delta" not in blob
+ text = "".join(
+ json.loads(stripped[len("data: ") :])["delta"].get("text", "")
+ for line in out
+ for stripped in (part.strip() for part in line.split("\n"))
+ if stripped.startswith("data: ") and '"text_delta"' in stripped
+ )
+ assert text == "<think>like this</think> is the syntax"
+
+ def test_stream_reconstruction_closes_before_same_chunk_content(self):
+ """One chunk can carry the final reasoning fragment AND content; the
+ closing tag must land between them, not after."""
+ from core.inference.anthropic_compat import AnthropicPassthroughEmitter
+
+ emitter = AnthropicPassthroughEmitter(reasoning_as_thinking = False)
+ emitter.start("msg_1", "test-model")
+ out = emitter.feed_chunk({"choices": [{"delta": {"reasoning_content": "like this"}}]})
+ out += emitter.feed_chunk(
+ {"choices": [{"delta": {"reasoning_content": " too", "content": "Answer"}}]}
+ )
+ out += emitter.finish()
+
+ text = "".join(
+ json.loads(stripped[len("data: ") :])["delta"].get("text", "")
+ for line in out
+ for stripped in (part.strip() for part in line.split("\n"))
+ if stripped.startswith("data: ") and '"text_delta"' in stripped
+ )
+ assert text == "<think>like this too</think>Answer"
+
+ def test_non_streaming_builds_thinking_block(self):
+ from models.inference import (
+ AnthropicMessagesResponse,
+ AnthropicResponseTextBlock,
+ AnthropicResponseThinkingBlock,
+ )
+
+ resp = AnthropicMessagesResponse(
+ model = "m",
+ content = [
+ AnthropicResponseThinkingBlock(thinking = "because 2+2"),
+ AnthropicResponseTextBlock(text = "4"),
+ ],
+ )
+ dumped = resp.model_dump()
+ assert [b["type"] for b in dumped["content"]] == ["thinking", "text"]
+ assert dumped["content"][0]["thinking"] == "because 2+2"
+ # signature is part of Anthropic's shape; empty is fine, missing is not.
+ assert "signature" in dumped["content"][0]
+
+
+class TestAnthropicReasoningArgs:
+ """`/v1/messages` must accept Anthropic's `thinking` block and the
+ x-unsloth reasoning fields instead of silently swallowing them."""
+
+ @staticmethod
+ def _payload(**kwargs):
+ from models.inference import AnthropicMessagesRequest
+ return AnthropicMessagesRequest(
+ model = "m",
+ max_tokens = 16,
+ messages = [{"role": "user", "content": "hi"}],
+ **kwargs,
+ )
+
+ @pytest.mark.parametrize(
+ "kwargs, expected",
+ [
+ ({}, None),
+ ({"thinking": {"type": "enabled", "budget_tokens": 600}}, True),
+ ({"thinking": {"type": "disabled"}}, False),
+ # Anthropic's adaptive tiers: unknown types must mean "think", never 400.
+ ({"thinking": {"type": "adaptive"}}, True),
+ ({"thinking": {"type": "auto"}}, True),
+ ({"enable_thinking": True}, True),
+ ({"enable_thinking": False}, False),
+ # x-unsloth field wins, mirroring enable_tools precedence.
+ ({"thinking": {"type": "disabled"}, "enable_thinking": True}, True),
+ ],
+ )
+ def test_resolved_enable_thinking(self, kwargs, expected):
+ assert self._payload(**kwargs).resolved_enable_thinking() is expected
+
+ def test_reasoning_args_reach_the_generators(self):
+ from routes.inference import _anthropic_reasoning_args
+ payload = self._payload(
+ thinking = {"type": "enabled"},
+ reasoning_effort = "high",
+ preserve_thinking = True,
+ )
+ assert _anthropic_reasoning_args(payload) == {
+ "enable_thinking": True,
+ "reasoning_effort": "high",
+ "preserve_thinking": True,
+ }
+
+ @pytest.mark.parametrize("thinking_type", ["adaptive", "auto", "high", "future_tier"])
+ def test_unknown_thinking_type_never_400s(self, thinking_type):
+ """A strict Literal here regressed real Claude Code traffic to a 400:
+ `thinking.type: Input should be 'enabled' or 'disabled'`."""
+ payload = self._payload(thinking = {"type": thinking_type})
+ assert payload.resolved_enable_thinking() is True
+
+ def test_budget_tokens_accepted_not_rejected(self):
+ """Claude Code always sends budget_tokens; llama-server has no budget,
+ so it must be ignored rather than 400'd."""
+ payload = self._payload(thinking = {"type": "enabled", "budget_tokens": 4096})
+ assert payload.thinking.budget_tokens == 4096
+ assert payload.resolved_enable_thinking() is True
+
+ def test_replayed_thinking_blocks_are_accepted(self):
+ """Anthropic's tool-use protocol makes clients replay thinking blocks
+ with tool results. Rejecting them 422s turn 2 of every thinking session."""
+ from core.inference.anthropic_compat import anthropic_messages_to_openai
+ from models.inference import AnthropicMessagesRequest
+
+ payload = AnthropicMessagesRequest(
+ model = "m",
+ max_tokens = 16,
+ messages = [
+ {"role": "user", "content": "hi"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "let me check", "signature": ""},
+ {"type": "redacted_thinking", "data": "opaque"},
+ {"type": "tool_use", "id": "toolu_1", "name": "ls", "input": {}},
+ ],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "ok"}],
+ },
+ ],
+ )
+ converted = anthropic_messages_to_openai([m.model_dump() for m in payload.messages])
+ assistant = next(m for m in converted if m["role"] == "assistant")
+ # Thinking is dropped from the prompt; the tool call survives.
+ assert "thinking" not in json.dumps(assistant)
+ assert assistant["tool_calls"][0]["function"]["name"] == "ls"
+
# =====================================================================
# Vision guard + PNG normalization (/v1/messages)
@@ -1720,11 +2309,19 @@ class TestAnthropicMessagesToolRouting:
def _gen_plain(**kwargs):
assert kwargs["promote_reasoning_only"] is False
+ # Mirror the real generator: record that the leading <think> was
+ # wrapped from reasoning_content, not literal model text.
+ prov = kwargs.get("reasoning_provenance")
+ if prov is not None:
+ prov["wrapped"] = prov.get("wrapped", 0) + 1
yield f"<think>{reasoning}"
yield f"<think>{reasoning}</think>"
def _gen_tools(**kwargs):
assert kwargs["promote_reasoning_only"] is False
+ prov = kwargs.get("reasoning_provenance")
+ if prov is not None:
+ prov["wrapped"] = prov.get("wrapped", 0) + 1
yield {"type": "content", "text": f"<think>{reasoning}"}
yield {"type": "content", "text": f"<think>{reasoning}</think>"}
@@ -1747,9 +2344,35 @@ class TestAnthropicMessagesToolRouting:
if stream:
body = self._sse_blob(self._consume_response(response))
assert body.count(reasoning) == 1
+ assert "<think>" not in body # markup split into a typed thinking block
else:
body = json.loads(response.body)
- assert body["content"][0]["text"] == f"<think>{reasoning}</think>"
+ assert body["content"][0]["type"] == "thinking"
+ assert body["content"][0]["thinking"] == reasoning
+
+ @pytest.mark.parametrize("stream", [False, True])
+ def test_literal_leading_think_without_provenance_stays_text(self, monkeypatch, stream):
+ # The model answered with literal <think> markup (user asked for it) and
+ # produced no genuine reasoning: the generator recorded no wrap, so the
+ # markup must come back as text, not be consumed into a thinking block.
+ literal = "<think>like this</think>"
+
+ def _gen_plain(**kwargs):
+ assert kwargs.get("reasoning_provenance") is not None
+ yield literal
+
+ _mock_backend(monkeypatch, generate_chat_completion = _gen_plain)
+ payload = _basic_payload(stream = stream)
+
+ response = _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))
+ if stream:
+ body = self._sse_blob(self._consume_response(response))
+ assert '"thinking_delta"' not in body
+ assert literal in body
+ else:
+ body = json.loads(response.body)
+ assert body["content"][0]["type"] == "text"
+ assert body["content"][0]["text"] == literal
def test_tool_use_non_streaming_records_api_monitor_reply(self, monkeypatch):
import routes.inference as inf_mod
@@ -2341,8 +2964,8 @@ def test_resumed_session_thinking_and_null_content_do_not_400():
{"role": "assistant", "content": None}, # tool-only turn serialized as null
],
)
- # Known blocks still parse as their typed models; only the unknown one is loose.
- assert type(req.messages[1].content[0]).__name__ == "AnthropicUnknownBlock"
+ # Known blocks parse as their typed models; replayed thinking is typed too.
+ assert type(req.messages[1].content[0]).__name__ == "AnthropicThinkingBlock"
assert type(req.messages[1].content[1]).__name__ == "AnthropicTextBlock"
assert req.messages[2].content == "" # null coerced
@@ -2360,6 +2983,36 @@ def test_resumed_session_thinking_and_null_content_do_not_400():
)
+def test_user_thinking_block_rejected_not_silently_dropped():
+ # Thinking blocks are typed for assistant replay only; the converter drops
+ # them from user content, so accepting one there would lose the user turn.
+ from pydantic import ValidationError
+ for btype in ("thinking", "redacted_thinking"):
+ with pytest.raises(ValidationError):
+ AnthropicMessagesRequest(
+ model = "x",
+ max_tokens = 16,
+ messages = [{"role": "user", "content": [{"type": btype}]}],
+ )
+
+
+def test_think_markup_split_preserves_text_verbatim():
+ from routes.inference import _think_markup_to_blocks
+
+ # Reasoning-free output passes through untouched, whitespace included.
+ [block] = _think_markup_to_blocks(" indented\n lines\n")
+ assert block.text == " indented\n lines\n"
+
+ # With markup, the trace and the answer keep their own bytes.
+ thinking, text = _think_markup_to_blocks("<think>why</think>\n\n answer\n")
+ assert thinking.thinking == "why"
+ assert text.text == "\n\n answer\n"
+
+ # Whitespace-only segments are dropped rather than emitted as empty blocks.
+ [only_thinking] = _think_markup_to_blocks("<think>why</think>\n\n")
+ assert only_thinking.thinking == "why"
+
+
def test_user_null_content_rejected():
# The null->"" leniency is assistant-only; a null user content must be rejected
# at the boundary, not coerced into an empty prompt and forwarded to the model.
@@ -2838,3 +3491,963 @@ def test_plain_stream_closes_generator_on_disconnect():
asyncio.run(_drive())
assert closed.is_set()
+
+
+def test_display_strip_keeps_provenance_trace_intact():
+ # Genuine reasoning that quotes </think> and then rehearses an enabled call: the
+ # think-aware cleaner closes the block at the quoted tag, so without provenance it
+ # strips the rehearsal out of the trace while wrap["len"] still measures the full
+ # one -- the split then eats the real terminator and the whole answer.
+ from routes.inference import _ReasoningSpanGuard, _split_think_segments
+
+ trace = (
+ 'emit </think> then <tool_call>{"name": "get_weather", "arguments": {}}</tool_call> ends it'
+ )
+ raw = f"<think>{trace}</think>It is sunny."
+ prov = {"wrapped": 1, "wraps": [{"len": len(trace)}]}
+
+ clean = _ReasoningSpanGuard(prov).strip(
+ raw, auto_heal_tool_calls = True, enabled_tool_names = {"get_weather"}
+ )
+ assert clean == raw
+
+ emitter = AnthropicStreamEmitter(think_provenance = prov)
+ events = emitter.start("msg_1", "m")
+ events += emitter.feed({"type": "content", "text": clean})
+ events += emitter.finish()
+ assert _emitter_client_thinking(events) == trace
+ assert _emitter_client_text(events) == "It is sunny."
+ assert _split_think_segments(clean, prov["wraps"][0]) == [
+ ("thinking", trace),
+ ("text", "It is sunny."),
+ ]
+
+
+def test_display_strip_protects_the_wrap_of_each_tool_turn():
+ # A tool loop's second synthesis turn opens its own leading <think> backed by the NEXT
+ # wrap entry, so the guard must advance with the emitter's ledger; measuring turn 2
+ # against wraps[0] would put the boundary mid-trace and strip the rehearsal again.
+ from routes.inference import _ReasoningSpanGuard
+
+ first = "short first turn"
+ second = (
+ 'emit </think> then <tool_call>{"name": "get_weather", "arguments": {}}</tool_call> ends it'
+ )
+ prov = {"wrapped": 2, "wraps": [{"len": len(first)}, {"len": len(second)}]}
+ guard = _ReasoningSpanGuard(prov)
+ names = {"get_weather"}
+
+ turn1 = f"<think>{first}</think>Looking it up."
+ assert guard.strip(turn1, auto_heal_tool_calls = True, enabled_tool_names = names) == turn1
+ guard.tool_end()
+
+ turn2 = f"<think>{second}</think>It is sunny."
+ assert guard.strip(turn2, auto_heal_tool_calls = True, enabled_tool_names = names) == turn2
+
+
+def test_display_strip_still_cleans_tool_xml_after_the_trace():
+ # The protection covers only the recorded span; a leaked call in the answer still goes.
+ from routes.inference import _ReasoningSpanGuard, _strip_tool_xml_for_display
+
+ prov = {"wrapped": 1, "wraps": [{"len": len("plain reasoning")}]}
+ raw = '<think>plain reasoning</think>Done <tool_call>{"name": "get_weather", "arguments": {}}</tool_call>ok'
+ clean = _ReasoningSpanGuard(prov).strip(
+ raw, auto_heal_tool_calls = True, enabled_tool_names = {"get_weather"}
+ )
+ assert clean == "<think>plain reasoning</think>Done ok"
+ # No provenance -> byte-identical to the plain display strip.
+ assert _ReasoningSpanGuard(None).strip(
+ raw, auto_heal_tool_calls = True, enabled_tool_names = {"get_weather"}
+ ) == _strip_tool_xml_for_display(
+ raw, auto_heal_tool_calls = True, enabled_tool_names = {"get_weather"}
+ )
+
+
+def test_display_strip_leaves_unwrapped_leading_tag_to_the_cleaner():
+ # wrapped == 0: the model typed the tag itself, so behaviour must not change.
+ from routes.inference import _ReasoningSpanGuard, _strip_tool_xml_for_display
+ raw = '<think>literal</think>Done <tool_call>{"name": "get_weather", "arguments": {}}</tool_call>ok'
+ for prov in ({"wrapped": 0, "wraps": []}, None):
+ assert _ReasoningSpanGuard(prov).strip(
+ raw, auto_heal_tool_calls = True, enabled_tool_names = {"get_weather"}
+ ) == _strip_tool_xml_for_display(
+ raw, auto_heal_tool_calls = True, enabled_tool_names = {"get_weather"}
+ )
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# SSE grammar conformance
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+def _parse_anthropic_sse(lines):
+ """Turn emitter output into (event_name, data) pairs, asserting well-formedness."""
+ events = []
+ blob = "".join(lines)
+ assert "\r" not in blob, "carriage return in SSE: strict parsers split events on \\n\\n"
+ for chunk in blob.split("\n\n"):
+ if not chunk.strip():
+ continue
+ name = data = None
+ for line in chunk.split("\n"):
+ if line.startswith("event: "):
+ name = line[len("event: ") :]
+ elif line.startswith("data: "):
+ data = json.loads(line[len("data: ") :])
+ assert name is not None and data is not None, f"malformed SSE chunk {chunk!r}"
+ events.append((name, data))
+ return events
+
+
+def assert_anthropic_stream_conformant(lines):
+ """Assert the Anthropic Messages streaming grammar and return the blocks.
+
+ A real SDK accumulates deltas into the block its index names, so an index that
+ skips, repeats or arrives with no open block corrupts the message (or raises).
+ This is the guard for that: message_start first, every block opened before it is
+ written to and closed exactly once, indices gapless from 0, message_delta with
+ stop_reason and usage before a final message_stop.
+ """
+ events = _parse_anthropic_sse(lines)
+ assert events, "no events emitted"
+ assert events[0][0] == "message_start", f"first event was {events[0][0]}"
+ assert events[-1][0] == "message_stop", f"last event was {events[-1][0]}"
+
+ blocks = {}
+ open_index = None
+ next_index = 0
+ closed = []
+ saw_message_delta = False
+
+ for name, data in events[1:]:
+ assert data.get("type") == name, f"event {name} carries data.type {data.get('type')}"
+ if name in ("ping", "tool_result"):
+ # tool_result is Studio's own event for a server-executed tool; real
+ # SDKs ignore it, and it must never claim a content block index.
+ assert "index" not in data, "tool_result must not consume a block index"
+ continue
+ if name == "content_block_start":
+ assert not saw_message_delta, "content_block_start after message_delta"
+ assert open_index is None, f"block {open_index} still open"
+ assert (
+ data["index"] == next_index
+ ), f"index {data['index']} out of sequence, expected {next_index}"
+ block = data["content_block"]
+ if block["type"] == "thinking":
+ assert block.get("thinking") == ""
+ assert "signature" in block, "thinking block start needs a signature field"
+ open_index = data["index"]
+ next_index += 1
+ blocks[open_index] = {"type": block["type"], "text": ""}
+ elif name == "content_block_delta":
+ assert open_index is not None, "delta with no open block"
+ assert data["index"] == open_index, f"delta index {data['index']} != {open_index}"
+ delta = data["delta"]
+ expected = {
+ "text_delta": "text",
+ "thinking_delta": "thinking",
+ "signature_delta": "thinking",
+ "input_json_delta": "tool_use",
+ }[delta["type"]]
+ assert (
+ blocks[open_index]["type"] == expected
+ ), f"{delta['type']} inside a {blocks[open_index]['type']} block"
+ blocks[open_index]["text"] += delta.get("text") or delta.get("thinking") or ""
+ elif name == "content_block_stop":
+ assert open_index is not None, "content_block_stop with no open block"
+ assert data["index"] == open_index
+ assert open_index not in closed, f"block {open_index} closed twice"
+ closed.append(open_index)
+ open_index = None
+ elif name == "message_delta":
+ assert not saw_message_delta, "two message_delta events"
+ assert open_index is None, f"message_delta while block {open_index} is open"
+ assert "stop_reason" in data["delta"] and "usage" in data
+ saw_message_delta = True
+ elif name == "message_stop":
+ assert saw_message_delta, "message_stop without message_delta"
+ else:
+ raise AssertionError(f"unexpected event {name}")
+
+ assert open_index is None, f"stream ended with block {open_index} open"
+ assert saw_message_delta, "no message_delta"
+ assert sorted(closed) == list(range(len(closed))), f"indices not gapless from 0: {closed}"
+ return [(blocks[i]["type"], blocks[i]["text"]) for i in sorted(blocks)]
+
+
+def _drive_emitter(
+ chunks,
+ provenance = None,
+ parse_think = True,
+ extra = (),
+):
+ """Feed cumulative content deltas (plus any extra events) through the emitter."""
+ emitter = AnthropicStreamEmitter(parse_think = parse_think, think_provenance = provenance)
+ lines = list(emitter.start("msg_1", "test-model", input_tokens = 3))
+ cumulative = ""
+ for chunk in chunks:
+ cumulative += chunk
+ lines.extend(emitter.feed({"type": "content", "text": cumulative}))
+ for event in extra:
+ lines.extend(emitter.feed(event))
+ lines.extend(emitter.finish())
+ return lines
+
+
+class TestAnthropicStreamGrammar:
+ """The index state machine an Anthropic SDK decodes against.
+
+ Blocks open lazily now, so every index comes from _alloc_block_index rather
+ than an eager bump in start(). A skipped or reused index is a user-visible
+ break: the official SDK accumulates deltas by index.
+ """
+
+ @pytest.mark.parametrize(
+ "text, provenance",
+ [
+ ("plain answer", None),
+ ("<think>trace</think>answer", {"wrapped": 1, "wraps": [{"len": 5}]}),
+ ("<think>unclosed trace", {"wrapped": 1, "wraps": [{"len": 14}]}),
+ ("<think></think>answer", {"wrapped": 1, "wraps": [{"len": 0}]}),
+ ("<think>a </think> b</think>answer", {"wrapped": 1, "wraps": [{"len": 11}]}),
+ ("answer then <think>quoted</think>", {"wrapped": 0, "wraps": []}),
+ ("<think>思考\U0001f9e0</think>答案", {"wrapped": 1, "wraps": [{"len": 3}]}),
+ ],
+ )
+ @pytest.mark.parametrize("split", ["whole", "chars", "halves"])
+ @pytest.mark.parametrize("parse_think", [True, False])
+ def test_grammar_holds_for_every_shape(self, text, provenance, split, parse_think):
+ chunks = {
+ "whole": [text],
+ "chars": list(text),
+ "halves": [text[: len(text) // 2], text[len(text) // 2 :]],
+ }[split]
+ assert_anthropic_stream_conformant(
+ _drive_emitter(
+ [c for c in chunks if c], json.loads(json.dumps(provenance)), parse_think
+ )
+ )
+
+ def test_a_reply_with_no_content_is_still_a_valid_stream(self):
+ """start() no longer opens a block, so an empty generation emits none."""
+ blocks = assert_anthropic_stream_conformant(_drive_emitter([]))
+ assert blocks == []
+
+ @pytest.mark.parametrize(
+ "extra_first",
+ [False, True],
+ )
+ def test_tool_blocks_keep_the_index_sequence(self, extra_first):
+ """A tool call must take the next index, and text after it another one --
+ whether or not text preceded it."""
+ tool = [
+ {
+ "type": "tool_start",
+ "tool_call_id": "call_1",
+ "name": "get_weather",
+ "arguments": '{"city": "SF"}',
+ },
+ {
+ "type": "tool_end",
+ "tool_call_id": "call_1",
+ "name": "get_weather",
+ "result": "sunny",
+ },
+ ]
+ chunks = ["checking"] if extra_first else []
+ blocks = assert_anthropic_stream_conformant(_drive_emitter(chunks, extra = tool))
+ assert [b[0] for b in blocks] == (["text", "tool_use"] if extra_first else ["tool_use"])
+
+ def test_thinking_then_tool_then_text_keeps_thinking_first(self):
+ """Anthropic orders thinking ahead of the tool call it justifies."""
+ provenance = {"wrapped": 1, "wraps": [{"len": len("need the weather")}]}
+ emitter = AnthropicStreamEmitter(parse_think = True, think_provenance = provenance)
+ lines = list(emitter.start("msg_1", "test-model"))
+ lines.extend(emitter.feed({"type": "content", "text": "<think>need the weather</think>"}))
+ lines.extend(
+ emitter.feed(
+ {
+ "type": "tool_start",
+ "tool_call_id": "call_1",
+ "name": "get_weather",
+ "arguments": "{}",
+ }
+ )
+ )
+ lines.extend(
+ emitter.feed(
+ {
+ "type": "tool_end",
+ "tool_call_id": "call_1",
+ "name": "get_weather",
+ "result": "sunny",
+ }
+ )
+ )
+ lines.extend(emitter.feed({"type": "content", "text": "It is sunny"}))
+ lines.extend(emitter.finish())
+ blocks = assert_anthropic_stream_conformant(lines)
+ assert blocks == [
+ ("thinking", "need the weather"),
+ ("tool_use", ""),
+ ("text", "It is sunny"),
+ ]
+
+
+class TestThinkTagSplitAcrossDeltas:
+ """A <think> tag can be cut at any offset by tokenisation, so the emitter
+ holds a trailing partial tag back. Sweeping every split position is the only
+ way to know the hold-back never leaks markup or eats prose."""
+
+ TEXT = "<think>abc</think>def"
+
+ @pytest.mark.parametrize("cut", range(len(TEXT) + 1))
+ def test_two_way_split_at_every_offset(self, cut):
+ provenance = {"wrapped": 1, "wraps": [{"len": 3}]}
+ blocks = assert_anthropic_stream_conformant(
+ _drive_emitter([c for c in (self.TEXT[:cut], self.TEXT[cut:]) if c], provenance)
+ )
+ assert blocks == [("thinking", "abc"), ("text", "def")]
+
+ @pytest.mark.parametrize("first", range(len(TEXT) + 1))
+ def test_three_way_split_at_every_offset(self, first):
+ for second in range(first, len(self.TEXT) + 1):
+ chunks = [
+ c for c in (self.TEXT[:first], self.TEXT[first:second], self.TEXT[second:]) if c
+ ]
+ blocks = assert_anthropic_stream_conformant(
+ _drive_emitter(chunks, {"wrapped": 1, "wraps": [{"len": 3}]})
+ )
+ assert blocks == [
+ ("thinking", "abc"),
+ ("text", "def"),
+ ], f"split at {first},{second} produced {blocks}"
+
+ @pytest.mark.parametrize("cut", range(1, len("<think>")))
+ def test_a_partial_tag_at_end_of_stream_is_literal_text(self, cut):
+ """The model stopped mid-way through something that looked like a tag;
+ those bytes are output, not markup, and must not be swallowed."""
+ held = "<think>"[:cut]
+ blocks = assert_anthropic_stream_conformant(
+ _drive_emitter(["answer " + held], {"wrapped": 0, "wraps": []})
+ )
+ assert blocks == [("text", "answer " + held)]
+
+
+class TestWhitespaceOnlyThinkingIsNotABlock:
+ """Qwen3-style templates render "<think>\\n\\n</think>" on every reply when
+ thinking is off, and llama-server parses that into reasoning_content. Opening
+ a thinking block for it hangs an empty thought off ordinary answers, and the
+ non-streaming reducer already drops it -- so the two paths disagreed."""
+
+ @pytest.mark.parametrize("trace", ["", " ", "\n\n", " \n \t "])
+ def test_streaming_drops_it(self, trace):
+ text = f"<think>{trace}</think>The answer"
+ provenance = {"wrapped": 1, "wraps": [{"len": len(trace)}]}
+ blocks = assert_anthropic_stream_conformant(_drive_emitter([text], provenance))
+ assert blocks == [("text", "The answer")]
+
+ @pytest.mark.parametrize("trace", ["", " ", "\n\n", " \n \t "])
+ def test_streaming_and_non_streaming_agree(self, trace):
+ from routes.inference import _anthropic_plain_response_from_events
+
+ text = f"<think>{trace}</think>The answer"
+ provenance = {"wrapped": 1, "wraps": [{"len": len(trace)}]}
+ streamed = assert_anthropic_stream_conformant(
+ _drive_emitter([text], json.loads(json.dumps(provenance)))
+ )
+ response = _anthropic_plain_response_from_events(
+ iter([text]),
+ "msg_1",
+ "test-model",
+ parse_think = True,
+ think_provenance = json.loads(json.dumps(provenance)),
+ )
+ reduced = [
+ (b["type"], b.get("thinking") or b.get("text", ""))
+ for b in json.loads(response.body)["content"]
+ ]
+ assert streamed == reduced
+
+ def test_a_trace_that_merely_starts_with_whitespace_is_kept_verbatim(self):
+ """Only an entirely blank trace is dropped; real reasoning keeps its
+ leading newlines so the rendered thought matches the model's output."""
+ trace = "\n\nWorking through it"
+ provenance = {"wrapped": 1, "wraps": [{"len": len(trace)}]}
+ blocks = assert_anthropic_stream_conformant(
+ _drive_emitter(list(f"<think>{trace}</think>Answer"), provenance)
+ )
+ assert blocks == [("thinking", trace), ("text", "Answer")]
+
+
+class TestReasoningSurvivesTheWholeChain:
+ """End to end over a fake llama-server stream: the generator folds
+ reasoning_content into <think> markup and records provenance, and the
+ emitter splits it back into typed blocks. The two halves are only correct
+ together, so they are exercised together against the bytes llama-server
+ actually sends."""
+
+ @staticmethod
+ def _backend(monkeypatch, chunks):
+ import contextlib
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ backend._process = object()
+ backend._healthy = True
+ backend._port = 48851
+ backend._api_key = None
+ backend._effective_context_length = 4096
+ backend._supports_reasoning = True
+ backend._reasoning_always_on = False
+ backend._reasoning_style = "enable_thinking"
+ backend._supports_preserve_thinking = False
+
+ @contextlib.contextmanager
+ def fake_stream(
+ _client,
+ _url,
+ payload,
+ _cancel,
+ headers = None,
+ first_token_deadline = None,
+ ):
+ yield type("R", (), {"status_code": 200, "chunks": chunks})()
+
+ monkeypatch.setattr(backend, "_stream_with_retry", fake_stream)
+ monkeypatch.setattr(
+ backend,
+ "_iter_text_cancellable",
+ lambda response, _c, first_token_deadline = None: iter(response.chunks),
+ )
+ monkeypatch.setattr(backend, "_maybe_recover_from_mtp_crash", lambda *a, **k: False)
+ return backend
+
+ @staticmethod
+ def _sse(delta):
+ return "data: " + json.dumps({"choices": [{"index": 0, "delta": delta}]}) + "\n"
+
+ def _run(self, monkeypatch, deltas):
+ backend = self._backend(monkeypatch, [self._sse(d) for d in deltas] + ["data: [DONE]\n"])
+ provenance = {"wrapped": 0}
+ emitter = AnthropicStreamEmitter(parse_think = True, think_provenance = provenance)
+ lines = list(emitter.start("msg_1", "test-model"))
+ for cumulative in backend.generate_chat_completion(
+ messages = [{"role": "user", "content": "hi"}],
+ reasoning_provenance = provenance,
+ ):
+ if isinstance(cumulative, str):
+ lines.extend(emitter.feed({"type": "content", "text": cumulative}))
+ lines.extend(emitter.finish())
+ return assert_anthropic_stream_conformant(lines)
+
+ def test_reasoning_then_answer_becomes_a_thinking_block_and_a_text_block(self, monkeypatch):
+ blocks = self._run(
+ monkeypatch,
+ [
+ {"reasoning_content": "First I "},
+ {"reasoning_content": "check the map."},
+ {"content": "It is "},
+ {"content": "north."},
+ ],
+ )
+ assert blocks == [("thinking", "First I check the map."), ("text", "It is north.")]
+
+ def test_a_reasoning_only_reply_is_not_empty(self, monkeypatch):
+ blocks = self._run(monkeypatch, [{"reasoning_content": "just thinking"}])
+ assert blocks and blocks[0][0] in ("thinking", "text")
+ assert "just thinking" in blocks[0][1]
+
+ def test_a_literal_think_tag_in_content_stays_text(self, monkeypatch):
+ """No reasoning_content, so the generator wraps nothing and provenance
+ stays at zero -- the model merely quoted the tag."""
+ blocks = self._run(
+ monkeypatch,
+ [
+ {"content": "<think>"},
+ {"content": " is the tag"},
+ ],
+ )
+ assert blocks == [("text", "<think> is the tag")]
+
+ def test_a_close_tag_quoted_inside_the_trace_does_not_end_it(self, monkeypatch):
+ blocks = self._run(
+ monkeypatch,
+ [
+ {"reasoning_content": "the closer is </think>"},
+ {"reasoning_content": " and it is quoted"},
+ {"content": "done"},
+ ],
+ )
+ assert blocks == [
+ ("thinking", "the closer is </think> and it is quoted"),
+ ("text", "done"),
+ ]
+
+ def test_an_old_llama_server_that_never_sends_reasoning_content_is_unchanged(self, monkeypatch):
+ """Pre-reasoning_content builds only ever populate `content`."""
+ blocks = self._run(monkeypatch, [{"content": "plain "}, {"content": "answer"}])
+ assert blocks == [("text", "plain answer")]
+
+ def test_a_blank_reasoning_trace_does_not_open_a_thinking_block(self, monkeypatch):
+ """Qwen3 with thinking off renders "<think>\\n\\n</think>" and llama-server
+ reports it as reasoning_content, on every single reply."""
+ blocks = self._run(
+ monkeypatch,
+ [
+ {"reasoning_content": "\n\n"},
+ {"content": "The answer"},
+ ],
+ )
+ assert blocks == [("text", "The answer")]
+
+
+class TestReasoningProvenanceIsBoundToItsSynthesisTurn:
+ """A tool loop's non-streaming reducer runs only after generation finished,
+ so ``think_provenance`` is already at its FINAL aggregate. Attributing wraps
+ by block order there let an early turn's literal ``<think>`` (Qwen3 with
+ thinking off re-emits the closed empty block into `content`, llama.cpp
+ common/chat-peg-parser.cpp discards whitespace-only reasoning so no
+ reasoning_content is reported) consume a LATER turn's genuine wrap: the
+ literal block was rendered as thinking and the real trace was delivered as
+ raw tagged text. The streamed emitter reads the ledger live and never can,
+ so the two paths must agree turn for turn.
+ """
+
+ TOOLS = [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Weather.",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ },
+ }
+ ]
+
+ @staticmethod
+ def _sse(delta):
+ return "data: " + json.dumps({"choices": [{"index": 0, "delta": delta}]}) + "\n"
+
+ @classmethod
+ def _tool_call_sse(cls, call_id, city):
+ return cls._sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": call_id,
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "arguments": json.dumps({"city": city}),
+ },
+ }
+ ]
+ }
+ )
+
+ @classmethod
+ def _backend(cls, monkeypatch, streams):
+ import contextlib
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ backend._process = object()
+ backend._healthy = True
+ backend._port = 48853
+ backend._api_key = None
+ backend._effective_context_length = 4096
+ backend._supports_reasoning = True
+ backend._reasoning_always_on = False
+ backend._reasoning_style = "enable_thinking"
+ backend._supports_preserve_thinking = False
+ _pending = list(streams)
+
+ @contextlib.contextmanager
+ def fake_stream(
+ _client,
+ _url,
+ _payload,
+ _cancel,
+ headers = None,
+ **_kw,
+ ):
+ yield type("R", (), {"status_code": 200, "chunks": _pending.pop(0)})()
+
+ monkeypatch.setattr(backend, "_stream_with_retry", fake_stream)
+ monkeypatch.setattr(
+ backend,
+ "_iter_text_cancellable",
+ lambda response, _c, first_token_deadline = None: iter(response.chunks),
+ )
+ monkeypatch.setattr(backend, "_maybe_recover_from_mtp_crash", lambda *a, **k: False)
+ monkeypatch.setattr(
+ "core.inference.tools.execute_tool", lambda name, arguments, **k: "sunny"
+ )
+ return backend
+
+ def _generator(self, monkeypatch, streams, provenance):
+ backend = self._backend(monkeypatch, streams)
+ return backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "weather?"}],
+ tools = self.TOOLS,
+ max_tool_iterations = len(streams),
+ reasoning_provenance = provenance,
+ )
+
+ def _streamed(self, monkeypatch, streams):
+ provenance = {"wrapped": 0}
+ emitter = AnthropicStreamEmitter(parse_think = True, think_provenance = provenance)
+ lines = list(emitter.start("msg_1", "test-model"))
+ for event in self._generator(monkeypatch, streams, provenance):
+ lines.extend(emitter.feed(event))
+ lines.extend(emitter.finish())
+ return assert_anthropic_stream_conformant(lines)
+
+ def _reduced(self, monkeypatch, streams):
+ from routes.inference import (
+ _anthropic_tool_response_from_events,
+ _collect_anthropic_events,
+ )
+
+ provenance = {"wrapped": 0}
+ gen = self._generator(monkeypatch, streams, provenance)
+ # Exactly what _anthropic_tool_non_streaming does: drain first, reduce after.
+ events = _collect_anthropic_events(lambda: gen, provenance)
+ response = _anthropic_tool_response_from_events(
+ events,
+ "msg_1",
+ "test-model",
+ openai_tools = self.TOOLS,
+ parse_think = True,
+ think_provenance = provenance,
+ )
+ blocks = []
+ for block in json.loads(response.body)["content"]:
+ if block["type"] == "thinking":
+ blocks.append(("thinking", block["thinking"]))
+ elif block["type"] == "tool_use":
+ blocks.append(("tool_use", block["name"]))
+ else:
+ blocks.append(("text", block["text"]))
+ return blocks
+
+ @staticmethod
+ def _norm(blocks):
+ """The stream conformance helper accumulates a tool_use block's
+ input_json_delta, the reducer reports its name; compare the rest."""
+ return [(t, "" if t == "tool_use" else v) for t, v in blocks]
+
+ def _literal_then_genuine(self):
+ return [
+ # Turn 1: the model re-emitted the template's closed think block, so
+ # llama-server reports no reasoning_content and the tags are content.
+ [
+ self._sse({"content": "<think>\n\n</think>\n\nLet me check."}),
+ self._tool_call_sse("call_1", "SF"),
+ "data: [DONE]\n",
+ ],
+ # Turn 2: genuine reasoning, reported as reasoning_content.
+ [
+ self._sse({"reasoning_content": "The tool said sunny, so"}),
+ self._sse({"content": "It is sunny in SF."}),
+ "data: [DONE]\n",
+ ],
+ ]
+
+ def test_a_literal_leading_tag_does_not_steal_a_later_turns_wrap(self, monkeypatch):
+ blocks = self._reduced(monkeypatch, self._literal_then_genuine())
+ assert blocks == [
+ ("text", "<think>\n\n</think>\n\nLet me check."),
+ ("tool_use", "get_weather"),
+ ("thinking", "The tool said sunny, so"),
+ ("text", "It is sunny in SF."),
+ ]
+
+ def test_streaming_and_non_streaming_agree_on_a_mixed_tool_loop(self, monkeypatch):
+ streamed = self._streamed(monkeypatch, self._literal_then_genuine())
+ reduced = self._reduced(monkeypatch, self._literal_then_genuine())
+ assert self._norm(streamed) == self._norm(reduced)
+
+ def test_a_literal_tag_between_two_genuine_turns_keeps_both_traces(self, monkeypatch):
+ """Three turns: wrap, literal, wrap. Block-order attribution handed the
+ literal middle turn the SECOND wrap and left the third turn's real trace
+ as tagged text."""
+ streams = [
+ [
+ self._sse({"reasoning_content": "first I check"}),
+ self._tool_call_sse("call_1", "SF"),
+ "data: [DONE]\n",
+ ],
+ [
+ self._sse({"content": "<think>\n\n</think>\n\nOne more."}),
+ self._tool_call_sse("call_2", "LA"),
+ "data: [DONE]\n",
+ ],
+ [
+ self._sse({"reasoning_content": "both are sunny"}),
+ self._sse({"content": "Both cities are sunny."}),
+ "data: [DONE]\n",
+ ],
+ ]
+ expected = [
+ ("thinking", "first I check"),
+ ("tool_use", "get_weather"),
+ ("text", "<think>\n\n</think>\n\nOne more."),
+ ("tool_use", "get_weather"),
+ ("thinking", "both are sunny"),
+ ("text", "Both cities are sunny."),
+ ]
+ assert self._reduced(monkeypatch, streams) == expected
+ assert self._norm(self._streamed(monkeypatch, streams)) == self._norm(expected)
+
+ def test_two_genuine_turns_still_map_in_order(self, monkeypatch):
+ """The ordinary case must be untouched: each turn keeps its own trace."""
+ streams = [
+ [
+ self._sse({"reasoning_content": "look it up"}),
+ self._tool_call_sse("call_1", "SF"),
+ "data: [DONE]\n",
+ ],
+ [
+ self._sse({"reasoning_content": "report it"}),
+ self._sse({"content": "Sunny."}),
+ "data: [DONE]\n",
+ ],
+ ]
+ expected = [
+ ("thinking", "look it up"),
+ ("tool_use", "get_weather"),
+ ("thinking", "report it"),
+ ("text", "Sunny."),
+ ]
+ assert self._reduced(monkeypatch, streams) == expected
+ assert self._norm(self._streamed(monkeypatch, streams)) == self._norm(expected)
+
+
+class TestALiteralTagAfterBlankSpaceIsNotDuplicated:
+ """A reply that opens with a blank line and then quotes ``<think>`` -- the
+ shape llama-server returns for a thinking model under
+ ``--reasoning-format none``, where nothing is split into reasoning_content.
+ The leading run was emitted, then emitted AGAIN as part of the literal-text
+ fallback, so the client saw it twice."""
+
+ @pytest.mark.parametrize("lead", ["\n", "\n\n", " ", " \n\t"])
+ @pytest.mark.parametrize("split", ["one", "chars"])
+ def test_the_leading_run_is_delivered_exactly_once(self, lead, split):
+ text = f"{lead}<think> is the tag you asked about."
+ chunks = [text] if split == "one" else list(text)
+ blocks = assert_anthropic_stream_conformant(
+ _drive_emitter(chunks, {"wrapped": 0, "wraps": []})
+ )
+ assert blocks == [("text", text)]
+
+ def test_a_genuine_trace_after_a_blank_line_still_parses(self):
+ """Only the literal branch was doubling; the provenance-backed one
+ already dropped the consumed run."""
+ provenance = {"wrapped": 1, "wraps": [{"len": 5}]}
+ blocks = assert_anthropic_stream_conformant(
+ _drive_emitter(["\n\n<think>trace</think>Answer"], provenance)
+ )
+ assert blocks == [("text", "\n\n"), ("thinking", "trace"), ("text", "Answer")]
+
+
+class TestPreserveThinkingHonoursTheBackendDefault:
+ """An omitted `preserve_thinking` must follow the LOADED template's default.
+
+ llama-server merges chat_template_kwargs per key, so a request that omits
+ preserve_thinking leaves the launch-time --chat-template-kwargs value active
+ (llama.cpp common/chat.cpp `extra_context`). Coercing the omission to False
+ on the conversion side stripped the reasoning_content that same template was
+ still being told to render: on a preserve-by-default family the replayed
+ thinking silently vanished from the prompt. Counting shares the resolver so
+ the total keeps describing the prompt generation actually builds.
+ """
+
+ TRACE = "The user prefers metric units."
+
+ MESSAGES = [
+ {"role": "user", "content": "How far is the moon?"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": TRACE, "signature": ""},
+ {"type": "text", "text": "About 384,400 km."},
+ ],
+ },
+ {"role": "user", "content": "And the sun?"},
+ ]
+
+ @staticmethod
+ def _payload(**fields):
+ base = {"max_tokens": 16, "messages": TestPreserveThinkingHonoursTheBackendDefault.MESSAGES}
+ base.update(fields)
+ return AnthropicMessagesRequest(**base)
+
+ @staticmethod
+ def _backend(default):
+ from types import SimpleNamespace
+ return SimpleNamespace(
+ supports_preserve_thinking = True,
+ preserve_thinking_default = default,
+ )
+
+ @pytest.mark.parametrize(
+ "default, override, expected",
+ [
+ # The regression: omitted on a preserve-by-default model must keep
+ # the block, not drop it.
+ (True, None, True),
+ # Omitted on an off-by-default model still drops (unchanged).
+ (False, None, False),
+ # Explicit values win over the default in both directions and are
+ # unchanged by the resolver.
+ (True, True, True),
+ (True, False, False),
+ (False, True, True),
+ (False, False, False),
+ ],
+ )
+ def test_resolver_is_three_valued(self, default, override, expected):
+ from routes.inference import _anthropic_preserve_thinking
+ resolved = _anthropic_preserve_thinking(
+ self._backend(default), self._payload(preserve_thinking = override)
+ )
+ assert resolved is expected
+
+ def test_none_and_explicit_false_are_distinguishable(self):
+ """`bool()` made these identical; on a default-true backend they must
+ now resolve to opposite values."""
+ from routes.inference import _anthropic_preserve_thinking
+
+ backend = self._backend(True)
+ assert _anthropic_preserve_thinking(backend, self._payload()) is True
+ assert (
+ _anthropic_preserve_thinking(backend, self._payload(preserve_thinking = False)) is False
+ )
+
+ def test_a_backend_without_the_attribute_stays_off(self):
+ """Test doubles and non-reasoning backends lack the property."""
+ from types import SimpleNamespace
+
+ from routes.inference import _anthropic_preserve_thinking
+
+ assert _anthropic_preserve_thinking(SimpleNamespace(), self._payload()) is False
+
+ @pytest.mark.parametrize("default", [True, False])
+ @pytest.mark.parametrize("override", [None, True, False])
+ def test_conversion_and_counting_cannot_drift(self, default, override):
+ """Both routes resolve through the one helper, so the prompt the count
+ prices is the prompt generation renders."""
+ from routes.inference import _anthropic_preserve_thinking
+
+ payload = self._payload(preserve_thinking = override)
+ backend = self._backend(default)
+ resolved = _anthropic_preserve_thinking(backend, payload)
+
+ converted = anthropic_messages_to_openai(
+ [m.model_dump() for m in payload.messages],
+ payload.system,
+ preserve_thinking = resolved,
+ )
+ counted = anthropic_messages_to_openai(
+ [m.model_dump() for m in payload.messages],
+ payload.system,
+ preserve_thinking = _anthropic_preserve_thinking(backend, payload),
+ )
+ assert converted == counted
+
+ assistant = next(m for m in converted if m["role"] == "assistant")
+ expected_kept = override if override is not None else default
+ assert ("reasoning_content" in assistant) is expected_kept
+ if expected_kept:
+ assert assistant["reasoning_content"] == self.TRACE
+ # The answer text is never affected by the preserve decision.
+ assert assistant["content"] == "About 384,400 km."
+
+ @pytest.mark.parametrize(
+ "default, override, expect_block",
+ [(True, None, True), (False, None, False), (True, False, False), (False, True, True)],
+ )
+ def test_the_route_hands_the_block_to_the_generator(
+ self, monkeypatch, default, override, expect_block
+ ):
+ """End to end over /v1/messages and /v1/messages/count_tokens against a
+ deterministic backend double: what reaches the generator is what the
+ counter prices."""
+ import asyncio
+ from types import SimpleNamespace
+
+ import routes.inference as inf_mod
+ from routes.inference import anthropic_count_tokens, anthropic_messages
+
+ seen = {}
+
+ def _gen(**kwargs):
+ seen["messages"] = kwargs["messages"]
+ seen["preserve_thinking"] = kwargs.get("preserve_thinking")
+ yield "ok"
+
+ def _count(
+ messages,
+ system,
+ tools,
+ strict = False,
+ chat_template_kwargs = None,
+ ):
+ seen["count_messages"] = messages
+ return sum(len(str(m.get("reasoning_content") or "")) for m in messages) + 1
+
+ backend = SimpleNamespace(
+ is_loaded = True,
+ is_vision = False,
+ supports_tools = False,
+ supports_tool_passthrough = False,
+ model_identifier = "unsloth/Qwen3.8-8B-GGUF",
+ context_length = 4096,
+ supports_reasoning = True,
+ reasoning_always_on = False,
+ reasoning_default = True,
+ supports_preserve_thinking = True,
+ preserve_thinking_default = default,
+ count_chat_tokens = _count,
+ generate_chat_completion = _gen,
+ generate_chat_completion_with_tools = _gen,
+ effective_parallel_slots = 4,
+ base_url = "http://llama.preserve.test:9999",
+ _request_reasoning_kwargs = lambda et, re_, pt: (
+ {
+ k: v
+ for k, v in (("enable_thinking", et), ("preserve_thinking", pt))
+ if v is not None
+ }
+ or None
+ ),
+ )
+ monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
+
+ class _Request:
+ def __init__(self):
+ self.state = SimpleNamespace()
+ self.url = SimpleNamespace(path = "/v1/messages")
+ self.method = "POST"
+
+ async def is_disconnected(self):
+ return False
+
+ payload = self._payload(preserve_thinking = override)
+ asyncio.run(anthropic_messages(payload, request = _Request(), current_subject = "t"))
+ gen_messages = seen["messages"]
+ assert any(m.get("reasoning_content") for m in gen_messages) is expect_block
+ # An omitted override must stay None on the wire so llama-server keeps
+ # falling back to the launch-time kwarg rather than being pinned here.
+ assert seen["preserve_thinking"] == override
+
+ asyncio.run(anthropic_count_tokens(payload, request = _Request(), current_subject = "t"))
+ assert seen["count_messages"] == gen_messages
diff --git a/studio/backend/tests/test_responses_api.py b/studio/backend/tests/test_responses_api.py
index 693e8321132..8247d1ffd76 100644
--- a/studio/backend/tests/test_responses_api.py
+++ b/studio/backend/tests/test_responses_api.py
@@ -315,6 +315,53 @@ class TestNormaliseResponsesInput:
assert msgs[1].role == "user"
+class TestResponsesReasoning:
+ """`/v1/responses` parsed `reasoning` and dropped it, and never relayed
+ llama-server's `reasoning_content` back -- so Codex could neither turn
+ thinking on nor see it. Mirrors the /v1/messages fix."""
+
+ @staticmethod
+ def _chat_req(reasoning):
+ from routes.inference import _build_chat_request
+ payload = ResponsesRequest(input = "hi", reasoning = reasoning)
+ return _build_chat_request(payload, [ChatMessage(role = "user", content = "hi")], stream = False)
+
+ def test_effort_reaches_the_chat_request(self):
+ req = self._chat_req({"effort": "high"})
+ assert req.reasoning_effort == "high"
+ assert req.enable_thinking is True
+
+ def test_effort_none_disables_thinking(self):
+ """enable_thinking-style templates have no dial, only a boolean."""
+ req = self._chat_req({"effort": "none"})
+ assert req.enable_thinking is False
+
+ def test_absent_reasoning_leaves_model_default(self):
+ req = self._chat_req(None)
+ assert req.reasoning_effort is None
+ assert req.enable_thinking is None
+
+ def test_malformed_reasoning_is_ignored_not_fatal(self):
+ """Never 400 on a shape we don't recognise -- that regressed real
+ Claude Code traffic once already."""
+ for bad in ("high", {"effort": 3}, {}, {"summary": "auto"}, {"effort": "auto"}):
+ req = self._chat_req(bad)
+ assert req.enable_thinking is None
+
+ def test_reasoning_output_item_shape(self):
+ from models.inference import (
+ ResponsesOutputReasoning,
+ ResponsesOutputReasoningContent,
+ )
+
+ item = ResponsesOutputReasoning(
+ content = [ResponsesOutputReasoningContent(text = "because 2+2")]
+ ).model_dump()
+ assert item["type"] == "reasoning"
+ assert item["id"].startswith("rs_")
+ assert item["content"] == [{"type": "reasoning_text", "text": "because 2+2"}]
+
+
if __name__ == "__main__":
import pytest
pytest.main([__file__, "-v"])