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: resume cut-off replies and structured output on vLLM and SGLang (#15435)

Nilay15569be3e994
diff --git a/studio/INFERENCE_ENGINES.md b/studio/INFERENCE_ENGINES.md
index 0cc7eb5449b..6d34812123b 100644
--- a/studio/INFERENCE_ENGINES.md
+++ b/studio/INFERENCE_ENGINES.md
@@ -52,8 +52,9 @@ version can return multiple calls even with `parallel_tool_calls: false`.
Legacy completions and Anthropic endpoints retain their existing GGUF requirement;
exact token counting for tool-enabled prompts is not available.
-LoRA adapters, audio/video input, structured output, reasoning
-controls and continuation are outside this profile. Custom model code uses the
+Structured output (`response_format`) and continuing a cut-off reply are served by the
+engine; a reply cut off mid-thought cannot be resumed. LoRA adapters, audio/video input
+and reasoning controls are outside this profile. Custom model code uses the
existing trust-remote-code consent setting. Multi-node serving is not configured by Unsloth.
Engine servers honor Unsloth's VRAM budget, capped by the most constrained
selected GPU's measured free-memory fraction, with at least 512 MiB left per GPU for driver allocations.
diff --git a/studio/backend/core/inference/managed_engine.py b/studio/backend/core/inference/managed_engine.py
index 7607f01daaf..237b1a35672 100644
--- a/studio/backend/core/inference/managed_engine.py
+++ b/studio/backend/core/inference/managed_engine.py
@@ -296,6 +296,8 @@ def validate_model(
options["seed"] = seed
if gpu_memory_utilization is not None:
options["gpu_memory_utilization"] = gpu_memory_utilization
+ if engine == "sglang" and generation_prompt_opens_thought(template):
+ options["opens_thought"] = True
if reasoning_parser:
from .llama_cpp import detect_reasoning_flags
options["reasoning_parser"] = reasoning_parser
@@ -494,7 +496,7 @@ def _rocm_visibility(env: dict, gpu_ids) -> dict:
# SGLang raises when its derived gRPC port (HTTP + 10000) exceeds 65535.
_PORT_LIMIT = 55535
# Launch options that change no compiled artifact, so they share the compile cache.
-_UNCACHED_OPTIONS = frozenset(("seed", "gpu_memory_utilization"))
+_UNCACHED_OPTIONS = frozenset(("seed", "gpu_memory_utilization", "opens_thought"))
def _free_port(limit: int | None = _PORT_LIMIT) -> int:
@@ -561,6 +563,57 @@ def _token_file_token(env) -> str | None:
return token or None
+CONTINUATION_FIELDS = {"continue_final_message": True, "add_generation_prompt": False}
+
+
+def generation_prompt_opens_thought(template) -> bool:
+ """R1 distills, QwQ and Qwen3 Thinking-2507 end the generation prompt inside ``<think>``."""
+ if not isinstance(template, str) or "<think>" not in template:
+ return False
+ from jinja2.sandbox import ImmutableSandboxedEnvironment
+
+ def raise_exception(message):
+ raise ValueError(message)
+
+ try:
+ environment = ImmutableSandboxedEnvironment(
+ extensions = ["jinja2.ext.loopcontrols", "jinja2.ext.do"]
+ )
+ environment.globals["raise_exception"] = raise_exception
+ prompt = environment.from_string(template).render(
+ messages = [{"role": "user", "content": "Hi"}],
+ add_generation_prompt = True,
+ bos_token = "",
+ eos_token = "",
+ )
+ except Exception:
+ return False
+ return prompt.rstrip().endswith("<think>")
+
+
+def sglang_prefill(message: dict, opens_thought: bool) -> dict:
+ """SGLang drops the trailing assistant turn, renders a fresh generation prompt and appends only
+ its string content, so a separately sent thought must travel in that content. Without one the
+ content goes as is: where the prompt opens <think>, SGLang's raw text already holds any close."""
+ content = message.get("content")
+ if isinstance(content, list):
+ content = "".join(part.get("text") or "" for part in content if isinstance(part, dict))
+ thought = (message.get("reasoning_content") or message.get("reasoning") or "").strip()
+ if thought:
+ opener = "" if opens_thought else "<think>\n"
+ content = f"{opener}{thought}\n</think>\n\n{content or ''}"
+ rest = {k: v for k, v in message.items() if k not in ("reasoning", "reasoning_content")}
+ return {**rest, "content": content}
+
+
+# The prompt closed the thought, but a forcing parser (deepseek_r1) files the rest as one.
+def fold_reasoning_into_answer(part: dict) -> None:
+ reasoning = part.pop("reasoning", None)
+ reasoning = part.pop("reasoning_content", None) or reasoning
+ if reasoning:
+ part["content"] = reasoning + (part.get("content") or "")
+
+
class ManagedEngine:
def __init__(self, engine: str):
self.engine = engine
@@ -578,6 +631,7 @@ class ManagedEngine:
self._last_output = time.monotonic()
self.base_url = ""
self.reasoning_parser = None
+ self.opens_thought = False
self._guest_environment = None
# A URL-safe token can start with '-', which CLI parsers read as an option.
self.key = "studio-" + secrets.token_urlsafe(32)
@@ -700,6 +754,7 @@ class ManagedEngine:
self.base_url = f"http://127.0.0.1:{port}"
self.model, self.context = model, context or 4096
self.reasoning_parser = (options or {}).get("reasoning_parser")
+ self.opens_thought = bool((options or {}).get("opens_thought"))
stdin = None
if info.get("host") == "wsl":
command, child_env = self._wsl_command(
@@ -1051,6 +1106,13 @@ class ManagedEngine:
fields["reasoning_effort"] = reasoning_effort
return fields
+ def continue_final_message(self, body: dict) -> None:
+ """Resume the trailing assistant turn of ``body["messages"]`` in place."""
+ body.update(CONTINUATION_FIELDS)
+ if self.engine == "sglang" and body.get("messages"):
+ *head, last = body["messages"]
+ body["messages"] = [*head, sglang_prefill(last, self.opens_thought)]
+
def replay_reasoning(
self,
messages,
@@ -1172,13 +1234,10 @@ class ManagedEngine:
)
message["content"] = parts
break
- if params.get("continue_final_message") or (
- not self.reasoning_parser
- and (params.get("enable_thinking") or params.get("preserve_thinking"))
+ if not self.reasoning_parser and (
+ params.get("enable_thinking") or params.get("preserve_thinking")
):
- raise ValueError(
- "Continuation and reasoning controls are unavailable for this engine profile."
- )
+ raise ValueError("Reasoning controls are unavailable for this engine profile.")
from .engine_transport import engine_messages
messages = self.replay_reasoning(engine_messages(messages), params.get("preserve_thinking"))
@@ -1201,6 +1260,7 @@ class ManagedEngine:
"seed",
"stop",
"logit_bias",
+ "response_format",
):
if params.get(key) is not None:
payload[key] = params[key]
@@ -1215,6 +1275,9 @@ class ManagedEngine:
params.get("preserve_thinking"),
)
)
+ continuing = bool(params.get("continue_final_message"))
+ if continuing:
+ self.continue_final_message(payload)
from .engine_transport import stream_chat_events
def cancelled():
@@ -1225,11 +1288,20 @@ class ManagedEngine:
if event.get("usage") and stats_holder is not None:
stats_holder.setdefault("stats", {})["usage"] = event["usage"]
if event.get("error"):
+ error = event["error"] if isinstance(event["error"], dict) else {}
+ constrained = payload.get("response_format", {"type": "text"}) != {"type": "text"}
+ # vLLM: "Grammar error: ...", SGLang: "Failed to compile json grammar: ...".
+ rejected = re.search(r"grammar|schema", str(error.get("message")), re.IGNORECASE)
+ if constrained and rejected and str(error.get("code")).startswith("4"):
+ from .grammar_constraint import ResponseFormatError
+ raise ResponseFormatError(error.get("message") or "Invalid response_format.")
raise RuntimeError("Engine generation failed.")
for choice in event.get("choices", []):
if choice.get("finish_reason") and stats_holder is not None:
stats_holder.setdefault("stats", {})["finish_reason"] = choice["finish_reason"]
delta = choice.get("delta", {})
+ if continuing:
+ fold_reasoning_into_answer(delta)
# The parser splits thinking out; <think> markup is what the route's extractor reads.
reasoning = delta.get("reasoning") or delta.get("reasoning_content")
if reasoning:
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 1225f8355b3..80aa8cb6f8e 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -3570,7 +3570,9 @@ class InferenceOrchestrator:
except EngineHTTPError:
raise
except Exception as exc:
- yield GenStreamError(str(exc), public = True)
+ yield GenStreamError(
+ str(exc), public = True, openai_param = getattr(exc, "openai_param", None)
+ )
return
if not self._ensure_subprocess_alive():
yield GenStreamError("Error: Inference subprocess is not running", public = True)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 0db8890a1cf..f3988fbf827 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -17787,12 +17787,9 @@ async def _managed_engine_request(request):
def _managed_engine_unsupported_controls(payload, model_info = None) -> bool:
- """A spelled-out ``{"type": "text"}`` response_format is the default, not structured output."""
reasoning = (model_info or {}).get("reasoning_flags") is not None
return bool(
payload.use_adapter is not None
- or _response_format_constrains_decoding(payload)
- or payload.continue_final_message
or (
not reasoning
and (
@@ -30313,7 +30310,8 @@ async def produce_openai_chat_completions(
_explicit_studio_tool_loop_requested(payload)
or not _tools_outrank_response_format(payload, payload.tools)
):
- if not model_info.get("is_mlx"):
+ _engine_grammar = model_info.get("engine") in ("vllm", "sglang")
+ if not (model_info.get("is_mlx") or _engine_grammar):
_raise_unsupported_openai_parameter(
"response_format",
"response_format needs a grammar engine, and the transformers backend "
@@ -30333,9 +30331,10 @@ async def produce_openai_chat_completions(
"decoding starts a new document rather than continuing the text before "
"it. Send the turn without continue_final_message.",
)
- await asyncio.get_running_loop().run_in_executor(
- _SCHEMA_VALIDATION_EXECUTOR, _reject_unhonorable_response_format, payload
- )
+ if not _engine_grammar:
+ await asyncio.get_running_loop().run_in_executor(
+ _SCHEMA_VALIDATION_EXECUTOR, _reject_unhonorable_response_format, payload
+ )
# ── Audio TTS path: auto-route to audio generation ────
# Whisper is ASR, not TTS, so it skips this branch and is handled in the audio input path below.
@@ -32787,7 +32786,11 @@ async def produce_openai_chat_completions(
if _managed_engine_unsupported_controls(payload, _sf_model_info):
raise _reject(
400,
- "This engine integration does not support adapters, structured output, continuation or reasoning controls.",
+ "This engine integration does not support adapters or reasoning controls.",
+ )
+ if _continue_final_message(payload, thought = True) and not _continue_final_message(payload):
+ raise _reject(
+ 400, "This engine cannot resume a response that stopped mid-thought. Use Retry."
)
from routes.managed_engine_chat import managed_tool_chat
diff --git a/studio/backend/routes/managed_engine_chat.py b/studio/backend/routes/managed_engine_chat.py
index 78d65631f68..e85568d0917 100644
--- a/studio/backend/routes/managed_engine_chat.py
+++ b/studio/backend/routes/managed_engine_chat.py
@@ -16,8 +16,10 @@ from fastapi.responses import JSONResponse
from core.inference.engine_transport import engine_messages, engine_request_timeout
from core.inference.inference_gate import gated_async_client
+from core.inference.managed_engine import fold_reasoning_into_answer
from core.inference.http_stream import closing_response_lines
from core.inference.studio_tool_loop import ToolLoopPolicy, ToolLoopRun, stream_with_studio_tools
+from utils.api_errors import openai_error_body
class ManagedToolTransport:
@@ -32,8 +34,10 @@ class ManagedToolTransport:
*,
preserve_thinking = None,
message_fitter = None,
+ continuing = False,
):
self.client, self.engine, self.body = client, engine, body
+ self._continuing = continuing
self._preserve_thinking = preserve_thinking
self._message_fitter = message_fitter
# The tool loop keeps a turn's reasoning_content on the assistant message only when asked.
@@ -55,6 +59,9 @@ class ManagedToolTransport:
}
if max_tokens:
body["max_tokens"] = max_tokens
+ continuing = self._continuing and messages[-1].get("role") == "assistant"
+ if continuing:
+ self.engine.continue_final_message(body)
if truncation_line:
yield truncation_line
if tools:
@@ -80,11 +87,22 @@ class ManagedToolTransport:
if cancel_event.is_set():
return
if line.startswith("data:"):
- yield _with_reasoning_content(line)
+ yield _as_answer(line) if continuing else _with_reasoning_content(line)
finally:
await lines.aclose()
+def _as_answer(line: str) -> str:
+ try:
+ event = json.loads(line[5:])
+ except ValueError:
+ return line
+ for choice in event.get("choices") or () if isinstance(event, dict) else ():
+ if isinstance(choice, dict) and isinstance(choice.get("delta"), dict):
+ fold_reasoning_into_answer(choice["delta"])
+ return "data: " + json.dumps(event)
+
+
def _with_reasoning_content(line: str) -> str:
"""vLLM 0.11+ streams thinking as ``reasoning``; Studio's readers take ``reasoning_content``."""
if '"reasoning"' not in line:
@@ -187,6 +205,10 @@ async def managed_tool_chat(
ui_events = api._ui_stream_events_enabled(request)
if tools_on and not api._launcher_tool_default_applies(payload, ui_events):
tools_on = False
+ if api._response_format_constrains_decoding(
+ payload
+ ) and not api._explicit_studio_tool_loop_requested(payload):
+ tools_on = False
if payload.tool_choice == "none":
tools_on = False
mcp_on = (
@@ -224,6 +246,19 @@ async def managed_tool_chat(
)
if tools and api._wants_multiple_choices(payload):
raise reject("Multiple choices are unavailable when Unsloth executes tools.")
+ if tools and api._response_format_constrains_decoding(payload):
+ # The tool loop never forwards response_format; refuse rather than violate it (as GGUF does).
+ message = (
+ "response_format is not supported with Unsloth tool execution; send the request "
+ "without enable_tools or mcp_enabled to use guided decoding."
+ )
+ api.api_monitor.fail(monitor_id, message)
+ raise HTTPException(
+ status_code = 400,
+ detail = openai_error_body(
+ message, status = 400, code = "unsupported_parameter", param = "response_format"
+ ),
+ )
if tools:
api._reject_confirm_gate_without_channel(
payload, ui_events, monitor_id, api._catalog_names(tools)
@@ -287,6 +322,10 @@ async def managed_tool_chat(
body["tools"] = payload.tools
if payload.tool_choice is not None and not tools:
body["tool_choice"] = payload.tool_choice
+ response_format = api._response_format_beside_tools(payload, tools or payload.tools)
+ if response_format is not None:
+ body["response_format"] = response_format
+ continuing = api._continue_final_message(payload)
cancel = api._chat_cancel_event(request)
completion_id = "chatcmpl-" + uuid.uuid4().hex[:12]
@@ -310,6 +349,7 @@ async def managed_tool_chat(
message_fitter = _message_fitter(
payload, engine, public, tools or payload.tools, studio_loop = bool(tools)
),
+ continuing = continuing,
)
stripper = api.ServerToolCallStripper()
stream = None
@@ -326,6 +366,7 @@ async def managed_tool_chat(
tool_choice = payload.tool_choice,
supports_vision = bool(info.get("is_vision")),
promoted_image_parts = promoted_image_parts,
+ continue_final_message = continuing,
),
policy = ToolLoopPolicy(
tools = tools,
@@ -358,6 +399,8 @@ async def managed_tool_chat(
)
if max_tokens:
request_body["max_tokens"] = max_tokens
+ if continuing:
+ engine.continue_final_message(request_body)
response = await client.post(
engine.base_url + "/v1/chat/completions",
headers = engine.headers,
@@ -370,6 +413,8 @@ async def managed_tool_chat(
data["model"] = public
for choice in data.get("choices") or () if isinstance(data, dict) else ():
message = choice.get("message") if isinstance(choice, dict) else None
+ if continuing and isinstance(message, dict):
+ fold_reasoning_into_answer(message)
if isinstance(message, dict) and "reasoning" in message:
reasoning = message.pop("reasoning")
if reasoning and not message.get("reasoning_content"):
diff --git a/studio/backend/tests/test_managed_engine_reasoning.py b/studio/backend/tests/test_managed_engine_reasoning.py
index 3e2a9f01b34..a2b7afafb55 100644
--- a/studio/backend/tests/test_managed_engine_reasoning.py
+++ b/studio/backend/tests/test_managed_engine_reasoning.py
@@ -191,7 +191,7 @@ def test_reasoning_controls_are_refused_only_without_a_parser():
payload, {"engine": "vllm", "reasoning_flags": {"supports_reasoning": True}}
)
payload = payload.model_copy(update = {"continue_final_message": True})
- assert _managed_engine_unsupported_controls(
+ assert not _managed_engine_unsupported_controls(
payload, {"engine": "vllm", "reasoning_flags": {"supports_reasoning": True}}
)
@@ -272,7 +272,9 @@ class _Engine:
engine = "vllm"
context = 2048
reasoning_parser = "qwen3"
+ opens_thought = False
replay_reasoning = ManagedEngine.replay_reasoning
+ continue_final_message = ManagedEngine.continue_final_message
def _tool_payload(**fields):
@@ -344,6 +346,191 @@ def test_tool_loop_keeps_and_replays_reasoning_when_preserving():
assert "reasoning" not in sent[-1]["messages"][1]
+def test_tool_loop_continues_only_the_turn_that_ends_on_the_partial():
+ import asyncio
+
+ from routes.managed_engine_chat import ManagedToolTransport
+
+ sent = []
+
+ class _Response:
+ status_code = 200
+
+ async def aiter_lines(self):
+ yield 'data: {"choices":[{"delta":{"reasoning_content":" upon a time"}}]}'
+
+ async def aclose(self):
+ return None
+
+ class _Stream:
+ async def __aenter__(self):
+ return _Response()
+
+ async def __aexit__(self, *exc):
+ return False
+
+ class _Client:
+ def stream(
+ self,
+ method,
+ url,
+ headers = None,
+ json = None,
+ ):
+ sent.append(json)
+ return _Stream()
+
+ engine = _Engine()
+ engine.base_url, engine.headers = "http://engine", {}
+ transport = ManagedToolTransport(_Client(), engine, {"model": "m"}, continuing = True)
+
+ async def run(messages):
+ lines = transport.stream(
+ messages = messages, tools = None, tool_choice = None, cancel_event = asyncio.Event()
+ )
+ return [json.loads(line[5:])["choices"][0]["delta"] async for line in lines]
+
+ partial = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "Once"}]
+ assert asyncio.run(run(partial)) == [{"content": " upon a time"}]
+ assert sent[-1]["continue_final_message"] is True
+ assert sent[-1]["add_generation_prompt"] is False
+ later = [*partial, {"role": "tool", "tool_call_id": "c", "content": "r"}]
+ assert asyncio.run(run(later)) == [{"reasoning_content": " upon a time"}]
+ assert "continue_final_message" not in sent[-1]
+ assert "add_generation_prompt" not in sent[-1]
+
+
+ "engine_name,parser",
+ [("vllm", "deepseek_r1"), ("vllm", "qwen3"), ("sglang", "deepseek-r1"), ("sglang", "qwen3")],
+)
+def test_a_continued_answer_stays_answer_under_a_forcing_parser(thinking_peer, engine_name, parser):
+ engine, requests = thinking_peer
+ engine.engine, engine.reasoning_parser = engine_name, parser
+ out = "".join(
+ engine.generate(
+ messages = [
+ {"role": "user", "content": "2+2?"},
+ {"role": "assistant", "content": "The sum is"},
+ ],
+ continue_final_message = True,
+ enable_thinking = True,
+ )
+ )
+ assert out == "two plus two\n\n4"
+ assert requests[-1]["continue_final_message"] is True
+
+
+_R1 = (
+ "{% for m in messages %}<|User|>{{ m['content'] }}{% endfor %}"
+ "{% if add_generation_prompt %}<|Assistant|><think>\n{% endif %}"
+)
+
+
+ "template,opens",
+ [(_R1, True), (_QWEN3, False), ("<|im_start|>assistant\n", False), ("{% if %}<think>", False)],
+)
+def test_the_generation_prompt_opening_a_thought_is_read_off_the_template(template, opens):
+ from core.inference.managed_engine import generation_prompt_opens_thought
+ assert generation_prompt_opens_thought(template) is opens
+
+
+def test_only_sglang_records_a_generation_prompt_that_opens_a_thought(tmp_path):
+ assert validate_model(_model_dir(tmp_path, _R1), engine = "sglang")["opens_thought"] is True
+ assert "opens_thought" not in validate_model(_model_dir(tmp_path, _R1), engine = "vllm")
+ assert "opens_thought" not in validate_model(_model_dir(tmp_path, _QWEN3), engine = "sglang")
+
+
+ "opens_thought,reasoning,expected",
+ [
+ # SGLang renders a fresh generation prompt, so R1's open <think> must be closed here.
+ (True, " Two plus two. ", "Two plus two.\n</think>\n\nThe sum is"),
+ # Raw SGLang text already carries the thought and its close (or is still inside it).
+ (True, None, "The sum is"),
+ (False, "Two plus two.", "<think>\nTwo plus two.\n</think>\n\nThe sum is"),
+ (False, None, "The sum is"),
+ ],
+)
+def test_sglang_prefills_the_finished_thought_before_the_partial(
+ thinking_peer, opens_thought, reasoning, expected
+):
+ engine, requests = thinking_peer
+ engine.engine, engine.reasoning_parser, engine.opens_thought = "sglang", None, opens_thought
+ partial = {"role": "assistant", "content": "The sum is"}
+ if reasoning is not None:
+ partial["reasoning_content"] = reasoning
+ list(
+ engine.generate(
+ messages = [{"role": "user", "content": "2+2?"}, partial], continue_final_message = True
+ )
+ )
+ assert requests[-1]["messages"][-1] == {"role": "assistant", "content": expected}
+ assert requests[-1]["continue_final_message"] is True
+
+
+def test_sglang_tool_loop_continuation_carries_the_thought_in_the_prefill():
+ import asyncio
+
+ from routes.managed_engine_chat import ManagedToolTransport
+
+ sent = []
+
+ class _Response:
+ status_code = 200
+
+ async def aiter_lines(self):
+ yield 'data: {"choices":[{"delta":{"content":" 4"}}]}'
+
+ async def aclose(self):
+ return None
+
+ class _Stream:
+ async def __aenter__(self):
+ return _Response()
+
+ async def __aexit__(self, *exc):
+ return False
+
+ class _Client:
+ def stream(
+ self,
+ method,
+ url,
+ headers = None,
+ json = None,
+ ):
+ sent.append(json)
+ return _Stream()
+
+ engine = _Engine()
+ engine.engine, engine.opens_thought = "sglang", True
+ engine.base_url, engine.headers = "http://engine", {}
+ transport = ManagedToolTransport(_Client(), engine, {"model": "m"}, continuing = True)
+ messages = [
+ {"role": "user", "content": "q"},
+ {
+ "role": "assistant",
+ "content": [{"type": "text", "text": "The sum is"}],
+ "reasoning_content": "2+2",
+ },
+ ]
+
+ async def run():
+ lines = transport.stream(
+ messages = messages, tools = None, tool_choice = None, cancel_event = asyncio.Event()
+ )
+ return [line async for line in lines]
+
+ asyncio.run(run())
+ assert sent[-1]["messages"][-1] == {
+ "role": "assistant",
+ "content": "2+2\n</think>\n\nThe sum is",
+ }
+ assert messages[-1]["reasoning_content"] == "2+2"
+
+
def test_tool_loop_turns_are_fitted_to_the_engine_window():
import asyncio
diff --git a/studio/backend/tests/test_managed_engines.py b/studio/backend/tests/test_managed_engines.py
index 6f6bb570d65..701c6653d9a 100644
--- a/studio/backend/tests/test_managed_engines.py
+++ b/studio/backend/tests/test_managed_engines.py
@@ -808,6 +808,239 @@ def test_cancellation_does_not_wait_for_next_token(peer):
assert time.monotonic() - start < 2
+def test_structured_output_and_continuation_reach_the_engine(peer):
+ engine, requests = peer
+ schema = {
+ "type": "json_schema",
+ "json_schema": {"name": "city", "schema": {"type": "object"}},
+ }
+ partial = {"role": "assistant", "content": "Once upon"}
+ list(
+ engine.generate(
+ messages = [{"role": "user", "content": "Hi"}, partial],
+ response_format = schema,
+ continue_final_message = True,
+ )
+ )
+ body = requests[-1][2]
+ assert body["response_format"] == schema
+ assert body["messages"][-1] == partial
+ assert body["continue_final_message"] is True
+ assert body["add_generation_prompt"] is False
+ list(engine.generate(messages = [{"role": "user", "content": "Hi"}]))
+ assert not {"response_format", "continue_final_message", "add_generation_prompt"} & set(
+ requests[-1][2]
+ )
+
+
[email protected]("engine", ["vllm", "sglang"])
+def test_chat_completions_hand_structured_output_and_continuation_to_the_engine(
+ monkeypatch, engine
+):
+ import asyncio
+ from types import SimpleNamespace
+
+ import routes.inference as inf
+ from fastapi import HTTPException
+ from core.inference.api_monitor import ApiMonitor
+ from models.inference import ChatCompletionRequest
+ from state.tool_policy import reset_tool_policy
+
+ calls = []
+
+ class Backend:
+ active_model_name = "m"
+ models = {"m": {"engine": engine, "context_length": 2048}}
+
+ def generate_chat_response(self, **kwargs):
+ calls.append(kwargs)
+ yield '{"city": "Tokyo"}'
+
+ def reset_generation_state(self, caller_cancel_event = None):
+ pass
+
+ class Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/chat/completions")
+ method = "POST"
+ scope: dict = {}
+ headers: dict = {}
+
+ async def is_disconnected(self):
+ return False
+
+ reset_tool_policy()
+ monkeypatch.setattr(inf, "api_monitor", ApiMonitor(max_entries = 8))
+ monkeypatch.setattr(
+ inf,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = False, supports_tools = False, is_vision = False, context_length = None
+ ),
+ )
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: Backend())
+
+ def chat(status = 200, **fields):
+ payload = ChatCompletionRequest(model = "m", stream = False, enable_tools = False, **fields)
+ try:
+ response = asyncio.run(
+ inf.openai_chat_completions(payload, request = Request(), current_subject = "u")
+ )
+ except HTTPException as exc:
+ assert exc.status_code == status, exc.detail
+ return exc.detail
+ assert response.status_code == status, response.body
+ return calls[-1]
+
+ schema = {"type": "json_schema", "json_schema": {"name": "c", "schema": {"type": "object"}}}
+ sent = chat(messages = [{"role": "user", "content": "City?"}], response_format = schema)
+ assert sent["response_format"] == schema
+ sent = chat(
+ messages = [
+ {"role": "user", "content": "Count to five."},
+ {"role": "assistant", "content": "one, two,"},
+ ],
+ continue_final_message = True,
+ )
+ assert sent["continue_final_message"] is True
+ sent_before = len(calls)
+ refusal = chat(
+ status = 400,
+ messages = [
+ {"role": "user", "content": "Count to five."},
+ {"role": "assistant", "content": "", "reasoning_content": "The user wants"},
+ ],
+ continue_final_message = True,
+ )
+ assert "mid-thought" in str(refusal)
+ assert len(calls) == sent_before
+
+
[email protected]("stream", [False, True])
+def test_studio_tool_execution_refuses_a_response_format_it_cannot_honor(monkeypatch, stream):
+ import asyncio
+ from types import SimpleNamespace
+
+ import routes.inference as inf
+ from fastapi import HTTPException
+ from core.inference.api_monitor import ApiMonitor
+ from models.inference import ChatCompletionRequest
+ from state.tool_policy import reset_tool_policy
+
+ class Backend:
+ active_model_name = "m"
+ models = {"m": {"engine": "vllm", "context_length": 2048, "supports_tools": True}}
+ _managed_engine = None
+
+ def reset_generation_state(self, caller_cancel_event = None):
+ pass
+
+ class Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/chat/completions")
+ method = "POST"
+ scope: dict = {}
+ headers: dict = {}
+
+ async def is_disconnected(self):
+ return False
+
+ reset_tool_policy()
+ monkeypatch.setattr(inf, "api_monitor", ApiMonitor(max_entries = 8))
+ monkeypatch.setattr(
+ inf,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = False, supports_tools = False, is_vision = False, context_length = None
+ ),
+ )
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: Backend())
+ payload = ChatCompletionRequest(
+ model = "m",
+ stream = stream,
+ enable_tools = True,
+ enabled_tools = ["python"],
+ permission_mode = "bypass",
+ messages = [{"role": "user", "content": "Compute 7*567 and answer as JSON."}],
+ response_format = {
+ "type": "json_schema",
+ "json_schema": {"name": "a", "schema": {"type": "object"}},
+ },
+ )
+ with pytest.raises(HTTPException) as refusal:
+ asyncio.run(inf.openai_chat_completions(payload, request = Request(), current_subject = "u"))
+ assert refusal.value.status_code == 400
+ assert refusal.value.detail["error"]["param"] == "response_format"
+
+
+def test_studio_tool_loop_resumes_the_partial_it_was_given(monkeypatch):
+ import asyncio
+ from types import SimpleNamespace
+
+ import routes.inference as inf
+ import routes.managed_engine_chat as mec
+ from core.inference.api_monitor import ApiMonitor
+ from models.inference import ChatCompletionRequest
+ from state.tool_policy import reset_tool_policy
+
+ runs = []
+
+ class _Stop(Exception):
+ pass
+
+ def capture(transport, *, run, **kwargs):
+ runs.append(run)
+ raise _Stop
+
+ engine = ManagedEngine("vllm")
+ engine.base_url, engine.model, engine.context = "http://127.0.0.1:9", "m", 2048
+
+ class Backend:
+ active_model_name = "m"
+ models = {"m": {"engine": "vllm", "context_length": 2048, "supports_tools": True}}
+ _managed_engine = engine
+
+ def reset_generation_state(self, caller_cancel_event = None):
+ pass
+
+ class Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/chat/completions")
+ method = "POST"
+ scope: dict = {}
+ headers: dict = {}
+
+ async def is_disconnected(self):
+ return False
+
+ reset_tool_policy()
+ monkeypatch.setattr(mec, "stream_with_studio_tools", capture)
+ monkeypatch.setattr(inf, "api_monitor", ApiMonitor(max_entries = 8))
+ monkeypatch.setattr(
+ inf,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = False, supports_tools = False, is_vision = False, context_length = None
+ ),
+ )
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: Backend())
+ payload = ChatCompletionRequest(
+ model = "m",
+ stream = False,
+ enable_tools = True,
+ enabled_tools = ["python"],
+ permission_mode = "off",
+ continue_final_message = True,
+ messages = [
+ {"role": "user", "content": "Count to five."},
+ {"role": "assistant", "content": "one, two,"},
+ ],
+ )
+ with pytest.raises(_Stop):
+ asyncio.run(inf.openai_chat_completions(payload, request = Request(), current_subject = "u"))
+ assert runs and runs[-1].continue_final_message is True
+
+
def test_unsupported_tools_are_not_silently_dropped(peer):
engine, requests = peer
with pytest.raises(ValueError, match = "Tools"):
@@ -935,6 +1168,51 @@ def test_orchestrator_dispatches_managed_generation_without_worker(peer):
]
+def test_an_engine_rejecting_the_schema_is_a_response_format_refusal():
+ from core.inference.orchestrator import InferenceOrchestrator
+
+ errors = ["Grammar error: Invalid type: ?"]
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_POST(self):
+ self.rfile.read(int(self.headers["Content-Length"]))
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.end_headers()
+ error = {"message": errors[-1], "type": "BadRequestError", "code": 400}
+ self.wfile.write(f"data: {json.dumps({'error': error})}\n\n".encode())
+ self.wfile.flush()
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target = server.serve_forever, daemon = True)
+ thread.start()
+ try:
+ engine = ManagedEngine("vllm")
+ engine.base_url = f"http://127.0.0.1:{server.server_port}"
+ engine.model = "org/model"
+ orchestrator = InferenceOrchestrator.__new__(InferenceOrchestrator)
+ orchestrator._managed_engine = engine
+ messages = [{"role": "user", "content": "Hi"}]
+ schema = {"type": "json_schema", "json_schema": {"name": "x", "schema": {"type": "?"}}}
+ [refusal] = orchestrator._generate_inner(messages = messages, response_format = schema)
+ assert refusal.openai_param == "response_format"
+ assert "Grammar error" in refusal
+ [failure] = orchestrator._generate_inner(messages = messages)
+ assert failure.openai_param is None
+ assert failure == "Engine generation failed."
+ errors.append("This model's maximum context length is 2048 tokens.")
+ [overflow] = orchestrator._generate_inner(messages = messages, response_format = schema)
+ assert overflow.openai_param is None
+ assert overflow == "Engine generation failed."
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(2)
+
+
def test_managed_load_launches_the_validated_local_path(monkeypatch):
import threading as _threading
from types import SimpleNamespace
@@ -2296,7 +2574,7 @@ def test_a_24_gb_card_leaves_the_headroom_measured_on_an_l4(monkeypatch, engine,
assert engine_adapters.gpu_memory_fraction([0], reserve) < highest_passing
-def test_a_spelled_out_text_response_format_is_not_structured_output():
+def test_structured_output_and_continuation_pass_the_managed_engine_gate():
from types import SimpleNamespace
from routes import inference as route
@@ -2314,9 +2592,11 @@ def test_a_spelled_out_text_response_format_is_not_structured_output():
assert not route._managed_engine_unsupported_controls(payload())
assert not route._managed_engine_unsupported_controls(payload(response_format = {"type": "text"}))
- assert route._managed_engine_unsupported_controls(
+ assert not route._managed_engine_unsupported_controls(
payload(response_format = {"type": "json_object"})
)
+ assert not route._managed_engine_unsupported_controls(payload(continue_final_message = True))
+ assert route._managed_engine_unsupported_controls(payload(use_adapter = True))
assert route._managed_engine_unsupported_controls(payload(reasoning_effort = "high"))
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index b7252ab34dc..5a97bd95f6f 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -215,6 +215,7 @@ import {
} from "@/features/chat/stores/research-run-store";
import { researchReplyOwnsRun } from "@/features/chat/utils/research-run-binding";
import {
+ isExternalModelId,
parseExternalModelId,
providerModelSupportsStudioTools,
} from "@/features/chat/external-providers";
@@ -230,6 +231,7 @@ import {
import {
CONTINUATION_RUN_CONFIG_KEY,
type ContinuationRequest,
+ carriedThought,
incompleteLabel,
incompleteRemedy,
isContinuableContent,
@@ -7662,6 +7664,9 @@ function useContinuation() {
checkpoint: s.params.checkpoint,
}),
);
+ const managedEngine = useChatRuntimeStore(
+ (s) => !isExternalModelId(s.params.checkpoint) && s.loadedEngine !== "auto",
+ );
const partial = useAuiState(
({ message }) => readContinuationSource(message.content).partial,
);
@@ -7727,7 +7732,10 @@ function useContinuation() {
cancelled && !isProviderReportedReason(stamped?.reason)
? ("cancelled" as const)
: stamped?.reason;
- const carriedReasoning = thoughtResumable ? reasoning : "";
+ const carriedReasoning = carriedThought(
+ { partial, reasoning },
+ { resumesThought: thoughtResumable, managedEngine },
+ );
const canResume =
isLast &&
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 67081430355..b9d00e499b5 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -381,6 +381,7 @@ import type { CachedGgufRepo, CachedModelRepo } from "./chat-api";
import {
budgetImpliesTruncation,
CONTINUE_INSTRUCTION,
+ carriedThought,
continuationSeed,
createContinuationMerger,
hasRenderableContent,
@@ -5208,17 +5209,20 @@ export function createOpenAIStreamAdapter(
}
// Carry reasoning only to a backend that can resume it.
- const resumedThought =
- continuation &&
- resumesThought({
- loadedIsGguf: runtime.loadedIsGguf,
- loadedIsMlx: runtime.loadedIsMlx,
- activeGgufVariant: runtime.activeGgufVariant,
- activeNativePathToken: runtime.activeNativePathToken,
- checkpoint: params.checkpoint,
- })
- ? (continuation.reasoning ?? "")
- : "";
+ const resumedThought = continuation
+ ? carriedThought(continuation, {
+ resumesThought: resumesThought({
+ loadedIsGguf: runtime.loadedIsGguf,
+ loadedIsMlx: runtime.loadedIsMlx,
+ activeGgufVariant: runtime.activeGgufVariant,
+ activeNativePathToken: runtime.activeNativePathToken,
+ checkpoint: params.checkpoint,
+ }),
+ managedEngine:
+ !isExternalModelId(params.checkpoint) &&
+ runtime.loadedEngine !== "auto",
+ })
+ : "";
const hasGeminiReplayContinuation = Boolean(
continuation &&
externalProvider?.providerType === "gemini" &&
diff --git a/studio/frontend/src/features/chat/utils/continuation.ts b/studio/frontend/src/features/chat/utils/continuation.ts
index 9f90e2a69c6..12d1ec18df9 100644
--- a/studio/frontend/src/features/chat/utils/continuation.ts
+++ b/studio/frontend/src/features/chat/utils/continuation.ts
@@ -275,6 +275,19 @@ export function readContinuationSource(
return { partial, reasoning: ordered ? thoughts.join("\n") : "" };
}
+/** A managed engine keeps a finished thought but cannot reopen one. */
+export function carriedThought(
+ continuation: { partial: string; reasoning?: string },
+ {
+ resumesThought,
+ managedEngine,
+ }: { resumesThought: boolean; managedEngine: boolean },
+): string {
+ return resumesThought || (managedEngine && continuation.partial)
+ ? (continuation.reasoning ?? "")
+ : "";
+}
+
export function continuationSeed(partial: string, thought: string): string {
if (!thought) {
return partial;
diff --git a/studio/frontend/tests/chat-thought-continuation.test.ts b/studio/frontend/tests/chat-thought-continuation.test.ts
index 5883b63511d..23ebc45178b 100644
--- a/studio/frontend/tests/chat-thought-continuation.test.ts
+++ b/studio/frontend/tests/chat-thought-continuation.test.ts
@@ -5,6 +5,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
+ carriedThought,
continuationSeed,
isContinuableContent,
readContinuationRequest,
@@ -231,6 +232,18 @@ test("a continued answer keeps the thought it followed", () => {
assert.equal(continuationSeed("2, 3 ", ""), "2, 3 ");
});
+test("a managed engine keeps a finished thought but never reopens one", () => {
+ const answer = { partial: "2, 3", reasoning: "Easy." };
+ const thoughtOnly = { partial: "", reasoning: THOUGHT };
+ const managed = { resumesThought: false, managedEngine: true };
+ assert.equal(carriedThought(answer, managed), "Easy.");
+ assert.equal(carriedThought(thoughtOnly, managed), "");
+ const llama = { resumesThought: true, managedEngine: false };
+ assert.equal(carriedThought(thoughtOnly, llama), THOUGHT);
+ const transformers = { resumesThought: false, managedEngine: false };
+ assert.equal(carriedThought(answer, transformers), "");
+});
+
function clock(start = 1_000_000) {
let now = start;
return {