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: list the full local model catalog from /v1/models (#6519)
Daniel Hanb11966b2db75
diff --git a/studio/backend/core/inference/model_ids.py b/studio/backend/core/inference/model_ids.pyindex 4d409cb4b54..548cc60f94a 100644--- a/studio/backend/core/inference/model_ids.py+++ b/studio/backend/core/inference/model_ids.py@@ -55,3 +55,17 @@ def public_model_id(identifier: Optional[str]) -> Optional[str]:if name.lower().endswith(_GGUF_SUFFIX):name = name[: -len(_GGUF_SUFFIX)]return name or identifier+++def model_id_matches(requested: Optional[str], internal: Optional[str]) -> bool:+ """Whether a client-supplied *requested* id refers to *internal*.++ Accepts the clean public id (preferred) and, for backward compatibility, the+ raw internal identifier (e.g. a legacy absolute path a client cached from an+ older ``/v1/models`` response).+ """+ if requested is None or internal is None:+ return False+ if requested == internal:+ return True+ return public_model_id(internal) == requesteddiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 1061542ca65..caf2a262a31 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -6391,6 +6391,9 @@ async def serve_sandbox_file(# OpenAI-Compatible Models Listing (/models → /v1/models)# =====================================================================+# `owned_by` marker on every /v1/models entry (loaded and available alike).+_OWNED_BY = "unsloth-studio"+def _openai_model_objects() -> list[dict]:"""The model objects GET /v1/models exposes (one per loaded local backend).@@ -6410,7 +6413,7 @@ def _openai_model_objects() -> list[dict]:"id": public_model_id(llama_backend.model_identifier),"object": "model","created": _created,- "owned_by": "local",+ "owned_by": _OWNED_BY,}_ctx = _positive_int_or_none(getattr(llama_backend, "context_length", None))if _ctx is not None:@@ -6431,7 +6434,7 @@ def _openai_model_objects() -> list[dict]:"id": public_model_id(backend.active_model_name),"object": "model","created": _created,- "owned_by": "local",+ "owned_by": _OWNED_BY,}_ctx = _positive_int_or_none(model_info.get("context_length"))if _ctx is None:@@ -6449,15 +6452,86 @@ def _openai_model_objects() -> list[dict]:return models+# Brief cache for the local-model filesystem scan so repeated /v1/models calls+# don't rescan the HF cache and models dirs on every request.+_CATALOG_CACHE: dict = {"at": 0.0, "models": []}+_CATALOG_TTL_S = 30.0+_CATALOG_LOCK = asyncio.Lock()+++async def _cached_local_catalog() -> list:+ """Locally available models (models dir + HF caches + LM Studio + scan+ folders), cached for a few seconds. Returns a list of LocalModelInfo.++ The scan walks several directories and stats many files, so it runs in a+ worker thread (asyncio.to_thread) -- calling it inline would block the event+ loop and stall every concurrent request and in-flight inference stream. A+ lock with a double-check collapses a burst of simultaneous /v1/models calls+ into a single scan instead of one per request."""+ # Validity is keyed on "at" (set only after a scan), not on list contents, so+ # an empty/errored scan is still cached instead of rescanning on every poll.+ now = time.monotonic()+ if _CATALOG_CACHE["at"] and (now - _CATALOG_CACHE["at"]) <= _CATALOG_TTL_S:+ return _CATALOG_CACHE["models"]+ async with _CATALOG_LOCK:+ now = time.monotonic()+ if _CATALOG_CACHE["at"] and (now - _CATALOG_CACHE["at"]) <= _CATALOG_TTL_S:+ return _CATALOG_CACHE["models"]+ try:+ from routes.models import collect_local_models+ _CATALOG_CACHE["models"] = await asyncio.to_thread(+ collect_local_models, Path("./models").resolve()+ )+ except Exception as exc:+ logger.debug("model catalog scan failed: %s", exc)+ _CATALOG_CACHE["models"] = []+ # Stamp after the scan, not the pre-scan "now": a scan slower than the TTL+ # would otherwise leave the cache already expired, so every waiter rescans.+ _CATALOG_CACHE["at"] = time.monotonic()+ return _CATALOG_CACHE["models"]+++async def _openai_catalog_objects() -> list[dict]:+ """Every model the server knows about for ``GET /v1/models``: the loaded+ model(s) plus locally available (downloaded/cached) models discovered by+ scanning. Loaded entries keep their context fields and are marked+ ``loaded: true``. All ids are clean public ids (never absolute paths)."""+ _created = int(time.time())+ # Loaded models first (clean ids + context fields), marked loaded.+ by_id: dict[str, dict] = {}+ for entry in _openai_model_objects():+ by_id[entry["id"]] = {**entry, "loaded": True}++ # Locally available (downloaded/cached) models that are not already loaded.+ for info in await _cached_local_catalog():+ cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))+ if not cid or cid in by_id:+ continue+ obj = {+ "id": cid,+ "object": "model",+ "created": _created,+ "owned_by": _OWNED_BY,+ "loaded": False,+ }+ display = getattr(info, "display_name", None)+ if display:+ obj["display_name"] = display+ by_id[cid] = obj++ return list(by_id.values())++@router.get("/models")async def openai_list_models(current_subject: str = Depends(get_current_subject)):"""- OpenAI-compatible model listing endpoint.+ OpenAI-compatible model listing endpoint (``GET /v1/models``).- Returns the currently loaded model in the format expected by- OpenAI-compatible clients (``GET /v1/models``).+ Lists every model available on this server -- the loaded model(s) plus+ locally available (downloaded/cached) models -- not only what is resident in+ memory. Each entry carries a clean public id and a ``loaded`` flag."""- return {"object": "list", "data": _openai_model_objects()}+ return {"object": "list", "data": await _openai_catalog_objects()}@router.get("/models/{model_id:path}")@@ -6465,11 +6539,20 @@ async def openai_retrieve_model(model_id: str, current_subject: str = Depends(ge"""OpenAI-compatible single-model retrieval endpoint (``GET /v1/models/{id}``).- Returns the bare model object when ``model_id`` matches a loaded local- model, or 404 model_not_found otherwise. Defined after the LIST route so- it does not shadow it; ``{model_id:path}`` keeps ids with slashes intact.+ Returns the bare model object when ``model_id`` matches a known model+ (loaded or locally available), or 404 model_not_found otherwise. Defined+ after the LIST route so it does not shadow it; ``{model_id:path}`` keeps ids+ with slashes intact."""- objects = _openai_model_objects()+ from core.inference.model_ids import model_id_matches++ # Loaded models resolve without a catalog scan (the common case); only build+ # the full catalog -- which may hit the filesystem -- for unloaded ids.+ for entry in _openai_model_objects():+ if entry["id"] == model_id:+ return {**entry, "loaded": True}++ objects = await _openai_catalog_objects()for model in objects:if model["id"] == model_id:return model@@ -6482,7 +6565,7 @@ async def openai_retrieve_model(model_id: str, current_subject: str = Depends(gellama_backend.model_identifier if llama_backend.is_loaded else None,backend.active_model_name or None,):- if raw and model_id == raw:+ if raw and model_id_matches(model_id, raw):clean = public_model_id(raw)for model in objects:if model["id"] == clean:diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 951c2960f3a..e22f65751c9 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -722,6 +722,94 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Locareturn found+def collect_local_models(models_root: Path) -> List[LocalModelInfo]:+ """Scan ``models_root``, the HF caches, LM Studio dirs, and user scan folders,+ returning a deduplicated, hidden-filtered list of discovered local models.++ Shared by ``GET /models/local`` (the model picker) and the OpenAI-compatible+ catalog (``GET /v1/models``) so the UI and the API never drift. ``models_root``+ must already be validated/trusted by the caller.+ """+ from storage.studio_db import list_scan_folders+ from utils.paths import (+ hf_default_cache_dir,+ legacy_hf_cache_dir,+ lmstudio_model_dirs,+ )++ hf_cache_dir = _resolve_hf_cache_dir()+ legacy_hf = legacy_hf_cache_dir()+ hf_default = hf_default_cache_dir()+ lm_dirs = lmstudio_model_dirs()++ local_models = _scan_models_dir(models_root) + _scan_hf_cache(hf_cache_dir)++ # Resolve once; an inaccessible aux cache must skip that scan, not 500.+ hf_cache_real = _safe_resolve(hf_cache_dir)+ legacy_real = _safe_resolve(legacy_hf)+ default_real = _safe_resolve(hf_default)++ # Scan legacy Unsloth HF cache for backward compatibility.+ if _safe_is_dir(legacy_hf) and legacy_real != hf_cache_real:+ local_models += _scan_hf_cache(legacy_hf)++ # Scan HF system default cache (may differ under env overrides).+ if _safe_is_dir(hf_default) and default_real != hf_cache_real and default_real != legacy_real:+ local_models += _scan_hf_cache(hf_default)++ # Scan LM Studio directories.+ for lm_dir in lm_dirs:+ local_models += _scan_lmstudio_dir(lm_dir)++ # Scan user-added custom folders (per-folder cap).+ _MAX_MODELS_PER_FOLDER = 200+ try:+ custom_folders = list_scan_folders()+ except Exception as e:+ logger.warning("Could not load custom scan folders: %s", e)+ custom_folders = []+ for folder in custom_folders:+ folder_path = Path(folder["path"])+ try:+ # Filter Ollama .studio_links/ from generic scanners to+ # avoid duplicates and leaking internal paths into the UI.+ _generic = [+ m+ for m in (+ _scan_models_dir(folder_path, limit = _MAX_MODELS_PER_FOLDER)+ + _scan_hf_cache(folder_path)+ + _scan_lmstudio_dir(folder_path)+ )+ if not any(p in (".studio_links", "ollama_links") for p in Path(m.path).parts)+ ]+ custom_models = _generic+ if len(custom_models) < _MAX_MODELS_PER_FOLDER:+ custom_models += _scan_ollama_dir(+ folder_path,+ limit = _MAX_MODELS_PER_FOLDER - len(custom_models),+ )+ except OSError as e:+ logger.warning("Skipping unreadable scan folder %s: %s", folder_path, e)+ continue+ local_models += [m.model_copy(update = {"source": "custom"}) for m in custom_models]++ # Deduplicate, but always keep custom folder entries (keyed by+ # (id, source)) so they show in the "Custom Folders" UI section+ # even when the model is also in the HF cache.+ deduped: dict[str, LocalModelInfo] = {}+ for model in local_models:+ key = f"{model.id}\x00custom" if model.source == "custom" else model.id+ if key not in deduped:+ deduped[key] = model++ models = sorted(+ deduped.values(),+ key = lambda item: (item.updated_at or 0),+ reverse = True,+ )+ return [m for m in models if not _is_hidden_model(m.id, m.path)]++@router.get("/local", response_model = LocalModelListResponse)async def list_local_models(models_dir: str = Query(@@ -770,78 +858,7 @@ async def list_local_models()try:- local_models = _scan_models_dir(models_root) + _scan_hf_cache(hf_cache_dir)-- # Resolve once; an inaccessible aux cache must skip that scan, not 500.- hf_cache_real = _safe_resolve(hf_cache_dir)- legacy_real = _safe_resolve(legacy_hf)- default_real = _safe_resolve(hf_default)-- # Scan legacy Unsloth HF cache for backward compatibility.- if _safe_is_dir(legacy_hf) and legacy_real != hf_cache_real:- local_models += _scan_hf_cache(legacy_hf)-- # Scan HF system default cache (may differ under env overrides).- if (- _safe_is_dir(hf_default)- and default_real != hf_cache_real- and default_real != legacy_real- ):- local_models += _scan_hf_cache(hf_default)-- # Scan LM Studio directories.- for lm_dir in lm_dirs:- local_models += _scan_lmstudio_dir(lm_dir)-- # Scan user-added custom folders (per-folder cap).- from storage.studio_db import list_scan_folders-- _MAX_MODELS_PER_FOLDER = 200- try:- custom_folders = list_scan_folders()- except Exception as e:- logger.warning("Could not load custom scan folders: %s", e)- custom_folders = []- for folder in custom_folders:- folder_path = Path(folder["path"])- try:- # Filter Ollama .studio_links/ from generic scanners to- # avoid duplicates and leaking internal paths into the UI.- _generic = [- m- for m in (- _scan_models_dir(folder_path, limit = _MAX_MODELS_PER_FOLDER)- + _scan_hf_cache(folder_path)- + _scan_lmstudio_dir(folder_path)- )- if not any(p in (".studio_links", "ollama_links") for p in Path(m.path).parts)- ]- custom_models = _generic- if len(custom_models) < _MAX_MODELS_PER_FOLDER:- custom_models += _scan_ollama_dir(- folder_path,- limit = _MAX_MODELS_PER_FOLDER - len(custom_models),- )- except OSError as e:- logger.warning("Skipping unreadable scan folder %s: %s", folder_path, e)- continue- local_models += [m.model_copy(update = {"source": "custom"}) for m in custom_models]-- # Deduplicate, but always keep custom folder entries (keyed by- # (id, source)) so they show in the "Custom Folders" UI section- # even when the model is also in the HF cache.- deduped: dict[str, LocalModelInfo] = {}- for model in local_models:- key = f"{model.id}\x00custom" if model.source == "custom" else model.id- if key not in deduped:- deduped[key] = model-- models = sorted(- deduped.values(),- key = lambda item: (item.updated_at or 0),- reverse = True,- )- models = [m for m in models if not _is_hidden_model(m.id, m.path)]+ models = collect_local_models(models_root)return LocalModelListResponse(models_dir = str(models_root),diff --git a/studio/backend/tests/test_model_ids.py b/studio/backend/tests/test_model_ids.pyindex 1b0cd927d8f..f9116afec37 100644--- a/studio/backend/tests/test_model_ids.py+++ b/studio/backend/tests/test_model_ids.py@@ -8,7 +8,7 @@ _BACKEND = Path(__file__).resolve().parents[1]if str(_BACKEND) not in sys.path:sys.path.insert(0, str(_BACKEND))-from core.inference.model_ids import public_model_id # noqa: E402+from core.inference.model_ids import model_id_matches, public_model_id # noqa: E402def test_local_gguf_path_becomes_clean_stem():@@ -51,3 +51,12 @@ def test_dotted_repo_id_not_mistaken_for_relative_path():# A leading dot that is not ./ or ../ is an ordinary clean name.assert public_model_id(".hidden-model") == ".hidden-model"assert public_model_id("org/.config") == "org/.config"+++def test_matches_clean_and_legacy():+ path = "/srv/models/Qwen3-Q4.gguf"+ assert model_id_matches("Qwen3-Q4", path) # clean public id+ assert model_id_matches(path, path) # legacy raw path+ assert not model_id_matches("other", path)+ assert not model_id_matches(None, path)+ assert not model_id_matches("x", None)diff --git a/studio/backend/tests/test_openai_catalog.py b/studio/backend/tests/test_openai_catalog.pynew file mode 100644index 00000000000..f9baf20a66d--- /dev/null+++ b/studio/backend/tests/test_openai_catalog.py@@ -0,0 +1,181 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""GET /v1/models lists the full server catalog (loaded + locally available)."""++import asyncio+import json+import sys+from pathlib import Path++_BACKEND = Path(__file__).resolve().parents[1]+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++import routes.inference as inf # noqa: E402+++class _Info:+ def __init__(+ self,+ id,+ display_name,+ model_id = None,+ ):+ self.id = id+ self.display_name = display_name+ self.model_id = model_id+++class _FakeLlama:+ is_loaded = True+ model_identifier = "/srv/models/Qwen3-Q4.gguf"+ context_length = 4096+ max_context_length = None+ native_context_length = None++ def __init__(self, loaded = True):+ self.is_loaded = loaded+++class _FakeUnsloth:+ active_model_name = None+ models: dict = {}+ context_length = None+ max_seq_length = None+++def test_catalog_lists_loaded_and_available(monkeypatch):+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama())+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _FakeUnsloth())++ async def _fake_catalog():+ return [+ _Info("/data/models/Qwen3-Q4.gguf", "Qwen3-Q4"), # same as loaded -> dedup+ _Info("/data/models/Llama-8B-Q8.gguf", "Llama-8B-Q8"), # available, not loaded+ _Info("models--org--Foo", "Foo", model_id = "org/Foo"), # hf cache repo id+ ]++ monkeypatch.setattr(inf, "_cached_local_catalog", _fake_catalog)++ data = asyncio.run(inf._openai_catalog_objects())+ ids = {m["id"]: m for m in data}++ # Loaded model is present, marked loaded, and keeps context fields.+ assert ids["Qwen3-Q4"]["loaded"] is True+ assert ids["Qwen3-Q4"]["context_length"] == 4096+ # Available-but-not-loaded models are listed too.+ assert ids["Llama-8B-Q8"]["loaded"] is False+ assert ids["org/Foo"]["loaded"] is False+ # The loaded gguf and the on-disk copy collapse to one clean id.+ assert [m["id"] for m in data].count("Qwen3-Q4") == 1+ # No absolute paths or .gguf suffixes leak anywhere.+ blob = json.dumps(data)+ assert ".gguf" not in blob+ assert "/srv/" not in blob+ assert "/data/" not in blob+++def test_empty_and_errored_scans_are_cached(monkeypatch):+ # Cache validity is keyed on the timestamp, not list contents, so an empty+ # (fresh install / no local models) or errored scan is still cached for the+ # TTL instead of rescanning the filesystem on every /v1/models poll.+ import routes.models as models_mod+ for outcome in ("empty", "error"):+ calls = {"n": 0}++ def _scan(_root, _outcome = outcome):+ calls["n"] += 1+ if _outcome == "error":+ raise RuntimeError("scan blew up")+ return []++ monkeypatch.setattr(models_mod, "collect_local_models", _scan)+ monkeypatch.setattr(inf, "_CATALOG_CACHE", {"at": 0.0, "models": []})++ async def _run():+ return [await inf._cached_local_catalog() for _ in range(3)]++ results = asyncio.run(_run())+ assert results == [[], [], []], outcome+ assert calls["n"] == 1, f"{outcome} scan ran {calls['n']}x (TTL not honored)"+++def test_catalog_ttl_starts_after_scan_completes(monkeypatch):+ # The cache timestamp must be taken AFTER the scan, not before it. A scan that+ # outlives the TTL would otherwise leave the cache born-expired, so the next+ # caller rescans instead of reusing the just-computed catalog.+ import routes.models as models_mod++ clock = {"t": 1000.0}+ monkeypatch.setattr(inf.time, "monotonic", lambda: clock["t"])+ monkeypatch.setattr(inf, "_CATALOG_CACHE", {"at": 0.0, "models": []})++ calls = {"n": 0}++ def _slow_scan(_root):+ calls["n"] += 1+ clock["t"] += inf._CATALOG_TTL_S + 10 # the scan itself outlives the TTL+ return [_Info("/m/A.gguf", "A")]++ monkeypatch.setattr(models_mod, "collect_local_models", _slow_scan)++ async def _run():+ first = await inf._cached_local_catalog()+ second = await inf._cached_local_catalog() # clock unchanged since scan end+ return first, second++ first, second = asyncio.run(_run())+ assert [i.id for i in first] == ["/m/A.gguf"]+ assert calls["n"] == 1, "TTL started before the scan -> cache born expired, rescanned"+++def test_retrieve_loaded_model_skips_catalog_scan(monkeypatch):+ # Retrieving a loaded id must resolve from the loaded set alone, never paying+ # for the filesystem scan that _cached_local_catalog drives.+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama())+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _FakeUnsloth())++ async def _boom():+ raise AssertionError("catalog scan must not run for a loaded id")++ monkeypatch.setattr(inf, "_cached_local_catalog", _boom)++ model = asyncio.run(inf.openai_retrieve_model("Qwen3-Q4", current_subject = "t"))+ assert model["id"] == "Qwen3-Q4"+ assert model["loaded"] is True+++def test_cached_local_catalog_offloads_and_caches(monkeypatch):+ # The filesystem scan must run off the event loop (asyncio.to_thread) and be+ # cached, so a burst of /v1/models calls does not re-scan or block.+ calls = {"scan": 0, "threaded": 0}++ def _fake_collect(_root):+ calls["scan"] += 1+ return [_Info("/data/models/A.gguf", "A")]++ import routes.models as models_mod++ monkeypatch.setattr(models_mod, "collect_local_models", _fake_collect)++ real_to_thread = inf.asyncio.to_thread++ async def _counting_to_thread(fn, *a, **k):+ calls["threaded"] += 1+ return await real_to_thread(fn, *a, **k)++ monkeypatch.setattr(inf.asyncio, "to_thread", _counting_to_thread)+ # Fresh cache for a deterministic count.+ monkeypatch.setattr(inf, "_CATALOG_CACHE", {"at": 0.0, "models": []})++ async def _run():+ first = await inf._cached_local_catalog()+ second = await inf._cached_local_catalog() # within TTL -> cached+ return first, second++ first, second = asyncio.run(_run())+ assert [i.id for i in first] == ["/data/models/A.gguf"]+ assert second is first or [i.id for i in second] == [i.id for i in first]+ assert calls["scan"] == 1 # cached: scanned once for two calls+ assert calls["threaded"] == 1 # offloaded to a worker thread