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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: auto-compact long chats on the SGLang engine (#15434)
Nilaya20b732e03f1
diff --git a/studio/backend/core/inference/engine_adapters.py b/studio/backend/core/inference/engine_adapters.pyindex ca0bec512c6..7907c2adade 100644--- a/studio/backend/core/inference/engine_adapters.py+++ b/studio/backend/core/inference/engine_adapters.py@@ -317,6 +317,7 @@ ADAPTERS = {"--context-length","--mem-fraction-static",("--attention-backend", "triton", "--sampling-backend", "pytorch"),+ True,),}diff --git a/studio/backend/core/inference/managed_engine.py b/studio/backend/core/inference/managed_engine.pyindex 237b1a35672..44e634061c0 100644--- a/studio/backend/core/inference/managed_engine.py+++ b/studio/backend/core/inference/managed_engine.py@@ -1133,6 +1133,21 @@ class ManagedEngine:for message in messages]+ def _reply_cap_in_window(self, messages, system_prompt, limit, params):+ """vLLM and SGLang refuse prompt + max_tokens past the window, where llama-server stops at it."""+ try:+ prompt = self.count_tokens(+ messages,+ system_prompt,+ enable_thinking = params.get("enable_thinking"),+ reasoning_effort = params.get("reasoning_effort"),+ preserve_thinking = params.get("preserve_thinking"),+ )[0]+ except Exception:+ # An estimate would cut a fitting reply short; the engine judges the cap itself.+ return limit+ return max(1, min(limit, self.context - prompt))+def count_tokens(self,messages,@@ -1267,7 +1282,11 @@ class ManagedEngine:# -1 or full context leaves no room for the prompt; let the engine budget it.limit = params.get("max_new_tokens") or 0if limit > 0 and (not self.context or limit < self.context):- payload["max_tokens"] = limit+ payload["max_tokens"] = (+ self._reply_cap_in_window(messages, system_prompt, limit, params)+ if self.context and not request_images+ else limit+ )payload.update(self.reasoning_fields(params.get("enable_thinking"),diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex 80aa8cb6f8e..bbac9d6f38a 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -53,6 +53,18 @@ def __getattr__(name: str):logger = get_logger(__name__)+# Half a token a UTF-8 byte, and a byte-level token spans at least one, so half the window bounds the real count.+_ESTIMATED_FIT_HEADROOM = 0.5+++def _utf8_half_tokens(messages) -> int:+ import json+ return sum(+ (len(json.dumps(message, ensure_ascii = False).encode("utf-8")) + 1) // 2+ for message in messages+ )++# Delimited, not a whitelist: a whitelist stopped at the apostrophe in `/home/o'connor/`._PATH_COMPONENT = r"[^\s\\/](?:(?:(?![A-Za-z]:[\\/])[^\\/\n\",;])*[^\s\\/])?"# Second alternative: the root-level case (`/model.gguf`, `\\server\share`) has no trailing separator.@@ -2791,6 +2803,7 @@ class InferenceOrchestrator:from core.inference.context_window import (messages_without_unpriced_media,retrieval_budget,+ truncate_oldest_messages,)from core.inference.llama_cpp import (_archive_and_recall,@@ -2823,17 +2836,28 @@ class InferenceOrchestrator:for tool in tools or ())+ count_kwargs = {+ "tools": tools,+ "enable_thinking": enable_thinking,+ "reasoning_effort": reasoning_effort,+ "preserve_thinking": preserve_thinking,+ }+ # SGLang 0.5.17's /tokenize returns 500 when model_max_length is the 1e30 sentinel.+ estimated = False+ if getattr(self, "_managed_engine", None) is not None:+ try:+ self.count_chat_tokens(conversation[-1:], "", **count_kwargs)+ except Exception as exc:+ logger.info("Fitting the managed engine prompt by estimate: %s", exc)+ estimated = True+ context_length = int(context_length * (1 - _ESTIMATED_FIT_HEADROOM))+def _count(fitted):if cancel_event is not None and cancel_event.is_set():raise RuntimeError("Context compaction cancelled")- return self.count_chat_tokens(- fitted,- "",- tools = tools,- enable_thinking = enable_thinking,- reasoning_effort = reasoning_effort,- preserve_thinking = preserve_thinking,- )[0]+ if estimated:+ return _utf8_half_tokens(messages_without_unpriced_media(fitted))+ return self.count_chat_tokens(fitted, "", **count_kwargs)[0]can_reset = _can_reset_epoch(thread_id,@@ -2863,9 +2887,7 @@ class InferenceOrchestrator:compaction_headroom_ratio = compaction_headroom_ratio,))- fitted, truncation = _fit_with_instruction_pins(- conversation,- context_length = context_length,+ fit_kwargs = dict(max_tokens = max_tokens,count_tokens = _count,anchor_ids = anchor_ids,@@ -2879,6 +2901,26 @@ class InferenceOrchestrator:force_reset = force_reset,**_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),)+ fitted, truncation = _fit_with_instruction_pins(+ conversation, context_length = context_length, **fit_kwargs+ )+ # The bound overprices, so its refusal is served as a rescue: the irreducible suffix, judged by the engine.+ if (+ estimated+ and truncation+ and not truncation.get("fits")+ and not truncation.get("dropped_messages")+ ):+ suffix, dropped = truncate_oldest_messages(+ conversation, 0.0, protected_message_ids = set(anchor_ids or ()) or None+ )+ if dropped:+ fitted = suffix+ truncation = {+ **truncation,+ "dropped_messages": dropped,+ "prompt_tokens_after": _count(suffix),+ }if not truncation:return {**unchanged, "boundary_applied": True}diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 40e3b8f5bfc..d83797ce4a0 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -32854,10 +32854,9 @@ async def produce_openai_chat_completions(# Classify capability flags from the loaded template._sf_model_info = backend.models.get(backend.active_model_name, {})- # Only MLX and managed vLLM count their own prompt exactly, so only they are fitted first._sf_fit_overflow = (_rolling_context_policy(payload)- if _sf_model_info.get("is_mlx") or _sf_model_info.get("engine") == "vllm"+ if _sf_model_info.get("is_mlx") or _sf_model_info.get("engine") in ("vllm", "sglang")else None)if _sf_model_info.get("engine") in ("vllm", "sglang"):@@ -32914,6 +32913,8 @@ async def produce_openai_chat_completions(# tool_choice asked directly: _tool_loop_unusable weighs it against GGUF's tools._sf_recall_loop_usable = (payload.tool_choice != "none"+ # Managed engines refuse tools on this path; their tool turns go through managed_tool_chat.+ and _sf_model_info.get("engine") not in ("vllm", "sglang")and not _tool_loop_unusableand not _has_client_tool_contractand not _response_format_constrains_decoding(payload)diff --git a/studio/backend/routes/managed_engine_chat.py b/studio/backend/routes/managed_engine_chat.pyindex e85568d0917..16288dab925 100644--- a/studio/backend/routes/managed_engine_chat.py+++ b/studio/backend/routes/managed_engine_chat.py@@ -129,11 +129,11 @@ def _message_fitter(tools,studio_loop = False,):- """Auto-compact to the vLLM engine's window; the exact count refuses tools, so this estimates."""+ """Auto-compact to the managed engine's window; the exact count refuses tools, so this estimates."""from routes import inference as apiif (- getattr(engine, "engine", None) != "vllm"+ getattr(engine, "engine", None) not in ("vllm", "sglang")or api._rolling_context_policy(payload) is Noneor not engine.context):@@ -152,6 +152,9 @@ def _message_fitter(# on a controller re-prompt that recall must not query for.branch: list = []tool_loop = studio_loop and not api._tool_calls_are_disabled(payload)+ # An uncapped reply is sized by the engine; a cap from the estimate can push the prompt over.+ limit = api._effective_max_tokens(payload)+ capped = bool(limit) and limit < engine.contextasync def fit(messages):if not branch:@@ -169,7 +172,7 @@ def _message_fitter(line = api._context_truncated_sse_chunk("chatcmpl-" + uuid.uuid4().hex[:12], public, truncation).rstrip("\n")- return fitted, max_tokens, line+ return fitted, max_tokens if capped else None, linereturn fitdiff --git a/studio/backend/tests/test_managed_engine_reasoning.py b/studio/backend/tests/test_managed_engine_reasoning.pyindex a2b7afafb55..3c2da3c3059 100644--- a/studio/backend/tests/test_managed_engine_reasoning.py+++ b/studio/backend/tests/test_managed_engine_reasoning.py@@ -217,12 +217,13 @@ def test_load_flags_come_from_the_engine_template():assert _detect_safetensors_features(backend, None)["supports_reasoning"] is False-def test_managed_engine_chat_is_fitted_to_the_engine_window():[email protected]("engine", ["vllm", "sglang"])+def test_managed_engine_chat_is_fitted_to_the_engine_window(engine):from core.inference.orchestrator import InferenceOrchestratororchestrator = InferenceOrchestrator.__new__(InferenceOrchestrator)orchestrator.active_model_name = "m"- orchestrator.models = {"m": {"engine": "vllm", "context_length": 2048}}+ orchestrator.models = {"m": {"engine": engine, "context_length": 2048}}calls = []def count(@@ -257,6 +258,126 @@ def test_managed_engine_chat_is_fitted_to_the_engine_window():assert unchanged["messages"] == messages[email protected]("engine", ["vllm", "sglang"])+def test_both_managed_engines_count_the_prompt_with_their_tokenize_route(monkeypatch, engine):+ # SGLang's /tokenize renders messages through its chat template like vLLM's.+ from core.inference import managed_engine++ sent = []++ class _Client:+ def __init__(self, **kwargs):+ pass++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def post(+ self,+ url,+ headers = None,+ json = None,+ ):+ sent.append((url, json))+ return SimpleNamespace(raise_for_status = lambda: None, json = lambda: {"count": 11})++ monkeypatch.setattr(managed_engine.httpx, "Client", _Client)+ managed = ManagedEngine(engine)+ managed.base_url, managed.model = "http://engine", "m"+ assert managed.count_tokens([{"role": "user", "content": "hi"}], "Be brief.")[0] == 11+ url, body = sent[-1]+ assert url == "http://engine/tokenize"+ assert body["messages"][0] == {"role": "system", "content": "Be brief."}+++def test_a_failed_sglang_count_falls_back_to_an_estimated_fit():+ # SGLang 0.5.17 answers /tokenize 500 for a tokenizer whose model_max_length is the 1e30 sentinel.+ from core.inference.orchestrator import InferenceOrchestrator++ orchestrator = InferenceOrchestrator.__new__(InferenceOrchestrator)+ orchestrator.active_model_name = "m"+ orchestrator.models = {"m": {"engine": "sglang", "context_length": 2048}}+ orchestrator._managed_engine = SimpleNamespace(adapter = ADAPTERS["sglang"])++ def count(*args, **kwargs):+ raise RuntimeError("500 Server Error: Integer exceeds 64-bit range")++ orchestrator.count_chat_tokens = count+ turn = "word " * 400+ messages = []+ for index in range(10):+ messages += [+ {"role": "user", "content": f"q{index} {turn}"},+ {"role": "assistant", "content": f"a{index} {turn}"},+ ]+ messages.append({"role": "user", "content": "latest"})+ fitted = orchestrator.compact_chat_context(+ messages, context_overflow = "truncate_oldest", max_tokens = 256+ )+ assert fitted["messages"][-1]["content"] == "latest"+ truncation = next(e for e in fitted["events"] if e.get("type") == "context_truncated")+ assert truncation["fits"] and truncation["prompt_tokens_after"] <= 2048 // 2 - 256++[email protected]("engine", ["vllm", "sglang"])+def test_a_reply_cap_is_clamped_to_the_room_the_prompt_leaves(monkeypatch, engine):+ # Both engines refuse prompt + max_tokens past the window, so a fitted chat with a cap would fail.+ from core.inference import engine_transport++ sent = []+ monkeypatch.setattr(+ engine_transport,+ "stream_chat_events",+ lambda url, headers, payload, cancelled: sent.append(payload) or iter(()),+ )+ managed = ManagedEngine(engine)+ managed.base_url, managed.model, managed.context = "http://engine", "m", 2048+ messages = [{"role": "user", "content": "hi"}]+ for counted, cap, expected in ((1500, 1024, 548), (100, 1024, 1024), (100, 4096, None)):+ managed.count_tokens = lambda *a, counted = counted, **k: (counted, "m")+ list(managed.generate(messages = messages, max_new_tokens = cap))+ assert sent[-1].get("max_tokens") == expected++ def refuse(*a, **k):+ raise RuntimeError("500 Server Error")++ managed.count_tokens = refuse+ list(+ managed.generate(messages = [{"role": "user", "content": "word " * 1250}], max_new_tokens = 256)+ )+ # Without a measured prompt the cap is the engine's to judge; an estimate would cut it to 1.+ assert sent[-1]["max_tokens"] == 256+++def test_a_latest_turn_the_strict_estimate_refuses_still_drops_old_history():+ from core.inference.orchestrator import InferenceOrchestrator++ orchestrator = InferenceOrchestrator.__new__(InferenceOrchestrator)+ orchestrator.active_model_name = "m"+ orchestrator.models = {"m": {"engine": "sglang", "context_length": 2048}}+ orchestrator._managed_engine = SimpleNamespace(adapter = ADAPTERS["sglang"])++ def count(*args, **kwargs):+ raise RuntimeError("500 Server Error: Integer exceeds 64-bit range")++ orchestrator.count_chat_tokens = count+ messages = []+ for index in range(10):+ messages += [+ {"role": "user", "content": "word " * 400},+ {"role": "assistant", "content": "ok"},+ ]+ messages.append({"role": "user", "content": "word " * 400 + "latest"})+ fitted = orchestrator.compact_chat_context(+ messages, context_overflow = "truncate_oldest", max_tokens = 256+ )+ assert fitted["messages"][-1]["content"].endswith("latest")+ assert len(fitted["messages"]) < len(messages)++def test_tool_stream_reasoning_reaches_studio_as_reasoning_content():from routes.managed_engine_chat import _with_reasoning_content@@ -553,10 +674,26 @@ def test_tool_loop_turns_are_fitted_to_the_engine_window():assert _message_fitter(_tool_payload(), _Engine(), "m", tools = None) is Nonesglang = _Engine()sglang.engine = "sglang"- assert (- _message_fitter(_tool_payload(context_overflow = "truncate_oldest"), sglang, "m", None)- is None- )+ fit = _message_fitter(_tool_payload(context_overflow = "truncate_oldest"), sglang, "m", None)+ fitted, _, line = asyncio.run(fit(messages))+ assert fitted[-1]["content"] == "latest" and len(fitted) < len(messages)+ assert line and "context_truncated" in line+++def test_a_window_sized_reply_cap_is_left_to_the_engine():+ import asyncio++ from routes.managed_engine_chat import _message_fitter++ prompt = [{"role": "user", "content": "word " * 1200}]+ for engine in ("vllm", "sglang"):+ managed = _Engine()+ managed.engine = engine+ for cap, sent in ((None, None), (4096, None), (256, 256)):+ payload = _tool_payload(context_overflow = "truncate_oldest")+ payload.max_tokens = cap+ fit = _message_fitter(payload, managed, "m", None)+ assert asyncio.run(fit(prompt))[1] == sentdef test_a_managed_refit_recalls_with_the_first_branch_it_saw(monkeypatch):diff --git a/studio/backend/tests/test_managed_engines.py b/studio/backend/tests/test_managed_engines.pyindex 701c6653d9a..881ce8b002d 100644--- a/studio/backend/tests/test_managed_engines.py+++ b/studio/backend/tests/test_managed_engines.py@@ -1747,7 +1747,8 @@ def test_max_tokens_sentinel_is_not_sent_as_a_negative_limit(peer, limit):engine, requests = peerengine.context = 4096assert list(engine.generate(messages = [{"role": "user", "content": "Hi"}], max_new_tokens = limit))- payload = requests[0][2]+ # A cap is first fitted to the window through /tokenize.+ payload = next(body for path, _, body in requests if path.endswith("/chat/completions"))if limit is not None and 0 < limit < engine.context:assert payload["max_tokens"] == limitelse:diff --git a/studio/backend/tests/test_sf_client_tools_passthrough.py b/studio/backend/tests/test_sf_client_tools_passthrough.pyindex bf5596f5569..a251a7ab8fb 100644--- a/studio/backend/tests/test_sf_client_tools_passthrough.py+++ b/studio/backend/tests/test_sf_client_tools_passthrough.py@@ -1769,6 +1769,22 @@ def test_a_compacted_mlx_thread_keeps_archive_search_with_tools_off(assert probed[0] is bool(offered)[email protected]("engine", ["sglang", "vllm"])+def test_a_compacted_managed_engine_thread_answers_without_the_local_tool_loop(monkeypatch, engine):+ import routes.inference as inf++ monkeypatch.setattr(inf, "_thread_has_conversation_archive", lambda thread_id: True)+ monkeypatch.setattr(inf, "_thread_has_checkpoint", lambda thread_id, messages = None: True)+ backend = _FittedToolLoopBackend(_fixed("done"))+ backend.models["sf-model"]["engine"] = engine+ _install(monkeypatch, backend)+ fields = {"thread_id": "saved", "context_overflow": "truncate_oldest"}+ _serve(monkeypatch, stream = False, enable_tools = False, context_policy = "checkpoint", **fields)++ assert backend.calls[0]["tools"] is None+ assert [fit["recall_reachable"] for fit in backend.fits] == [False]++@pytest.mark.parametrize("asked", [{"enable_tools": True}, {"mcp_enabled": True}])def test_tool_choice_none_keeps_a_compacted_mlx_thread_tool_free(monkeypatch, asked):import routes.inference as infdiff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex b9d00e499b5..368ef980689 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -2288,7 +2288,7 @@ export async function buildLocalTokenCountExtras(checkpoint: state.params.checkpoint,}),isMlx: state.loadedIsMlx === true,- isManagedEngine: state.loadedEngine === "vllm",+ isManagedEngine: state.loadedEngine !== "auto",autoCompactEnabled: state.autoCompactEnabled,}),};@@ -5519,7 +5519,7 @@ export function createOpenAIStreamAdapter(const isMlxForCompaction =!isExternalModelId(params.checkpoint) && runtime.loadedIsMlx === true;const isManagedEngineForCompaction =- !isExternalModelId(params.checkpoint) && runtime.loadedEngine === "vllm";+ !isExternalModelId(params.checkpoint) && runtime.loadedEngine !== "auto";// Taken once, so a retried request still carries it and the next turn does not.const compactNow =takeThreadCompactionRequest(resolvedThreadId) &&diff --git a/studio/frontend/src/features/chat/utils/auto-compaction.ts b/studio/frontend/src/features/chat/utils/auto-compaction.tsindex f94bf530875..2fc620dec0a 100644--- a/studio/frontend/src/features/chat/utils/auto-compaction.ts+++ b/studio/frontend/src/features/chat/utils/auto-compaction.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-/** Local GGUF, MLX and managed vLLM auto-compaction. On or off; how it compacts is the server's call.+/** Local GGUF, MLX and managed engine auto-compaction. On or off; how it compacts is the server's call.** Studio used to offer the policy as a setting, but the choice needed the reader to know what a* checkpoint epoch and a rolling window were before it meant anything, and both sides of it werediff --git a/studio/frontend/tests/auto-compaction-settings.test.ts b/studio/frontend/tests/auto-compaction-settings.test.tsindex 80e01b43e32..4bd33fedc97 100644--- a/studio/frontend/tests/auto-compaction-settings.test.ts+++ b/studio/frontend/tests/auto-compaction-settings.test.ts@@ -51,8 +51,8 @@ test("a managed vLLM or SGLang model compacts like a local GGUF", () => {{ context_overflow: "error" },);const adapter = readSrc("features/chat/api/chat-adapter.ts");- // SGLang has no exact count to fit against, so only the vLLM engine asks.- assert.match(adapter, /runtime\.loadedEngine === "vllm"/);+ assert.match(adapter, /runtime\.loadedEngine !== "auto"/);+ assert.match(adapter, /isManagedEngine: state\.loadedEngine !== "auto"/);// A queued turn keeps the engine it was queued against, like loadedIsGguf / loadedIsMlx.assert.match(readSrc("features/chat/utils/queued-chat-run-settings.ts"), /"loadedEngine",/);assert.match(adapter, /isManagedEngine: isManagedEngineForCompaction/);