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: compact long chats on self-hosted connections to the window the server reports (#12975)
oobaboogade64d69c6388
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex f35358c81a9..e148e7a5b7e 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -7,6 +7,7 @@import asyncioimport base64import contextlib+import hashlibimport ioimport json as _jsonimport math@@ -43,20 +44,36 @@ from models.providers import (# sweeping a hosted API costs a space in delimiter-like text, not sweeping a local one costs a forged turn._TEMPLATE_APPLYING_PROVIDERS = frozenset({"vllm", "llama_cpp", "ollama", "custom", "lemonade"})-# The subset documenting "continue_final_message" + "add_generation_prompt" on /v1/chat/completions.+# only vLLM and llama.cpp document both continuation flags on /v1/chat/completions._CONTINUATION_FLAG_PROVIDERS = frozenset({"vllm", "llama_cpp"})-# The subset documenting stream_options.include_usage. An OAI-compatible stream omits usage without it, leaving the-# chat context bar without prompt_tokens and, where no llama.cpp timings arrive, the monitor without a speed. Same-# caution as the flag above: "custom" is any user-supplied base_url and a strict endpoint 400s on an unknown field.-# "openai" is absent because it routes to /v1/responses, which reports usage on its own.+# custom may reject include_usage; OpenAI Responses supplies usage, while listed streams require it._USAGE_STREAM_OPTION_PROVIDERS = frozenset({"vllm", "llama_cpp", "openrouter", "kimi", "lemonade"})-# llama-server reads repeat_penalty, not repetition_penalty (as routes/inference does).+# launch-time windows are absent from catalogues; custom covers unregistered self-hosted servers.+_SERVED_WINDOW_PROVIDERS = frozenset({"vllm", "llama_cpp", "custom"})+# refresh quickly enough to detect a server restart within one or two turns.+_SERVED_WINDOW_TTL_S = 60.0+_SERVED_WINDOW_TIMEOUT_S = 5.0+_served_windows: dict[tuple[str, str, str], tuple[float, Optional[int]]] = {}+++def _positive_int(value: Any) -> Optional[int]:+ return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None+++def _reported_window(entry: dict[str, Any]) -> Optional[int]:+ # llama-server's served window is meta.n_ctx, not meta.n_ctx_train; others use max_model_len.+ meta = entry.get("meta")+ return _positive_int(meta.get("n_ctx") if isinstance(meta, dict) else None) or _positive_int(+ entry.get("max_model_len")+ )+++# llama-server expects repeat_penalty rather than repetition_penalty._REPETITION_PENALTY_BODY_KEY = {"llama_cpp": "repeat_penalty"}-# structlog so INFO diagnostics reach the backend's JSON log stream (the stdlib root logger defaults to WARNING with-# no handlers). It accepts the existing printf-style positional args.+# structlog sends INFO diagnostics to the backend JSON stream and accepts printf-style arguments.logger = structlog.get_logger(__name__)_MAX_CONCATENATED_WAV_BYTES = 64 * 1024 * 1024@@ -7397,30 +7414,15 @@ class ExternalProviderClient:]async def list_models(self) -> list[dict[str, Any]]:- """GET /models to discover available models. Returns dicts with at least 'id'. All providers- expose /models with the OpenAI {"data": [...]} shape, Anthropic included."""+ """return each provider's OpenAI-compatible /models entries, including Anthropic."""try:- response = await _client().get(- f"{self.base_url}/models",- headers = self._auth_headers(),- timeout = self._timeout,- )- response.raise_for_status()- data = response.json()- # Some local servers (Ollama with no models) return data: null.- models: list[dict[str, Any]] = []- if isinstance(data, dict):- raw_models = data.get("data") or []- if isinstance(raw_models, list):- models = [model for model in raw_models if isinstance(model, dict)]+ data, models = await self._models_payload(self._timeout)if self.provider_type == "ollama":- # Only /api/tags carries the per-model "thinking" capability.+ # only /api/tags carries each model's "thinking" capability.if not models:models = await self._list_ollama_native_models()else:models = await self._with_ollama_capabilities(models)- # Gemini's native /v1beta/models uses a different shape; repackage into the OpenAI-compatible one Unsloth- # expects.if not models and self.provider_type == "gemini":models = self._parse_gemini_models(data)return models@@ -7428,11 +7430,75 @@ class ExternalProviderClient:logger.error("Failed to list models from %s: %s", self.provider_type, exc)raise+ async def _models_payload(self, timeout: Any) -> tuple[Any, list[dict[str, Any]]]:+ response = await _client().get(+ f"{self.base_url}/models", headers = self._auth_headers(), timeout = timeout+ )+ response.raise_for_status()+ data = response.json()+ # Ollama returns data: null when no models are installed.+ raw = data.get("data") if isinstance(data, dict) else None+ return data, [e for e in raw if isinstance(e, dict)] if isinstance(raw, list) else []++ async def _read_served_window(self, model: str) -> Optional[int]:+ _, entries = await self._models_payload(_SERVED_WINDOW_TIMEOUT_S)+ by_id = {e["id"]: e for e in entries if isinstance(e.get("id"), str)}+ entry = by_id.get(model) or next(+ (e for e in entries if isinstance(e.get("aliases"), list) and model in e["aliases"]),+ # a single-model llama-server serves its only model for any requested id.+ entries[0] if len(entries) == 1 else None,+ )+ if entry is None:+ return None+ window = _reported_window(entry)+ parent = entry.get("parent")+ if window is None and isinstance(parent, str) and parent in by_id:+ # vLLM and SGLang LoRA adapters use their base model's context window.+ window = _reported_window(by_id[parent])+ if window is not None or entry.get("owned_by") != "llamacpp":+ return window+ # before b9500 added meta.n_ctx, /props reports n_ctx; ?model= routes only in router mode.+ entry_id = entry.get("id")+ props = await _client().get(+ f"{self.base_url.removesuffix('/v1')}/props",+ params = {"model": entry_id if isinstance(entry_id, str) else model},+ headers = self._auth_headers(),+ timeout = _SERVED_WINDOW_TIMEOUT_S,+ )+ props.raise_for_status()+ body = props.json()+ settings = body.get("default_generation_settings") if isinstance(body, dict) else None+ return _positive_int(settings.get("n_ctx") if isinstance(settings, dict) else None)++ async def served_context_window(self, model: str) -> Optional[int]:+ """cache served windows and missing results for one minute to limit silent-server reads."""+ if self.provider_type not in _SERVED_WINDOW_PROVIDERS:+ return None+ now = time.monotonic()+ key = (self.base_url, hashlib.sha256((self.api_key or "").encode()).hexdigest(), model)+ cached = _served_windows.get(key)+ if cached is not None and cached[0] > now:+ return cached[1]+ window = None+ try:+ # both reads share one deadline because the first token waits for them.+ window = await asyncio.wait_for(+ self._read_served_window(model), timeout = _SERVED_WINDOW_TIMEOUT_S+ )+ except httpx.ConnectError as exc:+ # retry a down or restarting server next turn instead of caching the miss for a minute.+ logger.info("No served context window from %s: %s", self.provider_type, exc)+ return None+ except (httpx.HTTPError, ValueError, asyncio.TimeoutError) as exc:+ logger.info("No served context window from %s: %r", self.provider_type, exc)+ for stale in [k for k, (expiry, _) in _served_windows.items() if expiry <= now]:+ del _served_windows[stale]+ _served_windows[key] = (now + _SERVED_WINDOW_TTL_S, window)+ return window+@staticmethoddef _parse_gemini_models(payload: Any) -> list[dict[str, Any]]:- """Translate Gemini's native /v1beta/models payload to OpenAI shape, keeping only entries- advertising generateContent / streamGenerateContent so embedding-only models do not reach- the chat picker."""+ """map Gemini models to OpenAI entries and exclude advertised embedding-only models."""if not isinstance(payload, dict):return []entries = payload.get("models") or []diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 44b441695e3..258e5ce145d 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2979,7 +2979,11 @@ class ChatCompletionRequest(BaseModel):"[x-unsloth] The external model's context window, in tokens. When ""Unsloth drops the oldest turns for a compaction_threshold, the prompt ""also leaves room for max_tokens within it, and max_tokens is lowered "- "if it would leave the prompt less than half of the window."+ "if it would leave the prompt less than half of the window. With "+ "context_overflow=truncate_oldest and no compaction_threshold, three "+ "quarters of this window is used as the threshold; when this field is "+ "also omitted, a vLLM, llama.cpp or Custom connection uses the window "+ "its server reports on /models."),)openai_code_exec_container_id: Optional[str] = Field(diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 8ea964141b1..7dfe12b02fd 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -27779,6 +27779,11 @@ async def _stop_on_cancel(agen, cancel_event: threading.Event):pass+# keep these limits aligned with auto-compaction.ts, which derives catalogued-window thresholds.+_EXTERNAL_COMPACTION_HEADROOM = 0.25+_EXTERNAL_COMPACTION_THRESHOLD_MAX = 2_000_000++def _fit_external_context(messages: list[dict],payload,@@ -28646,6 +28651,25 @@ async def _proxy_to_external_provider(if _external_nudge:chat_messages = _append_to_system_message(chat_messages, _external_nudge)_provider_compacts = compacts_server_side(provider_type, base_url, api_type, model)+ # UNSLOTH_CONTEXT_OVERFLOW must not bypass Studio's auto-compact switch.+ if (+ managed is None+ and payload.context_overflow == "truncate_oldest"+ and not payload.compaction_threshold+ and not _provider_compacts+ ):+ # a self-hosted server reports its startup window when the catalog has none.+ _served_window = payload.context_window or await client.served_context_window(model)+ if _served_window:+ payload = payload.model_copy(+ update = {+ "context_window": _served_window,+ "compaction_threshold": min(+ _EXTERNAL_COMPACTION_THRESHOLD_MAX,+ int(_served_window * (1 - _EXTERNAL_COMPACTION_HEADROOM)),+ ),+ }+ )_external_truncation = None_external_max_tokens = _effective_max_tokens(payload)_external_context_fitter = Nonediff --git a/studio/backend/tests/test_external_auto_compaction.py b/studio/backend/tests/test_external_auto_compaction.pyindex 8deb61fcc5b..9cfe520d5e2 100644--- a/studio/backend/tests/test_external_auto_compaction.py+++ b/studio/backend/tests/test_external_auto_compaction.py@@ -3,6 +3,7 @@from __future__ import annotations+import asyncioimport jsonimport sysfrom http.server import BaseHTTPRequestHandler@@ -400,3 +401,223 @@ def test_external_fit_reserves_tool_schemas():fitted, truncation, _ = ri._fit_external_context(messages, payload, tools = tools)assert truncation and truncation["dropped_messages"] > 0assert fitted[-1]["content"] == "latest question"+++class _ServedWindowHandler(_Handler):+ models: list[dict] = []+ props: dict | None = None+ key: str | None = None+ gets: list[str] = []++ def do_GET(self) -> None: # noqa: N802+ type(self).gets.append(self.path)+ if self.key is not None and self.headers.get("Authorization") != f"Bearer {self.key}":+ status, body = 401, {"error": "unauthorized"}+ elif self.path == "/v1/models":+ status, body = 200, {"object": "list", "data": self.models}+ elif self.path.startswith("/props") and self.props is not None:+ status, body = 200, self.props+ else:+ status, body = 404, {"error": "not found"}+ raw = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.end_headers()+ self.wfile.write(raw)+++def _served(**attrs):+ ep_mod._served_windows.clear()+ return type("Served", (_ServedWindowHandler,), {"gets": [], **attrs})+++def _llama_server():+ # llama-server -c 16384 -np 2 reports n_ctx per slot and n_ctx_train as the trained maximum.+ return _served(+ models = [+ {+ "id": "qwen3-next",+ "aliases": ["qwen3-next"],+ "owned_by": "llamacpp",+ "meta": {"n_ctx": 8_192, "n_ctx_train": 262_144},+ }+ ]+ )+++def _fits(sent: dict, window: int) -> bool:+ return estimate_messages_tokens_conservative(sent["messages"]) + sent["max_tokens"] <= window+++def test_a_llama_server_connection_compacts_to_the_window_the_server_reports():+ chunks, sent = _proxy(+ "llama_cpp",+ _long_chat(),+ handler = _llama_server(),+ model = "qwen3-next",+ context_overflow = "truncate_oldest",+ )+ assert len(sent["messages"]) < len(_long_chat())+ assert sent["messages"][-1]["content"] == "latest question"+ assert _fits(sent, 8_192)+ [truncation] = _truncations(chunks)+ assert truncation["fits"] is True+++def test_a_custom_connection_to_vllm_compacts_to_max_model_len():+ vllm = _served(models = [{"id": "a-model", "owned_by": "vllm", "max_model_len": 8_192}])+ chunks, sent = _proxy("custom", _long_chat(), handler = vllm, context_overflow = "truncate_oldest")+ assert len(sent["messages"]) < len(_long_chat())+ assert _fits(sent, 8_192)+ assert len(_truncations(chunks)) == 1+++def test_a_lora_adapter_uses_its_base_model_window():+ vllm = _served(+ models = [+ {"id": "base", "owned_by": "vllm", "max_model_len": 8_192},+ {"id": "my-lora", "owned_by": "vllm", "parent": "base"},+ ]+ )+ _, sent = _proxy(+ "vllm", _long_chat(), handler = vllm, model = "my-lora", context_overflow = "truncate_oldest"+ )+ assert len(sent["messages"]) < len(_long_chat())+ assert _fits(sent, 8_192)+++def test_an_older_llama_server_is_read_from_props_for_the_model():+ old = _served(+ models = [{"id": "a-model", "owned_by": "llamacpp", "meta": {"n_ctx_train": 262_144}}],+ props = {"default_generation_settings": {"n_ctx": 8_192}},+ )+ _, sent = _proxy("llama_cpp", _long_chat(), handler = old, context_overflow = "truncate_oldest")+ assert len(sent["messages"]) < len(_long_chat())+ assert _fits(sent, 8_192)+ assert old.gets == ["/v1/models", "/props?model=a-model"]+++def test_a_window_the_request_states_is_kept_over_the_served_one():+ server = _llama_server()+ _, sent = _proxy(+ "llama_cpp",+ _long_chat(),+ handler = server,+ model = "qwen3-next",+ context_overflow = "truncate_oldest",+ context_window = 4_096,+ )+ assert _fits(sent, 4_096)+ assert server.gets == []+++def test_a_server_that_reports_no_window_gets_the_whole_chat():+ silent = _served(models = [{"id": "a-model", "owned_by": "someone"}])+ chunks, sent = _proxy(+ "custom", _long_chat(), handler = silent, context_overflow = "truncate_oldest"+ )+ assert len(sent["messages"]) == len(_long_chat())+ assert _truncations(chunks) == []+++def test_auto_compact_off_never_reads_the_served_window():+ server = _llama_server()+ _, sent = _proxy("llama_cpp", _long_chat(), handler = server, model = "qwen3-next")+ assert len(sent["messages"]) == len(_long_chat())+ assert server.gets == []+++def test_a_hosted_provider_is_not_probed_for_a_window():+ server = _llama_server()+ _, sent = _proxy(+ "openrouter",+ _long_chat(),+ handler = server,+ model = "qwen3-next",+ context_overflow = "truncate_oldest",+ )+ assert len(sent["messages"]) == len(_long_chat())+ assert server.gets == []+++def test_a_tool_enabled_llama_server_chat_compacts_to_the_reported_window(monkeypatch):+ async def connected(self) -> bool:+ return False++ # the tool loop polls for disconnects and would stop before reaching the provider.+ monkeypatch.setattr(Request, "is_disconnected", connected)+ _, sent = _proxy(+ "llama_cpp",+ _long_chat(),+ handler = _llama_server(),+ model = "qwen3-next",+ enable_tools = True,+ enabled_tools = ["python"],+ permission_mode = "off",+ context_overflow = "truncate_oldest",+ )+ assert sent["tools"]+ assert len(sent["messages"]) < len(_long_chat())+ assert sent["messages"][-1]["content"] == "latest question"+++def test_an_unauthorized_read_does_not_hide_the_window_from_a_valid_key():+ server = _served(+ models = [{"id": "a-model", "owned_by": "vllm", "max_model_len": 8_192}], key = "good"+ )+ windows: list = []++ with _Server(handler = server) as upstream:++ async def go() -> None:+ for key in ("bad", "good", "bad", "good"):+ client = ep_mod.ExternalProviderClient(+ provider_type = "vllm", base_url = upstream.base_url, api_key = key+ )+ windows.append(await client.served_context_window("a-model"))++ _run(go)+ assert windows == [None, 8_192, None, 8_192]+ # each credential is read once, then served from the cache.+ assert len(server.gets) == 2+++def test_a_refused_connection_is_not_remembered():+ # a down or restarting server must be queried again on the next turn.+ ep_mod._served_windows.clear()+ windows: list = []++ async def go() -> None:+ client = ep_mod.ExternalProviderClient(+ provider_type = "llama_cpp", base_url = "http://127.0.0.1:9/v1", api_key = None+ )+ windows.append(await client.served_context_window("a-model"))++ _run(go)+ assert windows == [None]+ assert ep_mod._served_windows == {}+++def test_a_stalled_server_costs_one_deadline_and_is_remembered(monkeypatch):+ ep_mod._served_windows.clear()+ monkeypatch.setattr(ep_mod, "_SERVED_WINDOW_TIMEOUT_S", 0.2)+ reads: list[str] = []++ async def stalled(self, model):+ reads.append(model)+ await asyncio.sleep(5)++ monkeypatch.setattr(ep_mod.ExternalProviderClient, "_read_served_window", stalled)+ windows: list = []++ async def go() -> None:+ for _ in range(2):+ client = ep_mod.ExternalProviderClient(+ provider_type = "custom", base_url = "http://127.0.0.1:9/v1", api_key = None+ )+ windows.append(await client.served_context_window("a-model"))++ _run(go)+ assert windows == [None, None]+ assert reads == ["a-model"]diff --git a/studio/frontend/src/features/chat/utils/auto-compaction.ts b/studio/frontend/src/features/chat/utils/auto-compaction.tsindex 56719b2fceb..2fd8184aaef 100644--- a/studio/frontend/src/features/chat/utils/auto-compaction.ts+++ b/studio/frontend/src/features/chat/utils/auto-compaction.ts@@ -26,7 +26,7 @@ export function ggufCompactionRequestFields(options: {return { context_overflow: "truncate_oldest" };}-// Share of the window left free when compaction starts.+// leaves 25% of the window free, matching _EXTERNAL_COMPACTION_HEADROOM for self-hosted serversconst API_COMPACTION_HEADROOM = 0.25;// request schema ceiling for compaction_thresholdconst API_COMPACTION_THRESHOLD_MAX = 2_000_000;@@ -40,7 +40,9 @@ export function apiCompactionRequestFields(options: {context_window?: number;} {const { autoCompactEnabled, contextLength } = options;- if (!autoCompactEnabled || !contextLength || contextLength <= 0) return {};+ if (!autoCompactEnabled) return {};+ // without a catalogued window, the backend reads the self-hosted server's reported window+ if (!contextLength || contextLength <= 0) return { context_overflow: "truncate_oldest" };return {context_overflow: "truncate_oldest",compaction_threshold: Math.min(diff --git a/studio/frontend/tests/auto-compaction-settings.test.ts b/studio/frontend/tests/auto-compaction-settings.test.tsindex 7d0b74ebde3..5eb910547ba 100644--- a/studio/frontend/tests/auto-compaction-settings.test.ts+++ b/studio/frontend/tests/auto-compaction-settings.test.ts@@ -163,17 +163,38 @@ test("a window past the request ceiling still sends a threshold the server accep);});-test("an API model sends nothing with auto-compact off or no published window", () => {+test("an API model sends nothing with auto-compact off", () => {assert.deepEqual(apiCompactionRequestFields({ autoCompactEnabled: false, contextLength: 200_000 }),{},);assert.deepEqual(- apiCompactionRequestFields({ autoCompactEnabled: true, contextLength: null }),+ apiCompactionRequestFields({ autoCompactEnabled: false, contextLength: null }),{},);});+test("a self-hosted connection with no catalogued window still asks the server to compact", async () => {+ const { registerBundlerResolver, installLocalStorageFake } = await import(+ "./helpers/kit.ts"+ );+ registerBundlerResolver();+ installLocalStorageFake();+ const { resolveModelCatalogEntry } = await import(+ "../src/features/chat/model-catalog.ts"+ );+ for (const providerType of ["custom", "llama_cpp", "vllm"]) {+ const contextLength = resolveModelCatalogEntry(providerType, "qwen3-next")?.contextLength;+ assert.equal(contextLength ?? null, null, providerType);+ // the backend derives the threshold from the self-hosted server's reported window+ assert.deepEqual(+ apiCompactionRequestFields({ autoCompactEnabled: true, contextLength }),+ { context_overflow: "truncate_oldest" },+ providerType,+ );+ }+});+test("the external request carries the window the model catalog publishes", async () => {const { registerBundlerResolver, installLocalStorageFake } = await import("./helpers/kit.ts"