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: validate the reasoning controls instead of coercing them (#9595)

Apoze3ace6621d044
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 32eaac613e1..9f88909c080 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2049,7 +2049,11 @@ def resolve_thinking_onto_enable_thinking(request):
when both are given. Shared with counting, which must resolve the reasoning preamble exactly as
the completion does."""
if request.thinking is not None and request.enable_thinking is None:
- request.enable_thinking = request.thinking.type == "enabled"
+ # Derived, not an explicit x-unsloth override: out of model_fields_set so route
+ # precedence still ranks it below the nested controls. Also covers an explicit
+ # null, which pydantic records as set.
+ object.__setattr__(request, "enable_thinking", request.thinking.type == "enabled")
+ request.model_fields_set.discard("enable_thinking")
return request
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 7165cda7ff2..d7baf7b7ae5 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -705,22 +705,6 @@ def _has_openai_tool_history(messages) -> bool:
return False
-def _extra_body_enable_thinking(payload) -> Optional[bool]:
- """``enable_thinking`` sent through the OpenAI SDK's ``extra_body``, or None.
-
- The SDK spreads ``chat_template_kwargs`` into the request body, where ``extra="allow"``
- stashes it in ``model_extra``; every render consumes the typed field instead, so each
- entry point lifts it first.
- """
- extra = getattr(payload, "model_extra", None)
- if not isinstance(extra, dict):
- return None
- template_kwargs = extra.get("chat_template_kwargs")
- if isinstance(template_kwargs, dict) and "enable_thinking" in template_kwargs:
- return bool(template_kwargs["enable_thinking"])
- return None
-
-
def _raise_unsupported_openai_parameter(param: str, message: str) -> None:
raise HTTPException(
status_code = 400,
@@ -4633,19 +4617,18 @@ def _anthropic_reasoning_args(payload) -> dict:
# 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"
+ enable_thinking, reasoning_effort = _resolve_reasoning_controls(
+ payload.enable_thinking, payload.reasoning_effort
+ )
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()
+ # model in its load-time default). A ChatCompletionRequest has already
+ # mapped that block onto the boolean and carries no resolver, so the
+ # sampling gate can share this helper.
+ resolver = getattr(payload, "resolved_enable_thinking", None)
+ if resolver is not None:
+ enable_thinking = resolver()
return {
"enable_thinking": enable_thinking,
"reasoning_effort": reasoning_effort,
@@ -24004,6 +23987,101 @@ async def delete_openai_container(
await client.close()
+_REASONING_EFFORT_VALUES = {"none", "minimal", "low", "medium", "high", "max", "xhigh"}
+
+
+def _valid_reasoning_effort(value) -> Optional[str]:
+ """An effort level the templates understand, else None."""
+ if isinstance(value, str) and value in _REASONING_EFFORT_VALUES:
+ return value
+ return None
+
+
+def _chat_template_reasoning_kwargs(payload) -> dict:
+ """Validated reasoning controls from OpenAI ``extra_body``."""
+ extra = getattr(payload, "model_extra", None)
+ template_kwargs = extra.get("chat_template_kwargs") if isinstance(extra, dict) else None
+ if not isinstance(template_kwargs, dict):
+ return {}
+ controls = {}
+ enable_thinking = template_kwargs.get("enable_thinking")
+ if isinstance(enable_thinking, bool):
+ controls["enable_thinking"] = enable_thinking
+ effort = _valid_reasoning_effort(template_kwargs.get("reasoning_effort"))
+ if effort is not None:
+ controls["reasoning_effort"] = effort
+ preserve = template_kwargs.get("preserve_thinking")
+ if isinstance(preserve, bool):
+ controls["preserve_thinking"] = preserve
+ return controls
+
+
+_CHAT_TEMPLATE_REASONING_KEYS = ("enable_thinking", "reasoning_effort", "preserve_thinking")
+
+
+def _consume_chat_template_reasoning_kwargs(payload) -> None:
+ """Drop the reasoning keys a lift has just taken onto the typed fields, which is what makes the lift a fixed point; every render rebuilds the nested dict from those fields through ``_reasoning_template_kwargs``. Rebinds a filtered copy rather than popping: the dict is the parsed request body, shared with anything else holding it."""
+ extra = getattr(payload, "model_extra", None)
+ template_kwargs = extra.get("chat_template_kwargs") if isinstance(extra, dict) else None
+ if not isinstance(template_kwargs, dict):
+ return
+ if not any(key in template_kwargs for key in _CHAT_TEMPLATE_REASONING_KEYS):
+ return
+ extra["chat_template_kwargs"] = {
+ key: value
+ for key, value in template_kwargs.items()
+ if key not in _CHAT_TEMPLATE_REASONING_KEYS
+ }
+
+
+def _resolve_reasoning_controls(
+ enable_thinking: Optional[bool], reasoning_effort: Optional[str]
+) -> tuple[Optional[bool], Optional[str]]:
+ """Resolve the on/off gate while keeping a compatible effort level."""
+ if reasoning_effort is None:
+ return enable_thinking, None
+ effort_enables_thinking = reasoning_effort != "none"
+ if enable_thinking is None:
+ return effort_enables_thinking, reasoning_effort
+ if enable_thinking != effort_enables_thinking:
+ return enable_thinking, None
+ return enable_thinking, reasoning_effort
+
+
+def _normalize_chat_reasoning_controls(payload) -> None:
+ """Merge typed and nested controls, then remove contradictory state. Consumes what it lifts, so the second call /v1/responses makes inside the chat route is a no-op; otherwise a dropped contradictory effort came back through the nested-effort rescue and reached generation."""
+ nested = _chat_template_reasoning_kwargs(payload)
+ _consume_chat_template_reasoning_kwargs(payload)
+ fields_set = getattr(payload, "model_fields_set", set())
+ typed_enable = payload.enable_thinking if "enable_thinking" in fields_set else None
+ typed_effort = (
+ _valid_reasoning_effort(payload.reasoning_effort)
+ if "reasoning_effort" in fields_set
+ else None
+ )
+
+ if typed_enable is not None or typed_effort is not None:
+ enable_thinking, reasoning_effort = _resolve_reasoning_controls(typed_enable, typed_effort)
+ nested_effort = nested.get("reasoning_effort")
+ if typed_effort is None and nested_effort is not None:
+ _, compatible_effort = _resolve_reasoning_controls(enable_thinking, nested_effort)
+ if compatible_effort is not None:
+ reasoning_effort = compatible_effort
+ elif "enable_thinking" in nested or "reasoning_effort" in nested:
+ enable_thinking, reasoning_effort = _resolve_reasoning_controls(
+ nested.get("enable_thinking"), nested.get("reasoning_effort")
+ )
+ else:
+ # Lowest priority: Anthropic ``thinking``, already mapped onto the boolean.
+ enable_thinking = payload.enable_thinking
+ reasoning_effort = _valid_reasoning_effort(payload.reasoning_effort)
+
+ payload.enable_thinking = enable_thinking
+ payload.reasoning_effort = reasoning_effort
+ if payload.preserve_thinking is None and "preserve_thinking" in nested:
+ payload.preserve_thinking = nested["preserve_thinking"]
+
+
def _fill_recommended_sampling_openai(payload, model_id) -> None:
"""Apply per-model recommended sampling (and any operator UNSLOTH_SAMPLING_* pin) to a
ChatCompletionRequest in place.
@@ -24488,12 +24566,8 @@ async def produce_openai_chat_completions(
llama_backend = get_llama_cpp_backend()
using_gguf = llama_backend.is_loaded
- # Clients that only know the OpenAI shape (data_designer recipe runs, etc.) control
- # the reasoning preamble this way, so lift it onto the typed field the generators read.
- if payload.enable_thinking is None:
- _lifted_enable_thinking = _extra_body_enable_thinking(payload)
- if _lifted_enable_thinking is not None:
- payload.enable_thinking = _lifted_enable_thinking
+ # Lift ``extra_body`` template controls before sampling and generation read them.
+ _normalize_chat_reasoning_controls(payload)
# ── Determine which backend is active ─────────────────────
# Single-model server: any model name serves the loaded model (drop-in
@@ -30836,7 +30910,6 @@ def _responses_tool_output_content(output: Union[str, list]) -> Union[str, list]
_RESPONSES_THINK_OPEN = "<think>"
_RESPONSES_THINK_CLOSE = "</think>"
-_RESPONSES_REASONING_EFFORTS = {"none", "minimal", "low", "medium", "high", "max", "xhigh"}
def _coerce_responses_reasoning_text(value: Any) -> str:
@@ -31344,15 +31417,16 @@ def _build_chat_request(
if payload.parallel_tool_calls is not None:
chat_kwargs["parallel_tool_calls"] = payload.parallel_tool_calls
- # Both Responses paths reach a Chat Completions render, and the streaming
- # pass-through reads the typed field directly rather than re-lifting, so lift here.
+ # ``chat_template_kwargs`` arrives in ``model_extra`` (ResponsesRequest is
+ # ``extra="allow"``), but both Chat Completions paths read the typed fields,
+ # so lift it here to cover streaming and non-streaming alike.
explicit_enable_thinking = False
- _lifted_enable_thinking = _extra_body_enable_thinking(payload)
- if _lifted_enable_thinking is not None:
- chat_kwargs["enable_thinking"] = _lifted_enable_thinking
- explicit_enable_thinking = True
_extra = getattr(payload, "model_extra", None)
if isinstance(_extra, dict):
+ _nested_reasoning = _chat_template_reasoning_kwargs(payload)
+ chat_kwargs.update(_nested_reasoning)
+ if "enable_thinking" in _nested_reasoning:
+ explicit_enable_thinking = True
# auto_heal_tool_calls / nudge_tool_calls are not typed on
# ResponsesRequest; lift them from the extra-body so passthrough
# healing (and the opt-in nudge) honor them on both paths.
@@ -31372,7 +31446,7 @@ def _build_chat_request(
if isinstance(payload.reasoning, dict):
effort = payload.reasoning.get("effort")
- if isinstance(effort, str) and effort in _RESPONSES_REASONING_EFFORTS:
+ if isinstance(effort, str) and effort in _REASONING_EFFORT_VALUES:
if not explicit_enable_thinking:
chat_kwargs["reasoning_effort"] = effort
chat_kwargs["enable_thinking"] = effort != "none"
@@ -31385,7 +31459,9 @@ def _build_chat_request(
if response_format is not None:
chat_kwargs["response_format"] = response_format
- return ChatCompletionRequest(**chat_kwargs)
+ chat_request = ChatCompletionRequest(**chat_kwargs)
+ _normalize_chat_reasoning_controls(chat_request)
+ return chat_request
def _responses_custom_tool_input(arguments: Any) -> str:
@@ -33535,10 +33611,8 @@ async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONRespon
status_code = 503,
detail = "Cannot count tokens for an empty prompt.",
)
- # The same lift the completion applies before it renders.
- enable_thinking = payload.enable_thinking
- if enable_thinking is None:
- enable_thinking = _extra_body_enable_thinking(payload)
+ # The same normalization the completion applies before it renders.
+ _normalize_chat_reasoning_controls(payload)
# Re-checked immediately before the only work that takes the orchestrator's lock:
# everything since the endpoint's entry check awaits, so a chat can have started in
# the gap and would then wait on this count. The GGUF path re-checks for this reason.
@@ -33553,7 +33627,7 @@ async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONRespon
messages,
system_prompt or "",
tools = _tools_to_use,
- enable_thinking = enable_thinking,
+ enable_thinking = payload.enable_thinking,
reasoning_effort = payload.reasoning_effort,
preserve_thinking = payload.preserve_thinking,
)
@@ -33806,6 +33880,7 @@ async def chat_count_tokens(
# llama-server falls back to the load-time --chat-template-kwargs per key a request omits,
# so omitting these prices the template in whatever mode the model was LOADED in.
+ _normalize_chat_reasoning_controls(payload)
_template_kwargs = llama_backend._request_reasoning_kwargs(
payload.enable_thinking,
payload.reasoning_effort,
@@ -34287,8 +34362,9 @@ async def anthropic_messages(
# Anthropic sampling fields are Optional, so None already marks "client omitted".
from utils.inference.inference_config import resolve_effective_sampling
+ _anthropic_model_id = getattr(llama_backend, "model_identifier", None) or model_name
_anthropic_sampling = resolve_effective_sampling(
- getattr(llama_backend, "model_identifier", None) or model_name,
+ _anthropic_model_id,
{
"temperature": payload.temperature,
"top_p": payload.top_p,
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index a4f08335bfe..b315e0f11ed 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -248,13 +248,22 @@ def test_anthropic_reasoning_args_maps_effort_only_to_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
- )
+ # An explicit boolean always wins; a contradictory effort is removed rather than
+ # riding along into model-specific template resolution.
+ assert _anthropic_reasoning_args(
+ _basic_payload(enable_thinking = True, reasoning_effort = "none")
+ ) == {
+ "enable_thinking": True,
+ "reasoning_effort": None,
+ "preserve_thinking": None,
+ }
+ assert _anthropic_reasoning_args(
+ _basic_payload(enable_thinking = False, reasoning_effort = "high")
+ ) == {
+ "enable_thinking": False,
+ "reasoning_effort": None,
+ "preserve_thinking": None,
+ }
# thinking x reasoning_effort, every combination. The request model documents
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index b15a495956c..01af1e2c831 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -4063,7 +4063,7 @@ class _RenderRecordingBackend:
active_model_name = "mlx/model"
def __init__(self):
- self.messages = self.system = self.tools = None
+ self.messages = self.system = self.tools = self.reasoning = None
def count_chat_tokens(
self,
@@ -4073,6 +4073,10 @@ class _RenderRecordingBackend:
):
self.messages, self.system = messages, system_prompt
self.tools = kwargs.get("tools")
+ self.reasoning = {
+ key: kwargs.get(key)
+ for key in ("enable_thinking", "reasoning_effort", "preserve_thinking")
+ }
return 11, "mlx/model"
@@ -4134,6 +4138,26 @@ def test_an_mlx_count_is_served_where_llama_cpp_would_have_refused(monkeypatch):
assert refused.value.status_code == 503
+def test_an_mlx_count_uses_the_shared_nested_reasoning_controls(monkeypatch):
+ backend = _RenderRecordingBackend()
+ _count_route(
+ monkeypatch,
+ backend,
+ messages = [{"role": "user", "content": "hello"}],
+ thinking = {"type": "disabled"},
+ chat_template_kwargs = {
+ "reasoning_effort": "high",
+ "preserve_thinking": True,
+ },
+ )
+
+ assert backend.reasoning == {
+ "enable_thinking": True,
+ "reasoning_effort": "high",
+ "preserve_thinking": True,
+ }
+
+
@pytest.mark.parametrize(
"template, expected_tools",
[
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 9b17d3aa48c..378af06c27e 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -5708,6 +5708,18 @@ def test_chat_count_tokens_collapses_system_turns(monkeypatch):
{"enable_thinking": True, "preserve_thinking": True},
id = "preserve_thinking",
),
+ pytest.param(
+ "reasoning_effort",
+ {"chat_template_kwargs": {"reasoning_effort": "none"}},
+ {"reasoning_effort": "none"},
+ id = "nested_effort",
+ ),
+ pytest.param(
+ "enable_thinking",
+ {"chat_template_kwargs": {"preserve_thinking": True}},
+ {"preserve_thinking": True},
+ id = "nested_preserve_thinking",
+ ),
# Nothing selected: send nothing, so llama-server keeps its load-time defaults.
pytest.param("enable_thinking", {}, None, id = "template_default"),
],
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 0e5b4bdf8dd..76376d357c9 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -10162,6 +10162,45 @@ class TestResponsesChatTemplateKwargs:
chat_req = _build_chat_request(payload, self._messages, stream = False)
assert chat_req.enable_thinking is None
+ @pytest.mark.parametrize("stream", [False, True])
+ def test_nested_reasoning_controls_reach_llama_server(self, stream):
+ payload = ResponsesRequest(
+ model = "local",
+ input = "hi",
+ chat_template_kwargs = {
+ "reasoning_effort": "none",
+ "preserve_thinking": True,
+ },
+ )
+ chat_req = _build_chat_request(payload, self._messages, stream = stream)
+ body = _build_openai_passthrough_body(
+ chat_req,
+ backend_ctx = 4096,
+ llama_backend = _reasoning_backend(
+ reasoning_style = "reasoning_effort",
+ supports_preserve_thinking = True,
+ ),
+ )
+
+ assert chat_req.enable_thinking is False
+ assert body["chat_template_kwargs"] == {
+ "reasoning_effort": "none",
+ "preserve_thinking": True,
+ }
+
+ def test_native_responses_effort_wins_over_nested_effort(self):
+ payload = ResponsesRequest(
+ model = "local",
+ input = "hi",
+ reasoning = {"effort": "high"},
+ chat_template_kwargs = {"reasoning_effort": "none"},
+ )
+
+ chat_req = _build_chat_request(payload, self._messages, stream = True)
+
+ assert chat_req.enable_thinking is True
+ assert chat_req.reasoning_effort == "high"
+
def test_responses_stream_queued_request_sends_keepalive_before_upstream(self, monkeypatch):
import routes.inference as inf_mod
async def _run():
diff --git a/studio/backend/tests/test_responses_tool_passthrough.py b/studio/backend/tests/test_responses_tool_passthrough.py
index 61a5be2315e..5698479114d 100644
--- a/studio/backend/tests/test_responses_tool_passthrough.py
+++ b/studio/backend/tests/test_responses_tool_passthrough.py
@@ -533,6 +533,17 @@ class TestBuildChatRequest:
assert chat_req.enable_thinking is False
+ def test_chat_template_kwargs_enable_thinking_requires_json_boolean(self):
+ payload = ResponsesRequest(
+ input = "hi",
+ chat_template_kwargs = {"enable_thinking": "false"},
+ )
+ messages = [ChatMessage(role = "user", content = "hi")]
+
+ chat_req = _build_chat_request(payload, messages, stream = False)
+
+ assert chat_req.enable_thinking is None
+
def test_reasoning_effort_high_enables_local_thinking(self):
payload = ResponsesRequest(input = "hi", reasoning = {"effort": "high"})
messages = [ChatMessage(role = "user", content = "hi")]
diff --git a/studio/backend/tests/test_sampling_resolution.py b/studio/backend/tests/test_sampling_resolution.py
index f685e68e17c..87e16c5a140 100644
--- a/studio/backend/tests/test_sampling_resolution.py
+++ b/studio/backend/tests/test_sampling_resolution.py
@@ -266,6 +266,203 @@ def test_fill_recommended_sampling_openai_operator_pin_overrides_client(monkeypa
assert payload.temperature == 0.9 # operator pin wins even over an explicit client value
[email protected]("thinking_mode", [True, False])
+def test_chat_route_lifts_harness_template_kwargs_before_sampling(monkeypatch, thinking_mode):
+ """Exercise the DeepSeek Harness request shape through the real chat route.
+
+ The route must lift the extra-body ``chat_template_kwargs`` onto the typed field
+ before sampling is filled; testing the two helpers apart would not pin that order.
+ """
+ import asyncio
+ from types import SimpleNamespace
+
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inference_route
+
+ class _StopAfterSampling(Exception):
+ pass
+
+ async def _no_auto_switch(*_args, **_kwargs):
+ return None
+
+ llama_backend = SimpleNamespace(
+ is_loaded = True,
+ model_identifier = "unsloth/Qwen3.8-27B-GGUF",
+ _is_audio = False,
+ )
+ request = SimpleNamespace(
+ state = SimpleNamespace(skip_api_monitor = True),
+ url = SimpleNamespace(path = "/v1/chat/completions"),
+ method = "POST",
+ scope = {},
+ )
+ payload = ChatCompletionRequest(
+ model = "deepseek-harness-model",
+ messages = [{"role": "user", "content": "hi"}],
+ chat_template_kwargs = {"enable_thinking": thinking_mode},
+ )
+ assert payload.enable_thinking is None
+
+ real_fill = inference_route._fill_recommended_sampling_openai
+
+ def _capture_after_sampling(route_payload, model_id):
+ assert route_payload.enable_thinking is thinking_mode
+ real_fill(route_payload, model_id)
+ raise _StopAfterSampling
+
+ monkeypatch.setattr(inference_route, "_automatic_model_load_may_run", lambda: False)
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _no_auto_switch)
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: llama_backend)
+ monkeypatch.setattr(
+ inference_route, "_fill_recommended_sampling_openai", _capture_after_sampling
+ )
+
+ with pytest.raises(_StopAfterSampling):
+ asyncio.run(inference_route.openai_chat_completions(payload, request, "test-user"))
+
+
+ "request_kwargs, expected_thinking, expected_effort, expected_preserve",
+ [
+ ({"reasoning_effort": "none"}, False, "none", None),
+ ({"enable_thinking": True, "reasoning_effort": "none"}, True, None, None),
+ ({"enable_thinking": False, "reasoning_effort": "high"}, False, None, None),
+ ({"thinking": {"type": "enabled"}, "reasoning_effort": "none"}, False, "none", None),
+ (
+ {
+ "chat_template_kwargs": {
+ "enable_thinking": True,
+ "reasoning_effort": "medium",
+ "preserve_thinking": True,
+ }
+ },
+ True,
+ "medium",
+ True,
+ ),
+ (
+ {
+ "reasoning_effort": "high",
+ "preserve_thinking": False,
+ "chat_template_kwargs": {
+ "enable_thinking": False,
+ "reasoning_effort": "xhigh",
+ "preserve_thinking": True,
+ },
+ },
+ True,
+ "high",
+ False,
+ ),
+ (
+ {"chat_template_kwargs": {"enable_thinking": True, "reasoning_effort": "none"}},
+ True,
+ None,
+ None,
+ ),
+ # bool("false") used to be True here, so the string turned thinking ON. The invalid
+ # nested type is now ignored: nothing reaches generation and the template renders in
+ # its own default.
+ ({"chat_template_kwargs": {"enable_thinking": "false"}}, None, None, None),
+ (
+ {"chat_template_kwargs": {"enable_thinking": False, "reasoning_effort": {}}},
+ False,
+ None,
+ None,
+ ),
+ ],
+)
+def test_chat_route_normalizes_reasoning_effort_before_generation(
+ monkeypatch, request_kwargs, expected_thinking, expected_effort, expected_preserve
+):
+ import asyncio
+ from types import SimpleNamespace
+
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inference_route
+ from state.tool_policy import reset_tool_policy
+
+ captured = {}
+
+ def _generate(**kwargs):
+ captured.update(kwargs)
+ yield "done"
+
+ async def _no_auto_switch(*_args, **_kwargs):
+ return None
+
+ reset_tool_policy()
+ llama_backend = SimpleNamespace(
+ is_loaded = True,
+ is_vision = False,
+ supports_tools = False,
+ supports_reasoning = True,
+ reasoning_always_on = False,
+ _is_audio = False,
+ model_identifier = "unsloth/Qwen3.8-27B-GGUF",
+ context_length = 4096,
+ generate_chat_completion = _generate,
+ )
+
+ class _Request:
+ state = SimpleNamespace(skip_api_monitor = True)
+ url = SimpleNamespace(path = "/v1/chat/completions")
+ method = "POST"
+ scope = {}
+
+ async def is_disconnected(self):
+ return False
+
+ payload = ChatCompletionRequest(
+ model = "local-model",
+ messages = [{"role": "user", "content": "hi"}],
+ **request_kwargs,
+ )
+
+ monkeypatch.setattr(inference_route, "_automatic_model_load_may_run", lambda: False)
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _no_auto_switch)
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: llama_backend)
+
+ response = asyncio.run(
+ inference_route.openai_chat_completions(payload, _Request(), "test-user")
+ )
+
+ assert response.status_code == 200
+ assert captured["enable_thinking"] is expected_thinking
+ assert captured["reasoning_effort"] == expected_effort
+ assert captured["preserve_thinking"] is expected_preserve
+
+
+ "reasoning_style, enable_thinking, reasoning_effort, expected",
+ [
+ ("enable_thinking", True, "none", {"enable_thinking": True}),
+ ("enable_thinking", False, "high", {"enable_thinking": False}),
+ ("reasoning_effort", True, "none", {"reasoning_effort": "high"}),
+ ("reasoning_effort", False, "high", {"reasoning_effort": "low"}),
+ ("enable_thinking_effort", True, "none", {"enable_thinking": True}),
+ ("enable_thinking_effort", False, "high", {"enable_thinking": False}),
+ ],
+)
+def test_conflicting_controls_resolve_before_model_specific_translation(
+ reasoning_style, enable_thinking, reasoning_effort, expected
+):
+ from core.inference.llama_cpp import LlamaCppBackend
+ from routes.inference import _resolve_reasoning_controls
+
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ backend._supports_reasoning = True
+ backend._reasoning_always_on = False
+ backend._reasoning_style = reasoning_style
+ backend._reasoning_effort_levels = ["high", "max"]
+ backend._supports_preserve_thinking = False
+ backend._architecture = None
+
+ resolved = _resolve_reasoning_controls(enable_thinking, reasoning_effort)
+
+ assert backend._request_reasoning_kwargs(*resolved) == expected
+
+
def test_fill_recommended_sampling_completions_body(monkeypatch):
# /v1/completions is a raw proxy: recommendations fill omitted fields, but a field with no
# recommendation and no pin is left absent so llama-server keeps its own default (unlike the
@@ -300,3 +497,272 @@ def test_fill_recommended_sampling_completions_operator_pin(monkeypatch):
assert body["temperature"] == 0.9 # operator pin wins over the client's explicit value
assert body["repeat_penalty"] == 1.2 # repetition pin lands on llama-server's key
assert "repetition_penalty" not in body # never leak the schema field name into the body
+
+
[email protected]("effort", ["hihg", ""])
+def test_count_tokens_rejects_an_effort_the_chat_endpoint_would_reject(effort):
+ from models.inference import ChatCountTokensRequest
+ from pydantic import ValidationError
+ with pytest.raises(ValidationError):
+ ChatCountTokensRequest.model_validate(
+ {"messages": [{"role": "user", "content": "hi"}], "reasoning_effort": effort}
+ )
+
+
+ "reasoning_style, request_kwargs, expected_kwargs",
+ [
+ # An effort dial cannot be turned off, so enable_thinking=False lands on its
+ # lowest level, not "none"; the contradictory "high" used to ride along.
+ (
+ "reasoning_effort",
+ {"enable_thinking": False, "reasoning_effort": "high"},
+ {"reasoning_effort": "low"},
+ ),
+ # The mirror case: the typed boolean wins and the contradictory level goes,
+ # so the template's own default effort applies instead of "none".
+ (
+ "reasoning_effort",
+ {"enable_thinking": True, "reasoning_effort": "none"},
+ {"reasoning_effort": "high"},
+ ),
+ # A boolean-only template never saw the effort either way.
+ (
+ "enable_thinking",
+ {"enable_thinking": False, "reasoning_effort": "high"},
+ {"enable_thinking": False},
+ ),
+ (
+ "enable_thinking",
+ {"enable_thinking": True, "reasoning_effort": "none"},
+ {"enable_thinking": True},
+ ),
+ # Agreeing controls are not touched.
+ (
+ "reasoning_effort",
+ {"enable_thinking": True, "reasoning_effort": "high"},
+ {"reasoning_effort": "high"},
+ ),
+ ],
+)
+def test_contradictory_controls_are_resolved_for_every_family(
+ reasoning_style, request_kwargs, expected_kwargs
+):
+ """The conflict rule changes generation for every model, not one family.
+
+ `_resolve_reasoning_controls` runs before the model-specific translation, so an
+ effort-dial family (gpt-oss and friends) is affected too.
+ """
+ from types import SimpleNamespace
+
+ from core.inference.llama_cpp import LlamaCppBackend
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inference_route
+
+ backend = SimpleNamespace(
+ _supports_reasoning = True,
+ _reasoning_always_on = False,
+ _reasoning_style = reasoning_style,
+ _reasoning_effort_levels = ("none", "low", "medium", "high"),
+ _supports_preserve_thinking = False,
+ _architecture = "gpt-oss",
+ )
+ payload = ChatCompletionRequest(
+ model = "unsloth/gpt-oss-20b-GGUF",
+ messages = [{"role": "user", "content": "hi"}],
+ **request_kwargs,
+ )
+ inference_route._normalize_chat_reasoning_controls(payload)
+
+ assert (
+ LlamaCppBackend._request_reasoning_kwargs(
+ backend, payload.enable_thinking, payload.reasoning_effort, None
+ )
+ == expected_kwargs
+ )
+
+
+ "typed, nested",
+ [
+ ({"enable_thinking": True, "reasoning_effort": "none"}, {"reasoning_effort": "high"}),
+ ({"enable_thinking": False, "reasoning_effort": "high"}, {"reasoning_effort": "none"}),
+ ({"reasoning_effort": "none"}, {"enable_thinking": True, "reasoning_effort": "xhigh"}),
+ ({}, {"enable_thinking": False}),
+ ({}, {"reasoning_effort": "medium"}),
+ ({"enable_thinking": True}, {"reasoning_effort": "medium"}),
+ ],
+)
+def test_normalizing_twice_cannot_change_the_answer(typed, nested):
+ """/v1/responses normalizes the request it builds, then the chat route normalizes it again.
+
+ The first pass writes its result onto the typed fields, so a second pass reads a typed
+ effort of None where the first read the client's, and without consuming what it lifted
+ it took the nested-effort rescue the first deliberately skipped -- handing generation a
+ level the request had already lost the right to.
+ """
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inference_route
+
+ payload = ChatCompletionRequest.model_validate(
+ {
+ "model": "unsloth/Qwen3.8-27B-GGUF",
+ "messages": [{"role": "user", "content": "hi"}],
+ **typed,
+ "chat_template_kwargs": dict(nested),
+ }
+ )
+ inference_route._normalize_chat_reasoning_controls(payload)
+ once = (payload.enable_thinking, payload.reasoning_effort, payload.preserve_thinking)
+ inference_route._normalize_chat_reasoning_controls(payload)
+ twice = (payload.enable_thinking, payload.reasoning_effort, payload.preserve_thinking)
+ inference_route._normalize_chat_reasoning_controls(payload)
+ thrice = (payload.enable_thinking, payload.reasoning_effort, payload.preserve_thinking)
+
+ assert once == twice == thrice
+
+
+def test_normalizing_does_not_mutate_the_clients_nested_dict():
+ """The lift consumes the reasoning keys without reaching through to the parsed body."""
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inference_route
+
+ client_dict = {"enable_thinking": False, "reasoning_effort": "none", "keep_me": 1}
+ payload = ChatCompletionRequest.model_validate(
+ {
+ "model": "unsloth/Qwen3.8-27B-GGUF",
+ "messages": [{"role": "user", "content": "hi"}],
+ "chat_template_kwargs": client_dict,
+ }
+ )
+ inference_route._normalize_chat_reasoning_controls(payload)
+
+ assert client_dict == {"enable_thinking": False, "reasoning_effort": "none", "keep_me": 1}
+ # Unrelated keys survive on the payload; the consumed ones do not.
+ assert payload.model_extra["chat_template_kwargs"] == {"keep_me": 1}
+
+
+ "nested_enable_thinking",
+ [
+ "false", # bool("false") was True, so this used to turn thinking ON
+ "true",
+ 0, # a JSON number used to be coerced, and happened to land on the right answer
+ 1,
+ None,
+ [],
+ {},
+ "",
+ ],
+)
+def test_a_nested_enable_thinking_that_is_not_a_json_boolean_is_ignored(nested_enable_thinking):
+ """Only a real JSON boolean controls thinking, whichever way the wrong type would have read.
+
+ ``bool()`` on the old lift made ``"false"`` mean ON, which is the bug this fixes. It also
+ made ``0`` mean OFF, which happened to be what such a client wanted, so requiring the
+ boolean changes that request too: the value is ignored and the template renders in
+ whatever mode the model was launched in. Both directions are the same rule, and a client
+ is only carried by sending a real boolean.
+ """
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inference_route
+
+ payload = ChatCompletionRequest.model_validate(
+ {
+ "model": "unsloth/Qwen3.8-27B-GGUF",
+ "messages": [{"role": "user", "content": "hi"}],
+ "chat_template_kwargs": {"enable_thinking": nested_enable_thinking},
+ }
+ )
+ inference_route._normalize_chat_reasoning_controls(payload)
+
+ assert payload.enable_thinking is None
+ assert payload.reasoning_effort is None
+ # Consumed either way, so no render sees the value the validation just refused.
+ assert payload.model_extra["chat_template_kwargs"] == {}
+
+
[email protected]("nested_preserve_thinking", ["true", "false", 0, 1, None, [], {}])
+def test_a_nested_preserve_thinking_that_is_not_a_json_boolean_is_ignored(nested_preserve_thinking):
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inference_route
+
+ payload = ChatCompletionRequest.model_validate(
+ {
+ "model": "unsloth/Qwen3.8-27B-GGUF",
+ "messages": [{"role": "user", "content": "hi"}],
+ "chat_template_kwargs": {"preserve_thinking": nested_preserve_thinking},
+ }
+ )
+ inference_route._normalize_chat_reasoning_controls(payload)
+
+ assert payload.preserve_thinking is None
+ assert payload.model_extra["chat_template_kwargs"] == {}
+
+
+def test_an_ignored_nested_control_resolves_exactly_like_omitting_it():
+ """The rule stated as a property: an invalid value is not a third outcome.
+
+ Whatever an invalid nested control does, it has to be indistinguishable from never
+ having sent the key, on every surface that renders a template. Otherwise "ignored"
+ would still be steering generation.
+ """
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inference_route
+
+ def _resolved(nested):
+ payload = ChatCompletionRequest.model_validate(
+ {
+ "model": "unsloth/Qwen3.8-27B-GGUF",
+ "messages": [{"role": "user", "content": "hi"}],
+ **({"chat_template_kwargs": nested} if nested is not None else {}),
+ }
+ )
+ inference_route._normalize_chat_reasoning_controls(payload)
+ return payload.enable_thinking, payload.reasoning_effort, payload.preserve_thinking
+
+ omitted = _resolved(None)
+ for nested in (
+ {"enable_thinking": "false"},
+ {"enable_thinking": 0},
+ {"reasoning_effort": "hihg"},
+ {"reasoning_effort": "HIGH"},
+ {"reasoning_effort": 5},
+ {"preserve_thinking": "true"},
+ {"enable_thinking": "false", "reasoning_effort": "hihg"},
+ ):
+ assert _resolved(nested) == omitted, nested
+
+ # A valid control alongside an invalid one is still honored.
+ assert _resolved({"enable_thinking": "false", "reasoning_effort": "none"}) == (
+ False,
+ "none",
+ None,
+ )
+
+
+def test_an_anthropic_derived_boolean_stays_out_of_the_explicit_field_set():
+ """resolve_thinking_onto_enable_thinking's discard has to actually remove the name.
+
+ It relies on model_fields_set returning the live __pydantic_fields_set__. If a future
+ pydantic returns a copy, the discard becomes a no-op and the derived boolean would
+ outrank the nested controls it is meant to sit below, silently.
+ """
+ from models.inference import ChatCompletionRequest
+
+ payload = ChatCompletionRequest.model_validate(
+ {
+ "model": "unsloth/Qwen3.8-27B-GGUF",
+ "messages": [{"role": "user", "content": "hi"}],
+ "thinking": {"type": "enabled"},
+ "chat_template_kwargs": {"enable_thinking": False},
+ }
+ )
+ assert payload.enable_thinking is True
+ assert "enable_thinking" not in payload.model_fields_set
+
+ from routes import inference as inference_route
+
+ inference_route._normalize_chat_reasoning_controls(payload)
+ # The nested control is the higher-priority source, so it wins over the derived one.
+ assert payload.enable_thinking is False
diff --git a/studio/backend/tests/test_thinking_parameter.py b/studio/backend/tests/test_thinking_parameter.py
index 92e08912cb3..d6b226afa2a 100644
--- a/studio/backend/tests/test_thinking_parameter.py
+++ b/studio/backend/tests/test_thinking_parameter.py
@@ -63,6 +63,7 @@ def test_chat_completion_request_with_thinking_enabled():
assert req.thinking is not None
assert req.thinking.type == "enabled"
assert req.enable_thinking is True
+ assert "enable_thinking" not in req.model_fields_set
def test_chat_completion_request_without_thinking():
@@ -103,4 +104,41 @@ def test_thinking_overrides_enable_thinking_when_both_provided():
)
# enable_thinking is explicitly set, so it takes precedence
assert req.enable_thinking is False
+ assert "enable_thinking" in req.model_fields_set
assert req.thinking.type == "enabled"
+
+
+def test_thinking_mapping_ignores_an_explicitly_null_enable_thinking():
+ """A client that serializes every optional field must not change precedence.
+
+ pydantic records an explicit ``null`` as set, so without the discard the
+ derived value reads as a typed override and outranks the nested controls.
+ """
+ req = ChatCompletionRequest.model_validate(
+ {
+ "model": "test-model",
+ "messages": [{"role": "user", "content": "hello"}],
+ "thinking": {"type": "disabled"},
+ "enable_thinking": None,
+ }
+ )
+ assert req.enable_thinking is False
+ assert "enable_thinking" not in req.model_fields_set
+
+
+def test_explicit_null_and_omitted_enable_thinking_resolve_the_same():
+ from routes.inference import _normalize_chat_reasoning_controls
+
+ body = {
+ "model": "test-model",
+ "messages": [{"role": "user", "content": "hello"}],
+ "thinking": {"type": "disabled"},
+ "chat_template_kwargs": {"reasoning_effort": "high"},
+ }
+ with_null = ChatCompletionRequest.model_validate({**body, "enable_thinking": None})
+ omitted = ChatCompletionRequest.model_validate(dict(body))
+ for payload in (with_null, omitted):
+ _normalize_chat_reasoning_controls(payload)
+
+ assert (with_null.enable_thinking, with_null.reasoning_effort) == (True, "high")
+ assert (omitted.enable_thinking, omitted.reasoning_effort) == (True, "high")