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: Open WebUI llama.cpp residency and explicit load/unload (#10610) (#10693)

Debojyoti Banerjeeb865e89586eb
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index daf5fd3394e..054f0a645b2 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -74,6 +74,8 @@ class LoadRequest(BaseModel):
# Auto-switch only: the alias its owner-override lookup used, so the managed path-flag
# check reads the same override row.
_override_alias_id: Optional[str] = PrivateAttr(default = None)
+ # The catalog id a load by path should keep advertising (Open WebUI /models/load).
+ _advertised_id: Optional[str] = PrivateAttr(default = None)
load_request_id: Optional[str] = Field(
None,
min_length = 1,
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index b6657fc3025..eb65fcb2b8d 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -18549,7 +18549,7 @@ async def _load_model_impl(
ollama_advertised_id = (
await asyncio.to_thread(ollama_model_ref_public_id, request.model_path)
if resolved_ollama_path is not None
- else None
+ else request._advertised_id
)
# Version switching is handled by the subprocess-based inference
# backend -- no ensure_transformers_version() needed here.
@@ -18705,6 +18705,8 @@ async def _load_model_impl(
await asyncio.to_thread(acquire_for_request, CHAT)
if replacing:
account_access.join_resident("chat")
+ if request._advertised_id:
+ backend._openai_advertised_id = request._advertised_id
return LoadResponse(
engine = request.engine,
engine_parallelism = request.engine_parallelism,
@@ -19321,7 +19323,7 @@ async def _load_model_impl(
llama_backend._openai_gguf_companion_state = gguf_companion_state
if replacing:
await asyncio.to_thread(note_model_loaded, llama_backend)
- # None elsewhere: only an Ollama load has an identifier no client should be handed.
+ # Else None, or the catalog id a /models/load named: only those loads have an alias to keep.
llama_backend._openai_advertised_id = ollama_advertised_id
# Audio detection moved into load_model under _serial_load_lock (#5642).
@@ -19536,6 +19538,8 @@ async def _load_model_impl(
list(request.gpu_ids) if request.gpu_ids else None
)
+ if request._advertised_id:
+ backend._openai_advertised_id = request._advertised_id
logger.info(
f"Loaded model: {model_log_label if native_grant_backed else config.identifier}"
)
@@ -36499,6 +36503,12 @@ def _servable_catalog_rows(
]
+def _with_openai_residency(entry: dict) -> dict:
+ # Open WebUI's llama.cpp provider reads status.value and calls a row without one loaded (#10610).
+ loaded = bool(entry.get("loaded"))
+ return {**entry, "loaded": loaded, "status": {"value": "loaded" if loaded else "unloaded"}}
+
+
def _audio_cpp_speech_model_objects(created: int) -> list[dict]:
"""Downloaded audio.cpp speech, music and separation GGUFs, found by header in the HF cache. The
cache scan lists a dedicated repo as a GGUF but cannot key an umbrella folder, and none loads in
@@ -36609,10 +36619,11 @@ async def _openai_catalog_objects(quant_pins: bool = False) -> list[dict]:
for obj in media:
by_id.setdefault(obj["id"], obj)
- if not quant_pins or not pins:
- return list(by_id.values())
- # Off-loop: a loaded row on a cold index reads residency from every slot.
- return await asyncio.to_thread(_with_quant_pin_rows, list(by_id.values()), pins)
+ rows = list(by_id.values())
+ if quant_pins and pins:
+ # Off-loop: a loaded row on a cold index reads residency from every slot.
+ rows = await asyncio.to_thread(_with_quant_pin_rows, rows, pins)
+ return [_with_openai_residency(entry) for entry in rows]
def _with_quant_pin_rows(objects: list[dict], pins: dict[str, tuple[str, ...]]) -> list[dict]:
@@ -36756,7 +36767,7 @@ async def openai_retrieve_model(model_id: str, current_subject: str = Depends(ge
for entry in _loaded:
eid = entry["id"]
if isinstance(eid, str) and eid.lower() == model_id.lower():
- return {**entry, "loaded": True}
+ return _with_openai_residency({**entry, "loaded": True})
objects = await _openai_catalog_objects()
for model in objects:
@@ -36784,10 +36795,10 @@ async def openai_retrieve_model(model_id: str, current_subject: str = Depends(ge
if model_id_matches(model_id, raw):
for entry in _loaded:
if entry["id"] == clean:
- return {**entry, "loaded": True}
+ return _with_openai_residency({**entry, "loaded": True})
pinned = await asyncio.to_thread(_pinned_quant_object, model_id, objects)
if pinned is not None:
- return pinned
+ return _with_openai_residency(pinned)
raise HTTPException(
status_code = 404,
detail = openai_error_body(
diff --git a/studio/backend/routes/llama_compat.py b/studio/backend/routes/llama_compat.py
index 310cbf0d1a0..ae6181399f8 100644
--- a/studio/backend/routes/llama_compat.py
+++ b/studio/backend/routes/llama_compat.py
@@ -5,9 +5,10 @@
Probes for engine endpoints used to land on main.py's SPA catch-all, so ``GET /props`` returned 200 and a page
of HTML. That is worse than a 404: a probe reads the status before the body. Served here: ``/props``,
-``/v1/props``, ``/version``, plus a passthrough to the resident llama-server for ``GET /metrics``, ``GET /slots``,
-``POST /tokenize`` and ``POST /detokenize`` (#11705), owner only. Everything else in llama-server's table gets an
-explicit 404, on its real method as well as GET.
+``/v1/props``, ``/version``, a passthrough to the resident llama-server for ``GET /metrics``, ``GET /slots``,
+``POST /tokenize`` and ``POST /detokenize`` (#11705), owner only, and Open WebUI's llama.cpp model management
+(``GET /models``, ``POST /models/load``, ``POST /models/unload``, #10610). Everything else in llama-server's
+table gets an explicit 404, on its real method as well as GET.
Deliberately NOT served: Ollama's ``/api/tags`` and ``/api/show``. Answering them makes a client select Ollama
and then fail on ``/api/chat``, which Studio does not implement; the reporting user's client instead fell back
@@ -23,6 +24,7 @@ from typing import Any, Optional
import httpx
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, Response
+from pydantic import BaseModel, Field
from auth.authentication import get_current_subject
from loggers import get_logger
@@ -78,6 +80,16 @@ _PASSTHROUGH_ROUTES = frozenset(
)
_PASSTHROUGH_TIMEOUT_S = 30.0
+# Open WebUI's llama.cpp model management (#10610). Download, delete and /models/sse stay denied.
+_MANAGEMENT_ROUTES = frozenset(
+ {
+ ("GET", "models"),
+ ("POST", "models/load"),
+ ("POST", "models/unload"),
+ }
+)
+_SERVED_ROUTES = _PASSTHROUGH_ROUTES | _MANAGEMENT_ROUTES
+
# The /v1 entries Studio does not implement. A test asserts each is really absent from
# the assembled app, so implementing one fails CI instead of being shadowed by a 404.
_UNSERVED_V1_PROBE_PATHS = frozenset(
@@ -290,6 +302,201 @@ async def studio_version(current_subject: str = Depends(get_current_subject)):
return {"version": await asyncio.to_thread(_studio_version)}
+class _ModelManageBody(BaseModel):
+ model: str = Field(..., min_length = 1)
+
+
+def _catalog_match(catalog: list[dict], model_id: str) -> Optional[tuple[str, dict, bool]]:
+ """``(id, row, pinned)``: the catalog's own id, or ``model_id`` as ``<listed id>:<quant>`` (pinned)."""
+ wanted = model_id.strip()
+ rows = {e["id"].lower(): e for e in catalog if isinstance(e.get("id"), str)}
+ if wanted.lower() in rows:
+ row = rows[wanted.lower()]
+ return row["id"], row, False
+ from core.inference.openai_auto_download import looks_like_quant
+
+ base, sep, suffix = wanted.rpartition(":")
+ # Only a quant: the resolver maps any other suffix (":latest", ":") back to the bare repo.
+ row = rows.get(base.strip().lower()) if sep and looks_like_quant(suffix) else None
+ return (wanted, row, True) if row is not None else None
+
+
+async def _chat_catalog() -> list[dict]:
+ # A task row (image, video, speech) loads through its own engine, not /load and /unload.
+ rows = await _inference()._openai_catalog_objects(quant_pins = True)
+ return [e for e in rows if e.get("task") is None]
+
+
+async def _catalog_row(model_id: str) -> tuple[str, dict, bool]:
+ # The caller's own catalog, so a managed account only reaches models listed to it.
+ matched = _catalog_match(await _chat_catalog(), model_id)
+ if matched is None:
+ raise HTTPException(status_code = 404, detail = "Model not found")
+ return matched
+
+
+async def _resolve_local(public_id: str) -> Optional[tuple]:
+ from core.inference.local_model_resolver import (
+ resolve_local_gguf,
+ resolve_trusted_cached_local_gguf,
+ )
+ return resolve_trusted_cached_local_gguf(public_id) or await asyncio.to_thread(
+ resolve_local_gguf, public_id
+ )
+
+
+def _same_path(a: Optional[str], b: Optional[str]) -> bool:
+ import os
+ return bool(a and b) and os.path.normpath(a) == os.path.normpath(b)
+
+
+async def _unload_target(model_id: str, row: dict, pinned: bool) -> Optional[str]:
+ """What /unload must be named to stop this row, or None when nothing of it runs.
+
+ /unload matches the resident or loading identifier, not an alias (LM Studio, scan folder,
+ Ollama tag) nor a path-loaded row's listed id, and on a managed install it releases the
+ caller's shared resident before comparing names, so an unrelated row must never reach it.
+ """
+ from core.inference.openai_auto_download import looks_like_quant, split_model_ref
+
+ # Another account's resident is not this caller's to name: answering for it would reveal it.
+ if not row.get("loaded") and await asyncio.to_thread(_resident_hidden_from_caller):
+ return None
+ inf = _inference()
+ resolved = await _resolve_local(model_id)
+ path = resolved[0] if resolved else None
+ base, suffix = split_model_ref(model_id)
+ # Only a quant the caller named: a bare id resolves to the preferred quant, not the resident one.
+ # The resolver's spelling of it, which maps a legacy label (BF16) onto the current quant.
+ wanted_variant = None
+ if suffix and looks_like_quant(suffix):
+ wanted_variant = (resolved[1] if resolved else None) or suffix
+
+ llama = inf.get_llama_cpp_backend()
+ orchestrator = inf._peek_inference_backend()
+ if getattr(llama, "is_loaded", False) or getattr(llama, "is_active", False):
+ candidates = [(llama, llama.model_identifier, getattr(llama, "hf_variant", None))]
+ else:
+ # Loading and active apart: a switch keeps the old model active while the new one loads.
+ loading = getattr(orchestrator, "get_loading_model", lambda: None)()
+ active = getattr(orchestrator, "active_model_name", None)
+ candidates = [(orchestrator, loading, None), (orchestrator, active, None)]
+ for backend, running, running_variant in candidates:
+ if not running:
+ continue
+ advertised = getattr(backend, "_openai_advertised_id", None)
+ # The full id first: an Ollama tag such as "llama3:latest" is the advertised id, not a quant pin.
+ named = _same_path(running, path) or any(
+ advertised and name.strip().lower() == advertised.strip().lower()
+ for name in (model_id, base)
+ )
+ if not named:
+ continue
+ # A pin names one quant: another one, or a backend with none, may sit in a kept slot instead.
+ if wanted_variant and (running_variant or "").lower() != wanted_variant.lower():
+ continue
+ return running
+ filling = inf.model_slots.visible_loading()
+ if filling and _same_path(filling[1], path):
+ return path
+ # A kept slot routes by the listed id inside /unload. A pin through its base row has no
+ # residency of its own: the base row's flag describes whatever quant is resident.
+ return model_id if row.get("loaded") and not pinned else None
+
+
+async def _resolve_load_target(model_id: str):
+ """``(LoadRequest, listed id)``, from the on-disk copy and saved launch settings auto-switch would use."""
+ from core.inference.local_model_resolver import local_target_is_gguf
+ from core.inference.openai_auto_download import split_model_ref
+ from models.inference import LoadRequest
+ from utils.openai_auto_switch_settings import (
+ model_override_load_kwargs,
+ resolve_override_for_load,
+ stored_gpu_index_kind,
+ )
+
+ public_id, _, pinned = await _catalog_row(model_id)
+ resolved = await _resolve_local(public_id)
+ if resolved is None:
+ if pinned:
+ # A quant this machine does not have: no remote download from a catalog-gated route.
+ raise HTTPException(status_code = 404, detail = "Model not found")
+ # The row's own id, colon and all (an NPU "lemonade:..." id is not a quant pin).
+ return LoadRequest(model_path = public_id), public_id
+ model_path, variant, loader_id = resolved[:3]
+ alias = loader_id or split_model_ref(public_id)[0]
+ _, override = resolve_override_for_load(model_path, alias, variant)
+ # Not from the variant: a single-file GGUF or an Ollama tag resolves with no quant to pin.
+ is_gguf = await asyncio.to_thread(local_target_is_gguf, model_path, alias)
+ kwargs = model_override_load_kwargs(override, is_gguf = is_gguf)
+ # A stale pin (GPU removed or renumbered) is dropped, as auto-switch does, rather than 400 the load.
+ if kwargs.get("gpu_ids") and not await _inference()._override_gpu_ids_still_resolve(
+ kwargs["gpu_ids"], stored_gpu_index_kind(override)
+ ):
+ kwargs.pop("gpu_ids", None)
+ kwargs.pop("tensor_split", None)
+ request = LoadRequest(model_path = model_path, gguf_variant = variant, **kwargs)
+ request._override_alias_id = alias
+ request._advertised_id = alias
+ return request, public_id
+
+
+async def _lifecycle_answer(work, model_id: str, *, label: str):
+ """Studio's /load and /unload wrapping (GPU-busy 409, tunnel padding), answered as llama-server does."""
+ from hub.services.models.account_access import gpu_busy_route
+
+ async def _answer():
+ await work
+ # The listed id, never the resident's path; a padded reply serializes this after the stream starts.
+ return {"success": True, "model": model_id}
+
+ @gpu_busy_route
+ async def _padded():
+ return await _inference()._tunnel_safe_json(_answer(), label = label)
+
+ return await _padded()
+
+
+# Outside /v1: Open WebUI strips it for management calls (MODEL_MANAGEMENT_ENDPOINTS).
[email protected]("/models", include_in_schema = False)
[email protected]("/models/", include_in_schema = False)
+async def manage_list_models(current_subject: str = Depends(get_current_subject)):
+ return {"object": "list", "data": await _chat_catalog()}
+
+
[email protected]("/models/load", include_in_schema = False)
[email protected]("/models/load/", include_in_schema = False)
+async def manage_load_model(
+ body: _ModelManageBody,
+ fastapi_request: Request,
+ current_subject: str = Depends(get_current_subject),
+):
+ request, public_id = await _resolve_load_target(body.model)
+ work = _inference().load_model_gated(
+ request, fastapi_request, current_subject, user_initiated = True
+ )
+ return await _lifecycle_answer(work, public_id, label = "Model load")
+
+
[email protected]("/models/unload", include_in_schema = False)
[email protected]("/models/unload/", include_in_schema = False)
+async def manage_unload_model(
+ body: _ModelManageBody, current_subject: str = Depends(get_current_subject)
+):
+ from models.inference import UnloadRequest
+
+ model_id, row, pinned = await _catalog_row(body.model)
+ if pinned and await _resolve_local(model_id) is None:
+ # A quant this machine does not have names nothing running; never the bare model.
+ raise HTTPException(status_code = 404, detail = "Model not found")
+ target = await _unload_target(model_id, row, pinned)
+ if target is None:
+ return {"success": True, "model": model_id}
+ request = UnloadRequest(model_path = target)
+ work = _inference()._unload_model_impl(request, current_subject)
+ return await _lifecycle_answer(work, model_id, label = "Model unload")
+
+
async def _probe_not_found():
raise HTTPException(status_code = 404, detail = "API endpoint not found")
@@ -306,7 +513,7 @@ def _both_forms(path: str) -> tuple:
def _denied_methods(path: str) -> list:
- return [m for m in _PROBE_DENIED_METHODS if (m, path) not in _PASSTHROUGH_ROUTES]
+ return [m for m in _PROBE_DENIED_METHODS if (m, path) not in _SERVED_ROUTES]
for _probe_path in sorted(_ENGINE_PROBE_PATHS):
@@ -343,7 +550,7 @@ def add_get_denials(app) -> None:
none, so these paths matched on method alone and answered 405, which a client reads as "endpoint exists".
"""
for path in sorted(_ENGINE_PROBE_PATHS) + sorted(_UNSERVED_V1_PROBE_PATHS):
- if ("GET", path) in _PASSTHROUGH_ROUTES:
+ if ("GET", path) in _SERVED_ROUTES:
continue
for form in _both_forms(f"/{path}"):
app.add_api_route(form, _probe_not_found, methods = ["GET"], include_in_schema = False)
diff --git a/studio/backend/tests/test_llama_compat_routes.py b/studio/backend/tests/test_llama_compat_routes.py
index 7845fecd789..0c6c6b199a7 100644
--- a/studio/backend/tests/test_llama_compat_routes.py
+++ b/studio/backend/tests/test_llama_compat_routes.py
@@ -91,10 +91,11 @@ def _inference_double(
inference._peek_inference_backend = lambda: orchestrator
inference._orchestrator_public_model_id = lambda b: b.active_model_name
- async def _objects():
+ async def _objects(quant_pins = False):
return catalog
inference._openai_catalog_objects = _objects
+ inference.model_slots = types.SimpleNamespace(visible_loading = lambda: None)
return inference
@@ -368,7 +369,7 @@ def test_no_ui_route_or_public_asset_takes_a_forwarded_get_path():
if not frontend.is_dir():
pytest.skip("frontend sources not present in this checkout")
mod = _load()
- forwarded = {path for method, path in mod._PASSTHROUGH_ROUTES if method == "GET"}
+ forwarded = {path for method, path in mod._SERVED_ROUTES if method == "GET"}
public = (
{p.name.lower() for p in (frontend / "public").iterdir()}
if (frontend / "public").is_dir()
@@ -471,8 +472,10 @@ def test_the_probe_paths_are_admitted_under_keyless_inference_scope():
from utils.keyless_api_access import _INFERENCE_ROUTES
assert ("GET", "/v1/models") in _INFERENCE_ROUTES, "baseline moved; re-derive this"
- for path in ("/props", "/v1/props", "/version"):
+ for path in ("/props", "/v1/props", "/version", "/models"):
assert ("GET", path) in _INFERENCE_ROUTES, path
+ for path in ("/models/load", "/models/unload"):
+ assert ("POST", path) not in _INFERENCE_ROUTES, path
# Not the Ollama paths: they are not served at all.
for path in ("/api/tags", "/api/show", "/api/version"):
assert ("GET", path) not in _INFERENCE_ROUTES, path
@@ -562,7 +565,7 @@ def test_a_bare_llama_route_404s_on_every_method_a_client_would_use():
for path in (
"/chat/completions",
"/responses",
- "/models",
+ "/models/sse",
"/tools",
"/audio/transcriptions",
):
@@ -1018,7 +1021,7 @@ def test_a_get_probe_404s_in_api_only_mode(path):
def test_api_only_mode_still_serves_the_three_real_routes():
mod = _load()
with _api_only_client(mod) as c:
- for path in ("/props", "/v1/props", "/version"):
+ for path in ("/props", "/v1/props", "/version", "/models"):
r = c.get(path)
assert r.status_code == 200, (path, r.status_code)
assert "application/json" in r.headers["content-type"], path
@@ -1078,3 +1081,401 @@ def test_props_hides_a_resident_that_belongs_to_another_account(monkeypatch):
)
with _client(mod) as c:
assert c.get("/props").json()["model_path"] == "unsloth/Qwen3.8-27B-GGUF"
+
+
+# ── Open WebUI llama.cpp model management (#10610) ──────────────────────────
+
+QWEN = "unsloth/Qwen3.8-27B-GGUF"
+
+
+def _management(
+ load_status = 200,
+ catalog = None,
+ backend = None,
+):
+ """The routes double plus Studio's load and unload lifecycle, recording what they were asked."""
+ mod = _load(backend = backend, catalog = catalog)
+ double = mod._inference()
+ calls = []
+
+ async def _load_gated(
+ request,
+ fastapi_request,
+ current_subject,
+ *,
+ user_initiated = False,
+ ):
+ calls.append(("load", request.model_path, request.gguf_variant, request._advertised_id))
+ if load_status != 200:
+ raise HTTPException(status_code = load_status, detail = "busy")
+ return {"status": "loaded", "model": request.model_path}
+
+ async def _unload_impl(request, current_subject):
+ calls.append(("unload", request.model_path))
+ return {"status": "unloaded", "model": request.model_path}
+
+ async def _tunnel_safe_json(coro, *, label):
+ return await coro
+
+ async def _gpu_ids_resolve(gpu_ids, kind):
+ return True
+
+ double.load_model_gated = _load_gated
+ double._unload_model_impl = _unload_impl
+ double._tunnel_safe_json = _tunnel_safe_json
+ double._override_gpu_ids_still_resolve = _gpu_ids_resolve
+ return mod, calls
+
+
+def _no_local_gguf(monkeypatch):
+ import core.inference.local_model_resolver as resolver
+ import utils.openai_auto_switch_settings as overrides
+
+ monkeypatch.setattr(resolver, "resolve_trusted_cached_local_gguf", lambda *a, **k: None)
+ monkeypatch.setattr(resolver, "resolve_local_gguf", lambda *a, **k: None)
+ monkeypatch.setattr(overrides, "resolve_override_for_load", lambda *a, **k: (None, {}))
+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *a, **k: True)
+ return resolver
+
+
+def test_management_list_is_the_v1_chat_catalog():
+ media = {"id": "unsloth/FLUX.2-klein-GGUF", "task": "text-to-image", "loaded": True}
+ mod, _ = _management(catalog = CATALOG + [media])
+ with _client(mod) as c:
+ for path in ("/models", "/models/"):
+ r = c.get(path)
+ assert r.status_code == 200, path
+ assert r.json() == {"object": "list", "data": CATALOG}
+
+
+def test_management_load_resolves_a_listed_id_through_studios_load(_no_local_gguf):
+ mod, calls = _management()
+ with _client(mod) as c:
+ assert c.post("/models/load", json = {"model": QWEN}).status_code == 200
+ # A quant this machine does not have is refused, never fetched.
+ assert c.post("/models/load/", json = {"model": QWEN.lower() + ":Q8_0"}).status_code == 404
+ assert calls == [("load", QWEN, None, None)]
+
+
+def test_management_load_keeps_a_colon_in_an_exact_row_id(_no_local_gguf):
+ """An NPU row such as "lemonade:qwen" is the id itself, not a repo with a quant pin."""
+ row = {"id": "lemonade:qwen", "object": "model", "loaded": True}
+ mod, calls = _management(catalog = [row])
+ with _client(mod) as c:
+ assert c.post("/models/load", json = {"model": "lemonade:qwen"}).status_code == 200
+ assert calls == [("load", "lemonade:qwen", None, None)]
+
+
+def test_management_load_keeps_the_listed_alias_advertised(monkeypatch, _no_local_gguf):
+ """A path load would otherwise reappear in /v1/models under the path's basename."""
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ lambda requested, **k: ("/models/qwen", "UD-Q4_K_XL", "lmstudio-community/qwen"),
+ )
+ mod, calls = _management()
+ with _client(mod) as c:
+ r = c.post("/models/load", json = {"model": QWEN})
+ assert r.status_code == 200
+ # The answer names the listed row, never the on-disk path.
+ assert r.json() == {"success": True, "model": QWEN}
+ assert calls == [("load", "/models/qwen", "UD-Q4_K_XL", "lmstudio-community/qwen")]
+
+
+def test_management_load_applies_saved_launch_settings(monkeypatch, _no_local_gguf):
+ """The settings auto-switch would launch this row with, looked up by path then alias."""
+ import utils.openai_auto_switch_settings as overrides
+
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ # A single-file GGUF resolves with no quant, and is still llama.cpp's.
+ lambda requested, **k: ("/models/qwen.gguf", None, QWEN),
+ )
+ asked = []
+
+ def _override(
+ load_id,
+ alias_id = None,
+ variant = None,
+ ):
+ asked.append((load_id, alias_id, variant))
+ return load_id, {"n_parallel": 2, "kv_cache_dtype": "q8_0", "gpu_layers": 20}
+
+ monkeypatch.setattr(overrides, "resolve_override_for_load", _override)
+ mod, _ = _management()
+ seen = []
+ double = mod._inference()
+ original = double.load_model_gated
+
+ async def _capture(request, *args, **kwargs):
+ seen.append((request.n_parallel, request.cache_type_kv, request.gpu_layers))
+ return await original(request, *args, **kwargs)
+
+ double.load_model_gated = _capture
+ with _client(mod) as c:
+ assert c.post("/models/load", json = {"model": QWEN}).status_code == 200
+ assert asked == [("/models/qwen.gguf", QWEN, None)]
+ assert seen == [(2, "q8_0", 20)]
+
+
+def test_management_unload_maps_the_advertised_alias_to_the_resident(_no_local_gguf):
+ """/unload matches the resident's identifier, not an alias such as an LM Studio name."""
+ mod, calls = _management()
+ with _client(mod) as c:
+ r = c.post("/models/unload", json = {"model": QWEN.lower()})
+ assert r.status_code == 200
+ # The answer names the listed id, never the resident's path.
+ assert r.json() == {"success": True, "model": QWEN}
+ assert calls == [("unload", "/media/models/qwen/model.gguf")]
+
+
+def test_management_unload_of_an_idle_row_never_reaches_the_lifecycle(_no_local_gguf):
+ """/unload releases a managed account's shared resident before it compares names."""
+ mod, calls = _management()
+ with _client(mod) as c:
+ r = c.post("/models/unload", json = {"model": CATALOG[1]["id"]})
+ assert r.json() == {"success": True, "model": CATALOG[1]["id"]}
+ assert calls == []
+
+
+def test_management_unload_cancels_a_load_under_the_path_it_runs_as(monkeypatch, _no_local_gguf):
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ lambda requested, **k: ("/models/laguna", "Q4_K_M", requested),
+ )
+ backend = _Backend(loaded = False)
+ backend.is_active = True
+ backend.model_identifier = "/models/laguna"
+ backend._openai_advertised_id = None
+ mod, calls = _management(backend = backend)
+ with _client(mod) as c:
+ assert c.post("/models/unload", json = {"model": CATALOG[1]["id"]}).status_code == 200
+ assert calls == [("unload", "/models/laguna")]
+
+
[email protected]("path", ["/models/load", "/models/unload"])
+def test_management_rejects_unlisted_task_or_missing_models(path, _no_local_gguf):
+ media = {"id": "unsloth/FLUX.2-klein-GGUF", "task": "text-to-image", "loaded": True}
+ mod, calls = _management(catalog = CATALOG + [media])
+ with _client(mod) as c:
+ assert c.post(path, json = {"model": "someone/else"}).status_code == 404
+ # Image, video and speech rows load through their own engines, not /load and /unload.
+ assert c.post(path, json = {"model": media["id"]}).status_code == 404
+ assert c.post(path, json = {"model": ""}).status_code == 422
+ assert c.post(path, json = {}).status_code == 422
+ assert calls == []
+
+
+def test_management_load_keeps_studios_error_status(_no_local_gguf):
+ mod, _ = _management(load_status = 409)
+ with _client(mod) as c:
+ assert c.post("/models/load", json = {"model": QWEN}).status_code == 409
+
+
+def test_management_requires_a_credential():
+ mod, calls = _management()
+ app = FastAPI()
+ app.include_router(mod.router)
+ with TestClient(app) as c:
+ assert c.get("/models").status_code == 401
+ for path in ("/models/load", "/models/unload"):
+ assert c.post(path, json = {"model": QWEN}).status_code == 401
+ assert calls == []
+
+
+ "method, path",
+ [
+ ("POST", "/models"),
+ ("DELETE", "/models"),
+ ("HEAD", "/models/load"),
+ ("GET", "/models/load"),
+ ("GET", "/models/unload"),
+ ("GET", "/models/sse"),
+ ],
+)
+def test_unserved_management_operations_still_404(method, path):
+ mod, _ = _management()
+ with _client(mod) as c:
+ r = c.request(method, path, json = {} if method == "POST" else None)
+ assert r.status_code == 404, (method, path, r.status_code)
+ assert "text/html" not in r.headers.get("content-type", "")
+
+
+def test_management_unload_matches_an_ollama_tag_before_its_suffix(_no_local_gguf):
+ """ ":latest" is part of the advertised Ollama id, not a quant pin to strip first."""
+ tag = "ollama/llama3:latest"
+ backend = _Backend()
+ backend.model_identifier = "ollama-manifest:/models/llama3/latest"
+ backend._openai_advertised_id = tag
+ mod = _load(backend = backend, catalog = [{"id": tag, "object": "model", "loaded": True}])
+ calls = []
+
+ async def _unload_impl(request, current_subject):
+ calls.append(request.model_path)
+
+ async def _tunnel_safe_json(coro, *, label):
+ return await coro
+
+ mod._inference()._unload_model_impl = _unload_impl
+ mod._inference()._tunnel_safe_json = _tunnel_safe_json
+ with _client(mod) as c:
+ r = c.post("/models/unload", json = {"model": tag})
+ assert r.json() == {"success": True, "model": tag}
+ assert calls == ["ollama-manifest:/models/llama3/latest"]
+
+
+def test_management_unload_finds_a_path_loaded_row_with_no_alias_stamp(monkeypatch, _no_local_gguf):
+ """A Studio load by path advertises nothing, yet the catalog lists the row under its own id."""
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ lambda requested, **k: ("/models/lms/qwen", None, requested),
+ )
+ backend = _Backend()
+ backend.model_identifier = "/models/lms/qwen"
+ backend._openai_advertised_id = None
+ mod, calls = _management(backend = backend)
+ with _client(mod) as c:
+ assert c.post("/models/unload", json = {"model": QWEN}).status_code == 200
+ assert calls == [("unload", "/models/lms/qwen")]
+
+
+def test_management_unload_leaves_an_unrelated_load_alone(monkeypatch, _no_local_gguf):
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ lambda requested, **k: ("/models/laguna", None, requested),
+ )
+ backend = _Backend(loaded = False)
+ backend.is_active = True
+ backend.model_identifier = "/models/other"
+ backend._openai_advertised_id = None
+ mod, calls = _management(backend = backend)
+ with _client(mod) as c:
+ assert c.post("/models/unload", json = {"model": CATALOG[1]["id"]}).status_code == 200
+ assert calls == []
+
+
+def test_management_unload_keeps_a_resident_of_another_quant(monkeypatch, _no_local_gguf):
+ # Both quants are on disk; only the resident one may be unloaded.
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ lambda requested, **k: (
+ "/media/models/qwen/model.gguf",
+ requested.rpartition(":")[2],
+ QWEN,
+ ),
+ )
+ backend = _Backend()
+ backend.hf_variant = "UD-Q4_K_XL"
+ mod, calls = _management(backend = backend)
+ with _client(mod) as c:
+ assert c.post("/models/unload", json = {"model": QWEN + ":Q8_0"}).status_code == 200
+ assert c.post("/models/unload", json = {"model": QWEN + ":UD-Q4_K_XL"}).status_code == 200
+ assert calls == [("unload", "/media/models/qwen/model.gguf")]
+
+
+def test_management_unload_of_a_bare_id_ignores_the_preferred_quant(monkeypatch, _no_local_gguf):
+ """A bare id resolves to the preferred quant on disk, which need not be the resident one."""
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ lambda requested, **k: ("/media/models/qwen/model.gguf", "Q4_K_M", requested),
+ )
+ backend = _Backend()
+ backend.hf_variant = "Q8_0"
+ mod, calls = _management(backend = backend)
+ with _client(mod) as c:
+ assert c.post("/models/unload", json = {"model": QWEN}).status_code == 200
+ assert calls == [("unload", "/media/models/qwen/model.gguf")]
+
+
+def test_management_unload_cancels_a_switch_while_the_old_model_stays_active(
+ monkeypatch, _no_local_gguf
+):
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ lambda requested, **k: ("/models/laguna", None, requested),
+ )
+ orchestrator = types.SimpleNamespace(
+ active_model_name = "/models/old",
+ get_loading_model = lambda: "/models/laguna",
+ _openai_advertised_id = None,
+ )
+ mod = _load(backend = _Backend(loaded = False), orchestrator = orchestrator)
+ double = mod._inference()
+ calls = []
+
+ async def _unload_impl(request, current_subject):
+ calls.append(request.model_path)
+
+ async def _tunnel_safe_json(coro, *, label):
+ return await coro
+
+ double._unload_model_impl = _unload_impl
+ double._tunnel_safe_json = _tunnel_safe_json
+ with _client(mod) as c:
+ assert c.post("/models/unload", json = {"model": CATALOG[1]["id"]}).status_code == 200
+ assert calls == ["/models/laguna"]
+
+
+def test_management_unload_refuses_a_pin_this_machine_does_not_have(_no_local_gguf):
+ mod, calls = _management()
+ with _client(mod) as c:
+ assert c.post("/models/unload", json = {"model": QWEN + ":Q8_0"}).status_code == 404
+ assert calls == []
+
+
+def test_management_unload_never_reaches_another_accounts_resident(monkeypatch):
+ """The caller's catalog shows the row unloaded; matching the global resident would reveal it."""
+ mod, calls = _management(catalog = [{**CATALOG[0], "loaded": False}])
+ monkeypatch.setattr(mod, "_resident_hidden_from_caller", lambda: True)
+ with _client(mod) as c:
+ r = c.post("/models/unload", json = {"model": QWEN})
+ assert r.json() == {"success": True, "model": QWEN}
+ assert calls == []
+
+
[email protected]("suffix", ["latest", ""])
+def test_management_refuses_a_suffix_that_is_not_a_quant(suffix):
+ mod, calls = _management()
+ with _client(mod) as c:
+ for path in ("/models/load", "/models/unload"):
+ assert c.post(path, json = {"model": f"{QWEN}:{suffix}"}).status_code == 404, path
+ assert calls == []
+
+
+def test_management_unload_compares_a_legacy_pin_by_its_resolved_quant(monkeypatch, _no_local_gguf):
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ lambda requested, **k: ("/media/models/qwen/model.gguf", "Q4_K_M", QWEN),
+ )
+ backend = _Backend()
+ backend.hf_variant = "Q4_K_M"
+ mod, calls = _management(backend = backend)
+ with _client(mod) as c:
+ assert c.post("/models/unload", json = {"model": QWEN + ":BF16"}).status_code == 200
+ assert calls == [("unload", "/media/models/qwen/model.gguf")]
+
+
+def test_management_unload_routes_a_kept_slot_quant_past_the_primary(monkeypatch, _no_local_gguf):
+ """Q4 on the primary, Q8 kept in a slot: the Q8 pin goes to /unload, which routes it to the slot."""
+ monkeypatch.setattr(
+ _no_local_gguf,
+ "resolve_local_gguf",
+ lambda requested, **k: ("/media/models/qwen/model.gguf", "Q8_0", QWEN),
+ )
+ backend = _Backend()
+ backend.hf_variant = "Q4_K_M"
+ pin = {"id": QWEN + ":Q8_0", "object": "model", "loaded": True}
+ mod, calls = _management(backend = backend, catalog = CATALOG + [pin])
+ with _client(mod) as c:
+ assert c.post("/models/unload", json = {"model": pin["id"]}).status_code == 200
+ assert calls == [("unload", pin["id"])]
diff --git a/studio/backend/tests/test_openai_catalog.py b/studio/backend/tests/test_openai_catalog.py
index 42f20a182df..50960523a40 100644
--- a/studio/backend/tests/test_openai_catalog.py
+++ b/studio/backend/tests/test_openai_catalog.py
@@ -88,9 +88,11 @@ def test_catalog_lists_loaded_and_available(monkeypatch):
# Loaded model is present, marked loaded, and keeps context fields.
assert ids["Qwen3-Q4"]["loaded"] is True
+ assert ids["Qwen3-Q4"]["status"] == {"value": "loaded"}
assert ids["Qwen3-Q4"]["context_length"] == 4096
# Not-loaded GGUFs are listed too, with the quant a client appends to pin them.
assert ids["Llama-8B-Q8"]["loaded"] is False
+ assert ids["Llama-8B-Q8"]["status"] == {"value": "unloaded"}
assert ids["Llama-8B-Q8"]["quant"] == "Q8_0"
# The HF-cache GGUF is listed despite model_format being unset.
assert ids["org/Foo"]["loaded"] is False
@@ -163,6 +165,7 @@ def test_a_manually_loaded_non_gguf_model_has_one_catalog_row(monkeypatch):
"owned_by": "unsloth-studio",
"context_length": 8192,
"loaded": True,
+ "status": {"value": "loaded"},
}
]
@@ -280,6 +283,7 @@ def test_retrieve_loaded_model_skips_catalog_scan(monkeypatch):
model = asyncio.run(inf.openai_retrieve_model("Qwen3-Q4", current_subject = "t"))
assert model["id"] == "Qwen3-Q4"
assert model["loaded"] is True
+ assert model["status"] == {"value": "loaded"}
def test_cached_local_catalog_offloads_and_caches(monkeypatch):
@@ -598,6 +602,8 @@ def test_retrieve_resolves_an_on_disk_quant_pin(monkeypatch):
assert model["id"] == "publisher/Qwen3:Q4_K_M"
assert model["quant"] == "Q4_K_M"
assert model["loaded"] is False
+ # Open WebUI's llama.cpp provider calls a row without status loaded.
+ assert model["status"] == {"value": "unloaded"}
def test_retrieve_pin_of_the_resident_quant_keeps_its_loaded_fields(monkeypatch):
@@ -743,6 +749,7 @@ def test_list_names_every_on_disk_quant_of_a_multi_quant_repo(monkeypatch):
"owned_by": "unsloth-studio",
"display_name": "Qwen3",
"loaded": False,
+ "status": {"value": "unloaded"},
"quant": "Q4_K_M",
}
# Every listed pin retrieves as the same object, so validating clients accept it.
diff --git a/studio/backend/utils/keyless_api_access.py b/studio/backend/utils/keyless_api_access.py
index 03b6d32e7f0..09db469b457 100644
--- a/studio/backend/utils/keyless_api_access.py
+++ b/studio/backend/utils/keyless_api_access.py
@@ -45,6 +45,8 @@ _INFERENCE_ROUTES = frozenset(
("GET", "/props"),
("GET", "/v1/props"),
("GET", "/version"),
+ # /v1/models for Open WebUI's management view; /models/load and /models/unload stay keyed.
+ ("GET", "/models"),
# Token counters, like /v1/chat/count_tokens. Not /slots or /metrics: those are server-wide.
("POST", "/tokenize"),
("POST", "/detokenize"),