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 route-aware models through the openai api
Nilay0d41a7203a06
diff --git a/studio/backend/core/inference/media_keepwarm.py b/studio/backend/core/inference/media_keepwarm.pyindex 1188514eb03..5fc9d9eed48 100644--- a/studio/backend/core/inference/media_keepwarm.py+++ b/studio/backend/core/inference/media_keepwarm.py@@ -279,6 +279,10 @@ def _video_engine() -> Any:_ENGINES = {DIFFUSION: _diffusion_engine, VIDEO: _video_engine}+def engine_if_imported(owner: str) -> Any:+ return _ENGINES[owner]()++def _completed_token(progress: dict[str, Any]) -> Optional[tuple[Any, ...]]:"""Identity of the last FINISHED job, for a backend that publishes a terminal record.diff --git a/studio/backend/hub/services/models/catalog_classification.py b/studio/backend/hub/services/models/catalog_classification.pyindex 23fc04722c7..deef60252bd 100644--- a/studio/backend/hub/services/models/catalog_classification.py+++ b/studio/backend/hub/services/models/catalog_classification.py@@ -50,6 +50,26 @@ _ORPHEUS_GGUF_HINT = re.compile()+class _LocalProbeModel:+ def __init__(self, model, path: str):+ self._model = model+ self.path = path++ def __getattr__(self, name):+ return getattr(self._model, name)+++def _local_probe_model(model):+ if getattr(model, "source", None) != "hf_cache" or _hf_cache_snapshot_repo_id(model.path):+ return model+ try:+ from hub.utils.inventory_scan import resolve_hf_cache_realpath+ path = resolve_hf_cache_realpath(Path(model.path))+ except Exception:+ path = None+ return _LocalProbeModel(model, path) if path and path != model.path else model++def _is_h3_bundle_gguf_hint(hint: Optional[str]) -> bool:if not hint:return False@@ -398,10 +418,12 @@ def _local_family_needles(model) -> tuple[str, ...]:def _local_model_can_chat(model) -> Optional[bool]:+ model = _local_probe_model(model)return _local_path_can_chat(model.path, getattr(model, "base_model", None))def _local_model_task(model) -> Optional[str]:+ model = _local_probe_model(model)path = model.pathid_hints = (model.model_id, model.display_name, model.id)if model.model_format == "gguf" or Path(path).suffix.lower() == ".gguf":@@ -444,6 +466,7 @@ def _local_model_task(model) -> Optional[str]:def _local_model_audio_type(model) -> Optional[str]:+ model = _local_probe_model(model)path = model.pathif model.model_format == "gguf" or Path(path).suffix.lower() == ".gguf":return _gguf_path_audio_type(path, (model.model_id, model.display_name, model.id))@@ -479,6 +502,7 @@ def _local_model_classification(model) -> tuple[Optional[str], Optional[str]]:def _local_is_diffusers(model) -> bool:+ model = _local_probe_model(model)try:path = Path(model.path)if path.is_dir() and _is_diffusers_pipeline_dir(path):diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 788b0370618..5a2bccfc577 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -23507,6 +23507,12 @@ def _openai_model_objects() -> list[dict]:_native_ctx = _positive_int_or_none(getattr(llama_backend, "native_context_length", None))if _native_ctx is not None:entry["native_context_length"] = _native_ctx+ # The same gate /v1/audio/speech applies: _audio_type alone also matches whisper+ # (ASR) and audio_vlm (Gemma 3n chat), which that route rejects with a 400.+ if getattr(llama_backend, "_is_audio", False) and (+ getattr(llama_backend, "_audio_type", None) in _GGUF_TTS_AUDIO_TYPES+ ):+ entry["task"] = _TTS_MODEL_TASKmodels.append(entry)# Check Unsloth backend@@ -23531,6 +23537,12 @@ def _openai_model_objects() -> list[dict]:breakif _ctx is not None:entry["context_length"] = _ctx+ if (+ not model_info.get("is_mlx")+ and model_info.get("is_audio")+ and (model_info.get("audio_type") in _TRANSFORMERS_TTS_AUDIO_TYPES)+ ):+ entry["task"] = _TTS_MODEL_TASKmodels.append(entry)return models@@ -23601,6 +23613,264 @@ def _catalog_lock() -> asyncio.Lock:return lock+def _classified_catalog(models: list) -> list:+ from hub.services.models.catalog_classification import _local_model_classification++ classified = []+ for model in models:+ if getattr(model, "task", None) is None and hasattr(model, "model_copy"):+ try:+ task, audio_type = _local_model_classification(model)+ model = model.model_copy(update = {"task": task, "audio_type": audio_type})+ except Exception as exc: # noqa: BLE001+ logger.debug(+ "model task classification failed for %s: %s", getattr(model, "id", "?"), exc+ )+ classified.append(model)+ return classified+++_MEDIA_MODEL_TASKS = ("text-to-image", "text-to-video")+_STT_MODEL_TASK = "automatic-speech-recognition"+_TTS_MODEL_TASK = "text-to-speech"+++def _media_owner(task: str) -> str:+ from core.inference.gpu_arbiter import DIFFUSION, VIDEO+ return DIFFUSION if task == "text-to-image" else VIDEO+++def _resident_media_status(task: str) -> Optional[dict]:+ from core.inference.media_keepwarm import engine_if_imported+ try:+ engine = engine_if_imported(_media_owner(task))+ status = engine.status() if engine is not None else None+ except Exception as exc: # noqa: BLE001+ logger.debug("%s status unavailable for /v1/models: %s", task, exc)+ return None+ return status if status and status.get("loaded") else None+++_MEDIA_PICK_CACHE: dict = {"at": None, "picks": {}}+_MEDIA_PICK_CACHE_LOCK = threading.Lock()+++def _validated_media_picks(catalog_at: float) -> dict:+ """The (id, pick) rows per task, rebuilt only when the shared catalog scan is replaced.++ Each media index keeps its own short TTL and its own ``collect_local_models`` walk, so+ resolving them per request made an otherwise-cached /v1/models pay two extra full+ scans. The Settings usage examples poll this endpoint, so that cost repeats.+ """+ if _MEDIA_PICK_CACHE["at"] == catalog_at:+ return _MEDIA_PICK_CACHE["picks"]+ with _MEDIA_PICK_CACHE_LOCK:+ if _MEDIA_PICK_CACHE["at"] == catalog_at:+ return _MEDIA_PICK_CACHE["picks"]+ from core.inference.media_locality import is_edit_only, missing_download_bytes+ from core.inference.media_model_index import (+ available_media_model_ids,+ resolve_local_media_model,+ )++ picks: dict = {}+ for task in _MEDIA_MODEL_TASKS:+ rows = []+ for model_id in available_media_model_ids(task):+ pick = resolve_local_media_model(model_id, task = task)+ if pick is None:+ continue+ # The local catalog tags an instruction-editing checkpoint text-to-image, but it+ # ships no txt2img workflow: the switch refuses it with a 400 and a resident one+ # is refused by /v1/images/generations too.+ if task == "text-to-image" and is_edit_only(pick):+ continue+ try:+ local = missing_download_bytes(_media_owner(task), pick) == 0+ except Exception as exc: # noqa: BLE001+ logger.debug("media locality unavailable for %s: %s", model_id, exc)+ local = False+ rows.append((model_id, pick, local))+ picks[task] = rows+ _MEDIA_PICK_CACHE.update(at = catalog_at, picks = picks)+ return picks+++def _media_model_objects(catalog: list, created: int, catalog_at: float) -> list[dict]:+ """Downloaded image/video models, as the generation resolver actually sees them.++ Built from the media index rather than the raw catalog, because that index is what+ /v1/images/generations and /v1/videos resolve a name against: it drops partial pulls,+ directories no loader can open, and builds a sibling quant cannot be told apart from.+ Anything it rejects would be advertised here and then answered with model_not_found.++ Residency goes through ``resident_is_pick`` for the same reason. A standalone GGUF+ loads with its parent directory as the model path and an HF cache repo with its+ snapshot directory, so comparing the public id or the catalog's own path reports the+ resident model as unloaded. Residency is read per request; only the scan is cached.+ """+ from core.inference.media_model_index import (+ partition_matches,+ resident_is_gguf,+ satisfied_by,+ )+ from hub.utils.gguf import extract_quant_token++ display_by_id: dict[str, str] = {}+ for info in catalog:+ cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))+ display = getattr(info, "display_name", None)+ if cid and display:+ display_by_id.setdefault(cid, display)++ picks_by_task = _validated_media_picks(catalog_at)+ objects: list[dict] = []+ for task in _MEDIA_MODEL_TASKS:+ status = _resident_media_status(task)+ for model_id, pick, local in picks_by_task.get(task, ()):+ loaded = bool(status) and satisfied_by(status, model_id, pick)+ if not loaded and not local:+ continue+ obj = {+ "id": model_id,+ "object": "model",+ "created": created,+ "owned_by": _OWNED_BY,+ "task": task,+ "loaded": loaded,+ }+ quant = (status.get("gguf_variant") if loaded else None) or (+ extract_quant_token(pick.gguf_filename) if pick.gguf_filename else None+ )+ if quant:+ obj["quant"] = quant+ display = display_by_id.get(model_id)+ if display:+ obj["display_name"] = display+ objects.append(obj)+ resident_id = str((status or {}).get("repo_id") or "").strip()+ resident_workflows = (status or {}).get("workflows") or ()+ if (+ status+ and resident_id+ and not resident_is_gguf(status)+ and partition_matches(status)+ and (+ task != "text-to-image" or not resident_workflows or "txt2img" in resident_workflows+ )+ and public_model_id(resident_id) == resident_id+ and not any(obj["id"].lower() == resident_id.lower() for obj in objects)+ ):+ objects.append(+ {+ "id": resident_id,+ "object": "model",+ "created": created,+ "owned_by": _OWNED_BY,+ "task": task,+ "loaded": True,+ }+ )+ return objects+++_CUSTOM_STT_CACHE: dict = {"at": None, "ids": ()}+_CUSTOM_STT_CACHE_LOCK = threading.Lock()+++def _downloaded_custom_stt_ids(catalog_at: Optional[float]) -> tuple[str, ...]:+ if catalog_at is not None and _CUSTOM_STT_CACHE["at"] == catalog_at:+ return _CUSTOM_STT_CACHE["ids"]+ with _CUSTOM_STT_CACHE_LOCK:+ if catalog_at is not None and _CUSTOM_STT_CACHE["at"] == catalog_at:+ return _CUSTOM_STT_CACHE["ids"]+ from core.inference import stt_sidecar+ from hub.services.models.cache_inventory import _scan_cached_models++ try:+ ids = tuple(+ sorted(+ row["repo_id"]+ for row in _scan_cached_models()+ if row.get("task") == _STT_MODEL_TASK+ and not row.get("partial")+ and isinstance(row.get("repo_id"), str)+ and stt_sidecar.is_model_downloaded(row["repo_id"])+ )+ )+ except Exception as exc: # noqa: BLE001+ logger.debug("custom stt cache scan unavailable for /v1/models: %s", exc)+ ids = ()+ _CUSTOM_STT_CACHE.update(at = catalog_at, ids = ids)+ return ids+++def _stt_model_objects(created: int, catalog_at: Optional[float] = None) -> list[dict]:+ """Downloaded speech-to-text models this endpoint's own route can actually serve.++ /v1/audio/transcriptions resolves an id to an engine by itself: only the mtmd ids are+ forced, and everything else lands on Transformers. So a curated Whisper id cached only+ for whisper.cpp is not servable here (the route loads the absent Transformers snapshot+ and 409s), and neither engine can serve anything while its runtime is missing (501).+ Both engines are therefore gated on their own availability, and residency is read only+ from the engines this route can select.+ """+ try:+ from core.inference import stt_mtmd_sidecar, stt_sidecar++ whisper_ready = stt_sidecar.is_available()+ mtmd_ready = stt_mtmd_sidecar.is_available()+ loaded = set()+ if whisper_ready:+ whisper_loaded = stt_sidecar.get_stt_sidecar().loaded_model+ loaded.add(stt_sidecar.STT_MODELS.get(whisper_loaded, whisper_loaded))+ if mtmd_ready:+ loaded.add(stt_mtmd_sidecar.get_mtmd_stt_sidecar().loaded_model)+ loaded -= {None}++ ids: list[str] = []+ if whisper_ready:+ ids.extend(+ repo_id+ for model_id, repo_id in stt_sidecar.STT_MODELS.items()+ if stt_sidecar.is_model_downloaded(model_id)+ )+ ids.extend(+ model_id+ for model_id in _downloaded_custom_stt_ids(catalog_at)+ if model_id not in ids+ )+ if mtmd_ready:+ ids.extend(+ model_id+ for model_id in stt_mtmd_sidecar.MTMD_STT_MODELS+ if stt_mtmd_sidecar.is_model_downloaded(model_id)+ )+ # A custom Whisper repo the route can still reload by name while it is resident.+ ids.extend(sorted(model_id for model_id in loaded if model_id not in ids))+ except Exception as exc: # noqa: BLE001+ logger.debug("stt models unavailable for /v1/models: %s", exc)+ return []+ objects = []+ for model_id in ids:+ obj = {+ "id": model_id,+ "object": "model",+ "created": created,+ "owned_by": _OWNED_BY,+ "task": _STT_MODEL_TASK,+ "loaded": model_id in loaded,+ }+ spec = stt_mtmd_sidecar.MTMD_STT_MODELS.get(model_id)+ if spec is not None:+ from hub.utils.gguf import extract_quant_token+ quant = extract_quant_token(spec.model_file)+ if quant:+ obj["quant"] = quant+ objects.append(obj)+ return objects++async def _cached_local_catalog() -> list:"""Locally available models (models dir + HF caches + LM Studio + scanfolders), cached for a few seconds. Returns a list of LocalModelInfo.@@ -23622,7 +23892,7 @@ async def _cached_local_catalog() -> list:try:from routes.models import collect_local_models_CATALOG_CACHE["models"] = await asyncio.to_thread(- collect_local_models, Path("./models").resolve()+ lambda: _classified_catalog(collect_local_models(Path("./models").resolve())))except Exception as exc:logger.debug("model catalog scan failed: %s", exc)@@ -23638,9 +23908,17 @@ def _servable_catalog_rows(catalog) -> list[tuple[object, bool, tuple[str, ...],from disk. Module scope, and always called through ``asyncio.to_thread``: the filechecks stat many files and the residency check reads the inference singleton."""from core.inference.local_model_resolver import local_load_dir, local_servable_model+ from hub.services.models.catalog_classification import _UNSUPPORTED_DIFFUSION_TASKrows = []for info in catalog:+ if getattr(info, "task", None) in (+ *_MEDIA_MODEL_TASKS,+ _STT_MODEL_TASK,+ _TTS_MODEL_TASK,+ _UNSUPPORTED_DIFFUSION_TASK,+ ):+ continueservable = local_servable_model(info)if servable is None:continue@@ -23668,6 +23946,8 @@ async def _openai_catalog_objects() -> list[dict]:# build waits on detection. Inline, an early GET /v1/models held the loop for the import.for entry in await asyncio.to_thread(_openai_model_objects):by_id[entry["id"]] = {**entry, "loaded": True}+ orchestrator = _peek_inference_backend()+ resident_id = _orchestrator_public_model_id(orchestrator) if orchestrator else None# Downloaded but unloaded: GGUF via llama.cpp, other weights via the orchestrator.catalog = await _cached_local_catalog()@@ -23676,7 +23956,6 @@ async def _openai_catalog_objects() -> list[dict]:if not cid or cid in by_id:continueif loaded and not is_gguf:- resident_id = _orchestrator_public_model_id(get_inference_backend())if resident_id in by_id:continueobj = {@@ -23699,6 +23978,15 @@ async def _openai_catalog_objects() -> list[dict]:obj["display_name"] = displayby_id[cid] = obj+ media = await asyncio.to_thread(+ lambda: (+ _media_model_objects(catalog, _created, _CATALOG_CACHE["at"])+ + _stt_model_objects(_created, _CATALOG_CACHE["at"])+ )+ )+ for obj in media:+ by_id.setdefault(obj["id"], obj)+return list(by_id.values())diff --git a/studio/backend/tests/test_local_model_format.py b/studio/backend/tests/test_local_model_format.pyindex 82388b57464..3e70a817257 100644--- a/studio/backend/tests/test_local_model_format.py+++ b/studio/backend/tests/test_local_model_format.py@@ -376,6 +376,53 @@ def test_local_classification_never_opens_an_online_only_gguf(tmp_path, monkeypaassert opened == []+def test_local_classification_probes_the_hf_cache_snapshot(tmp_path):+ from hub.services.models import catalog_classification as classification++ repo = tmp_path / "models--unsloth--csm-1b"+ snapshot = repo / "snapshots" / "abc"+ snapshot.mkdir(parents = True)+ (snapshot / "tokenizer_config.json").write_text(+ json.dumps(+ {+ "added_tokens_decoder": {+ "0": {"content": "<|AUDIO|>"},+ "1": {"content": "<|audio_eos|>"},+ }+ }+ ),+ encoding = "utf-8",+ )+ model = LocalModelInfo(+ id = "unsloth/csm-1b",+ display_name = "csm-1b",+ path = str(repo),+ source = "hf_cache",+ model_id = "unsloth/csm-1b",+ )++ assert classification._local_model_classification(model) == ("text-to-speech", "csm")+++def test_local_task_probes_the_hf_cache_pipeline_snapshot(tmp_path):+ repo = tmp_path / "models--hf-internal-testing--tiny-sdxl-pipe"+ snapshot = repo / "snapshots" / "abc"+ snapshot.mkdir(parents = True)+ (snapshot / "model_index.json").write_text(+ json.dumps({"_class_name": "StableDiffusionXLPipeline"}),+ encoding = "utf-8",+ )+ model = LocalModelInfo(+ id = "hf-internal-testing/tiny-sdxl-pipe",+ display_name = "tiny-sdxl-pipe",+ path = str(repo),+ source = "hf_cache",+ model_id = "hf-internal-testing/tiny-sdxl-pipe",+ )++ assert models_route._local_model_task(model) == "text-to-image"++def test_an_unhydrated_denoiser_keeps_the_picker_that_would_hydrate_it(tmp_path, monkeypatch):"""Images and Video filter On Device rows on an exact task, so an unclassified denoiseris not reachable from the one page whose pick would pull it down, and lists in Chatdiff --git a/studio/backend/tests/test_openai_models_media.py b/studio/backend/tests/test_openai_models_media.pynew file mode 100644index 00000000000..d5073c52486--- /dev/null+++ b/studio/backend/tests/test_openai_models_media.py@@ -0,0 +1,808 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import asyncio+import json+import sys+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from types import SimpleNamespace+from typing import Optional++from fastapi import FastAPI+from fastapi.testclient import TestClient+from pydantic import BaseModel++_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+from auth.authentication import get_current_subject # noqa: E402+from core.inference import local_model_resolver as resolver # noqa: E402+from core.inference import media_model_index as mmi # noqa: E402+from core.inference.media_model_index import MediaModelPick # noqa: E402+from utils.api_errors import install_api_error_handlers # noqa: E402+++class _Info:+ def __init__(+ self,+ id,+ display_name,+ model_id = None,+ path = None,+ task = None,+ is_gguf = True,+ ):+ self.id = id+ self.display_name = display_name+ self.model_id = model_id+ self.path = path or id+ self.task = task+ self.is_gguf = is_gguf+++class _FakeLlama:+ is_loaded = False+ model_identifier = None+ context_length = None+ max_context_length = None+ native_context_length = None+ _is_audio = False+ _audio_type = None+++class _FakeUnsloth:+ active_model_name = None+ models: dict = {}+ context_length = None+ max_seq_length = None+++def _media_index(monkeypatch, picks_by_task):+ """Stand in for the media index the generation routes resolve against."""+ from core.inference import media_locality++ inf._MEDIA_PICK_CACHE.update(at = None, picks = {})+ monkeypatch.setattr(media_locality, "missing_download_bytes", lambda owner, pick: 0)+ monkeypatch.setattr(+ mmi,+ "available_media_model_ids",+ lambda task: sorted(p.model_id for p in picks_by_task.get(task, [])),+ )+ monkeypatch.setattr(+ mmi,+ "resolve_local_media_model",+ lambda name, *, task: next(+ (p for p in picks_by_task.get(task, []) if p.model_id == name), None+ ),+ )+++def _catalog(+ monkeypatch,+ infos,+ resident = None,+ picks = None,+):+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama())+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _FakeUnsloth())++ async def _fake_catalog():+ return infos++ monkeypatch.setattr(inf, "_cached_local_catalog", _fake_catalog)+ monkeypatch.setattr(+ resolver,+ "local_servable_model",+ lambda info: (info.is_gguf, ("Q8_0",) if info.is_gguf else ()),+ )+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda *_args, **_kwargs: False)+ monkeypatch.setattr(inf, "_resident_media_status", lambda task: (resident or {}).get(task))+ monkeypatch.setattr(inf, "_stt_model_objects", lambda created, catalog_at = None: [])+ _media_index(monkeypatch, picks if picks is not None else _PICKS)+++_INFOS = [+ _Info("/data/models/Qwen3-Q4.gguf", "Qwen3-Q4", task = "text-generation"),+ _Info(+ "models--unsloth--Z-Image-Turbo-GGUF",+ "Z-Image-Turbo",+ model_id = "unsloth/Z-Image-Turbo-GGUF",+ path = "/hf/models--unsloth--Z-Image-Turbo-GGUF/snapshots/abc",+ task = "text-to-image",+ ),+ _Info(+ "models--Lightricks--LTX-2",+ "LTX-2",+ model_id = "Lightricks/LTX-2",+ path = "/hf/models--Lightricks--LTX-2/snapshots/def",+ task = "text-to-video",+ is_gguf = False,+ ),+ _Info("/data/models/Unsupported.gguf", "Unsupported", task = "image-diffusion-unsupported"),+]+++_PICKS = {+ "text-to-image": [+ MediaModelPick(+ "unsloth/Z-Image-Turbo-GGUF",+ "/hf/models--unsloth--Z-Image-Turbo-GGUF/snapshots/abc",+ "z-image-turbo-Q8_0.gguf",+ "gguf",+ )+ ],+ "text-to-video": [+ MediaModelPick("Lightricks/LTX-2", "/hf/models--Lightricks--LTX-2/snapshots/def")+ ],+}+++def test_media_models_list_with_task_and_residency(monkeypatch):+ resident = {+ "text-to-image": {+ "loaded": True,+ "repo_id": "unsloth/z-image-turbo-gguf",+ "gguf_variant": "Q8_0",+ "model_kind": "gguf",+ }+ }+ _catalog(monkeypatch, _INFOS, resident)++ data = asyncio.run(inf._openai_catalog_objects())+ ids = {m["id"]: m for m in data}++ image = ids["unsloth/Z-Image-Turbo-GGUF"]+ assert image["task"] == "text-to-image" and image["loaded"] is True+ assert image["quant"] == "Q8_0" and image["display_name"] == "Z-Image-Turbo"+ assert image["object"] == "model" and image["owned_by"] == inf._OWNED_BY+ video = ids["Lightricks/LTX-2"]+ assert video["task"] == "text-to-video" and video["loaded"] is False+ assert "quant" not in video+ assert "Unsupported" not in ids+ assert "task" not in ids["Qwen3-Q4"] and ids["Qwen3-Q4"]["quant"] == "Q8_0"+ assert [m["id"] for m in data].count("unsloth/Z-Image-Turbo-GGUF") == 1+ blob = json.dumps(data)+ assert "/hf/" not in blob and "/data/" not in blob+++def test_media_models_report_the_on_disk_quant_when_not_loaded(monkeypatch):+ _catalog(monkeypatch, _INFOS)+ ids = {m["id"]: m for m in asyncio.run(inf._openai_catalog_objects())}+ assert ids["unsloth/Z-Image-Turbo-GGUF"]["loaded"] is False+ assert ids["unsloth/Z-Image-Turbo-GGUF"]["quant"] == "Q8_0"+++def test_resident_media_model_matches_by_path(monkeypatch):+ resident = {+ "text-to-video": {"loaded": True, "repo_id": "/hf/models--Lightricks--LTX-2/snapshots/def"}+ }+ _catalog(monkeypatch, _INFOS, resident)+ ids = {m["id"]: m for m in asyncio.run(inf._openai_catalog_objects())}+ assert ids["Lightricks/LTX-2"]["loaded"] is True+ assert sum(1 for m in ids.values() if m.get("task") == "text-to-video") == 1+++def test_a_resident_sibling_quant_is_not_reported_as_the_indexed_build(monkeypatch):+ """Same repo, different weights: the indexed build is Q8_0 and Q4_K_M is resident."""+ resident = {+ "text-to-image": {+ "loaded": True,+ "repo_id": "unsloth/z-image-turbo-gguf",+ "gguf_variant": "Q4_K_M",+ "model_kind": "gguf",+ }+ }+ _catalog(monkeypatch, _INFOS, resident)+ ids = {m["id"]: m for m in asyncio.run(inf._openai_catalog_objects())}+ assert ids["unsloth/Z-Image-Turbo-GGUF"]["loaded"] is False+ assert ids["unsloth/Z-Image-Turbo-GGUF"]["quant"] == "Q8_0"+++def test_ambiguous_same_token_media_builds_are_not_both_loaded(monkeypatch):+ picks = {+ "text-to-image": [+ MediaModelPick(+ "image-a",+ "/srv/models",+ "image-a-IQ4_XS-3.53bpw.gguf",+ "gguf",+ ambiguous = True,+ ),+ MediaModelPick(+ "image-b",+ "/srv/models",+ "image-b-IQ4_XS-3.97bpw.gguf",+ "gguf",+ ambiguous = True,+ ),+ ]+ }+ resident = {+ "text-to-image": {+ "loaded": True,+ "repo_id": "/srv/models",+ "gguf_variant": "IQ4_XS",+ "model_kind": "gguf",+ }+ }+ _catalog(monkeypatch, [], resident, picks = picks)++ models = asyncio.run(inf._openai_catalog_objects())+ assert {model["id"]: model["loaded"] for model in models} == {+ "image-a": False,+ "image-b": False,+ }+++def test_a_standalone_gguf_resident_is_matched_by_its_load_directory(monkeypatch):+ """A standalone GGUF loads with its PARENT directory as the model path.++ Comparing the public id or the catalog's own file path reports the resident model as+ unloaded and then adds a second entry named after the directory.+ """+ pick = MediaModelPick("z-image", "/srv/models", "z-image-Q4_K_M.gguf", "gguf")+ resident = {+ "text-to-image": {+ "loaded": True,+ "repo_id": "/srv/models",+ "gguf_variant": "Q4_K_M",+ "dtype": "gguf",+ "model_kind": "gguf",+ }+ }+ _catalog(monkeypatch, [], resident, picks = {"text-to-image": [pick]})+ data = asyncio.run(inf._openai_catalog_objects())+ assert [m["id"] for m in data] == ["z-image"]+ assert data[0]["loaded"] is True and data[0]["quant"] == "Q4_K_M"+ assert "/srv/" not in json.dumps(data)+++def test_edit_only_checkpoints_are_not_offered_for_text_to_image(monkeypatch):+ """The catalog tags an instruction-editing checkpoint text-to-image, but it ships no+ txt2img workflow: the switch refuses it with a 400 and a resident one is refused by+ /v1/images/generations too."""+ from core.inference import media_locality++ edit = MediaModelPick("org/qwen-image-edit", "/hf/edit")+ plain = MediaModelPick("org/plain-image", "/hf/plain")+ monkeypatch.setattr(+ media_locality, "is_edit_only", lambda pick: pick.model_id == "org/qwen-image-edit"+ )+ _catalog(monkeypatch, [], picks = {"text-to-image": [edit, plain]})+ ids = [m["id"] for m in asyncio.run(inf._openai_catalog_objects())]+ assert ids == ["org/plain-image"]+++def test_the_media_scan_is_reused_across_requests_in_one_catalog_window(monkeypatch):+ """Each media index runs its own collect_local_models walk on a short TTL, so+ resolving them per request made a cached /v1/models pay two extra full scans."""+ calls = []++ def _ids(task):+ calls.append(task)+ return []++ monkeypatch.setattr(mmi, "available_media_model_ids", _ids)+ monkeypatch.setattr(mmi, "resolve_local_media_model", lambda name, *, task: None)+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama())+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _FakeUnsloth())+ monkeypatch.setattr(inf, "_resident_media_status", lambda task: None)+ monkeypatch.setattr(inf, "_stt_model_objects", lambda created, catalog_at = None: [])+ inf._MEDIA_PICK_CACHE.update(at = None, picks = {})++ async def _cat():+ return []++ monkeypatch.setattr(inf, "_cached_local_catalog", _cat)+ monkeypatch.setattr(inf, "_CATALOG_CACHE", {"at": 1234.0, "models": []})++ for _ in range(3):+ asyncio.run(inf._openai_catalog_objects())+ assert calls == list(inf._MEDIA_MODEL_TASKS), calls++ # A replaced catalog scan rebuilds it.+ inf._CATALOG_CACHE["at"] = 5678.0+ asyncio.run(inf._openai_catalog_objects())+ assert calls == list(inf._MEDIA_MODEL_TASKS) * 2, calls+++def test_concurrent_media_requests_share_one_catalog_rebuild(monkeypatch):+ calls = []+ ready = threading.Barrier(2)++ def _ids(task):+ calls.append(task)+ time.sleep(0.02)+ return []++ monkeypatch.setattr(mmi, "available_media_model_ids", _ids)+ monkeypatch.setattr(mmi, "resolve_local_media_model", lambda name, *, task: None)+ inf._MEDIA_PICK_CACHE.update(at = None, picks = {})++ def _build():+ ready.wait()+ return inf._validated_media_picks(1234.0)++ with ThreadPoolExecutor(max_workers = 2) as pool:+ results = [future.result() for future in (pool.submit(_build), pool.submit(_build))]++ assert results == [{task: [] for task in inf._MEDIA_MODEL_TASKS}] * 2+ assert calls == list(inf._MEDIA_MODEL_TASKS)+++def test_only_ids_the_media_resolver_accepts_are_listed(monkeypatch):+ """The index already drops partial pulls, unopenable paths and ambiguous builds.++ Listing anything it rejects advertises an id the generation route answers with+ model_not_found, so an empty index must advertise nothing -- even while a model the+ index does not know is resident.+ """+ resident = {+ "text-to-image": {+ "loaded": True,+ "repo_id": "/srv/models/half-pulled",+ "gguf_variant": "Q4_K_M",+ }+ }+ _catalog(monkeypatch, _INFOS, resident, picks = {})+ data = asyncio.run(inf._openai_catalog_objects())+ assert [m for m in data if m.get("task") in ("text-to-image", "text-to-video")] == []+ assert "half-pulled" not in json.dumps(data)+++def test_media_model_with_missing_companions_is_not_advertised(monkeypatch):+ from core.inference import media_locality++ image = _PICKS["text-to-image"][0]+ _catalog(monkeypatch, _INFOS, picks = {"text-to-image": [image]})+ monkeypatch.setattr(+ media_locality,+ "missing_download_bytes",+ lambda owner, pick: 9_000 if pick is image else 0,+ )+ inf._MEDIA_PICK_CACHE.update(at = None, picks = {})++ data = asyncio.run(inf._openai_catalog_objects())+ assert [model for model in data if model.get("task") == "text-to-image"] == []+++def test_loaded_non_gguf_media_stays_listed_when_discovery_misses_it(monkeypatch):+ from core.inference.gpu_arbiter import DIFFUSION+ from core.inference.media_auto_switch import resident_answers_media_request++ resident = {+ "text-to-image": {+ "loaded": True,+ "repo_id": "black-forest-labs/FLUX.1-dev",+ "model_kind": "pipeline",+ }+ }+ _catalog(monkeypatch, [], resident, picks = {})+ (model,) = asyncio.run(inf._openai_catalog_objects())+ assert model["id"] == "black-forest-labs/FLUX.1-dev"+ assert model["task"] == "text-to-image" and model["loaded"] is True+ assert resident_answers_media_request(resident["text-to-image"], model["id"], owner = DIFFUSION)+++def test_edit_only_resident_missing_from_discovery_is_not_advertised(monkeypatch):+ resident = {+ "text-to-image": {+ "loaded": True,+ "repo_id": "org/qwen-image-edit",+ "model_kind": "pipeline",+ "workflows": ["edit"],+ }+ }+ _catalog(monkeypatch, [], resident, picks = {})+ assert asyncio.run(inf._openai_catalog_objects()) == []+++def _stt(+ monkeypatch,+ *,+ whisper = True,+ mtmd = True,+ downloaded = ("small",),+ mtmd_downloaded = (),+ whisper_loaded = None,+ mtmd_loaded = None,+):+ from core.inference import stt_mtmd_sidecar, stt_sidecar++ monkeypatch.setattr(stt_sidecar, "is_available", lambda: whisper)+ monkeypatch.setattr(stt_mtmd_sidecar, "is_available", lambda: mtmd)+ monkeypatch.setattr(stt_sidecar, "is_model_downloaded", lambda m: m in downloaded)+ monkeypatch.setattr(stt_mtmd_sidecar, "is_model_downloaded", lambda m: m in mtmd_downloaded)+ monkeypatch.setattr(+ stt_sidecar, "get_stt_sidecar", lambda: SimpleNamespace(loaded_model = whisper_loaded)+ )+ monkeypatch.setattr(+ stt_mtmd_sidecar, "get_mtmd_stt_sidecar", lambda: SimpleNamespace(loaded_model = mtmd_loaded)+ )+ monkeypatch.setattr(inf, "_downloaded_custom_stt_ids", lambda catalog_at: ())+++def test_stt_models_list_downloaded_and_loaded(monkeypatch):+ _stt(+ monkeypatch,+ downloaded = ("small",),+ mtmd_downloaded = ("qwen3-asr-0.6b",),+ whisper_loaded = "org/whisper-custom",+ )+ objects = inf._stt_model_objects(7)+ assert [(o["id"], o["loaded"]) for o in objects] == [+ ("unsloth/whisper-small", False),+ ("qwen3-asr-0.6b", False),+ ("org/whisper-custom", True),+ ]+ assert all(o["task"] == "automatic-speech-recognition" and o["created"] == 7 for o in objects)+ assert {o["id"]: o.get("quant") for o in objects} == {+ "unsloth/whisper-small": None,+ "qwen3-asr-0.6b": "Q8_0",+ "org/whisper-custom": None,+ }+++def test_curated_stt_alias_reports_canonical_loaded_id(monkeypatch):+ _stt(monkeypatch, downloaded = ("small",), whisper_loaded = "small")+ assert [(o["id"], o["loaded"]) for o in inf._stt_model_objects(7)] == [+ ("unsloth/whisper-small", True)+ ]+++def test_downloaded_custom_whisper_model_remains_listed_after_unload(monkeypatch):+ _stt(monkeypatch, downloaded = ())+ monkeypatch.setattr(+ inf, "_downloaded_custom_stt_ids", lambda catalog_at: ("org/whisper-custom",)+ )+ assert [(o["id"], o["loaded"]) for o in inf._stt_model_objects(7, 12.0)] == [+ ("org/whisper-custom", False)+ ]+++def test_custom_stt_scan_keeps_only_complete_servable_whisper_repos(monkeypatch):+ from core.inference import stt_sidecar+ from hub.services.models import cache_inventory++ calls = []+ rows = [+ {"repo_id": "org/whisper-ready", "task": "automatic-speech-recognition"},+ {+ "repo_id": "org/whisper-partial",+ "task": "automatic-speech-recognition",+ "partial": True,+ },+ {"repo_id": "org/qwen-asr", "task": "automatic-speech-recognition"},+ {"repo_id": "org/chat", "task": "text-generation"},+ ]+ monkeypatch.setattr(+ cache_inventory,+ "_scan_cached_models",+ lambda: calls.append(True) or rows,+ )+ monkeypatch.setattr(+ stt_sidecar,+ "is_model_downloaded",+ lambda model_id: model_id == "org/whisper-ready",+ )+ inf._CUSTOM_STT_CACHE.update(at = None, ids = ())++ assert inf._downloaded_custom_stt_ids(22.0) == ("org/whisper-ready",)+ assert inf._downloaded_custom_stt_ids(22.0) == ("org/whisper-ready",)+ assert len(calls) == 1+++def test_concurrent_custom_stt_requests_share_one_inventory_scan(monkeypatch):+ from hub.services.models import cache_inventory++ calls = []+ ready = threading.Barrier(2)++ def _scan():+ calls.append(True)+ time.sleep(0.02)+ return []++ monkeypatch.setattr(cache_inventory, "_scan_cached_models", _scan)+ inf._CUSTOM_STT_CACHE.update(at = None, ids = ())++ def _build():+ ready.wait()+ return inf._downloaded_custom_stt_ids(1234.0)++ with ThreadPoolExecutor(max_workers = 2) as pool:+ results = [future.result() for future in (pool.submit(_build), pool.submit(_build))]++ assert results == [(), ()]+ assert calls == [True]+++def test_a_whisper_id_cached_only_for_whisper_cpp_is_not_advertised(monkeypatch):+ """/v1/audio/transcriptions never selects the GGML engine on its own.++ _stt_engine_for_model forces only the mtmd ids, so a curated Whisper id resolves to+ Transformers; advertising one that exists only in the whisper.cpp cache sends the+ caller at an absent Transformers snapshot, which answers 409.+ """+ from core.inference import stt_ggml_sidecar++ _stt(monkeypatch, downloaded = ())+ # Resident on the GGML sidecar, and cached there, yet still not OpenAI-servable.+ monkeypatch.setattr(+ stt_ggml_sidecar, "_cached_model_path", lambda m: "/x" if m == "large-v3-turbo" else None+ )+ monkeypatch.setattr(+ stt_ggml_sidecar,+ "get_ggml_stt_sidecar",+ lambda: SimpleNamespace(loaded_model = "large-v3-turbo"),+ )+ assert inf._stt_model_objects(3) == []+++def test_whisper_rows_need_the_transformers_runtime(monkeypatch):+ """WhisperSttSidecar.load() calls ensure_stt_available(), which the route maps to 501."""+ _stt(monkeypatch, whisper = False, downloaded = ("small", "tiny"))+ assert inf._stt_model_objects(3) == []+ _stt(monkeypatch, whisper = True, downloaded = ("small", "tiny"))+ assert [o["id"] for o in inf._stt_model_objects(3)] == [+ "unsloth/whisper-tiny",+ "unsloth/whisper-small",+ ]+++def test_mtmd_models_are_hidden_when_their_runtime_is_missing(monkeypatch):+ """Qwen3-ASR runs on no other engine, so without llama-server every+ /v1/audio/transcriptions call for one returns 501."""+ _stt(+ monkeypatch,+ mtmd = False,+ downloaded = ("small",),+ mtmd_downloaded = ("qwen3-asr-0.6b", "qwen3-asr-1.7b"),+ )+ assert [o["id"] for o in inf._stt_model_objects(3)] == ["unsloth/whisper-small"]++ _stt(+ monkeypatch,+ mtmd = True,+ downloaded = ("small",),+ mtmd_downloaded = ("qwen3-asr-0.6b", "qwen3-asr-1.7b"),+ )+ assert [o["id"] for o in inf._stt_model_objects(3)] == [+ "unsloth/whisper-small",+ "qwen3-asr-0.6b",+ "qwen3-asr-1.7b",+ ]+++def test_stt_probe_failure_hides_nothing_else(monkeypatch):+ from core.inference import stt_sidecar++ def _boom():+ raise RuntimeError("no sidecar")++ monkeypatch.setattr(stt_sidecar, "get_stt_sidecar", _boom)+ assert inf._stt_model_objects(1) == []+++def test_stt_models_join_the_catalog(monkeypatch):+ _catalog(+ monkeypatch,+ [_Info("/data/models/small.gguf", "small", task = "text-generation")],+ )+ monkeypatch.setattr(+ inf,+ "_stt_model_objects",+ lambda created, catalog_at = None: [+ {+ "id": "unsloth/whisper-small",+ "object": "model",+ "created": created,+ "owned_by": inf._OWNED_BY,+ "task": "automatic-speech-recognition",+ "loaded": False,+ }+ ],+ )+ ids = {m["id"]: m for m in asyncio.run(inf._openai_catalog_objects())}+ assert ids["unsloth/whisper-small"]["task"] == "automatic-speech-recognition"+ assert "task" not in ids["small"]+++def test_stt_gguf_repository_is_not_advertised_as_chat(monkeypatch):+ repo = _Info(+ "models--unslothai--Qwen3-ASR-0.6B-GGUF",+ "Qwen3-ASR-0.6B-GGUF",+ model_id = "unslothai/Qwen3-ASR-0.6B-GGUF",+ task = "automatic-speech-recognition",+ )+ _catalog(monkeypatch, [repo], picks = {})+ monkeypatch.setattr(+ inf,+ "_stt_model_objects",+ lambda created, catalog_at = None: [+ {+ "id": "qwen3-asr-0.6b",+ "object": "model",+ "created": created,+ "owned_by": inf._OWNED_BY,+ "task": "automatic-speech-recognition",+ "loaded": False,+ }+ ],+ )++ ids = {model["id"]: model for model in asyncio.run(inf._openai_catalog_objects())}+ assert "unslothai/Qwen3-ASR-0.6B-GGUF" not in ids+ assert ids["qwen3-asr-0.6b"]["task"] == "automatic-speech-recognition"+++def test_loaded_tts_model_is_tagged(monkeypatch):+ class _Tts(_FakeLlama):+ is_loaded = True+ model_identifier = "/srv/models/orpheus-3b-Q4.gguf"+ _is_audio = True+ _audio_type = "snac"++ class _Chat(_FakeLlama):+ is_loaded = True+ model_identifier = "/srv/models/qwen3-Q4.gguf"++ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _Tts())+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _FakeUnsloth())+ (entry,) = inf._openai_model_objects()+ assert entry["id"] == "orpheus-3b-Q4" and entry["task"] == "text-to-speech"++ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _Chat())+ (entry,) = inf._openai_model_objects()+ assert entry["id"] == "qwen3-Q4" and "task" not in entry+++def test_audio_input_models_are_not_tagged_text_to_speech(monkeypatch):+ """Only what /v1/audio/speech can actually serve is tagged text-to-speech.++ whisper (ASR) and audio_vlm (Gemma 3n chat) carry an _audio_type but that route+ 400s on both, and csm is transformers-only, so none may advertise the task."""+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _FakeUnsloth())+ for audio_type in ("whisper", "audio_vlm", "csm"):+ gguf = type(+ "_Gguf",+ (_FakeLlama,),+ {+ "is_loaded": True,+ "model_identifier": f"/srv/models/{audio_type}-Q4.gguf",+ "_is_audio": False,+ "_audio_type": audio_type,+ },+ )+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda gguf = gguf: gguf())+ (entry,) = inf._openai_model_objects()+ assert "task" not in entry, f"{audio_type} advertised as {entry.get('task')}"++ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama())+ for audio_type, is_audio in (("audio_vlm", False), ("whisper", True)):+ unsloth = type(+ "_Unsloth",+ (_FakeUnsloth,),+ {+ "active_model_name": f"org/{audio_type}-model",+ "models": {+ f"org/{audio_type}-model": {"is_audio": is_audio, "audio_type": audio_type}+ },+ },+ )+ monkeypatch.setattr(inf, "get_inference_backend", lambda unsloth = unsloth: unsloth())+ (entry,) = inf._openai_model_objects()+ assert "task" not in entry, f"{audio_type} advertised as {entry.get('task')}"++ # A transformers TTS codec still is tagged.+ unsloth = type(+ "_Tts",+ (_FakeUnsloth,),+ {+ "active_model_name": "unsloth/csm-1b",+ "models": {"unsloth/csm-1b": {"is_audio": True, "audio_type": "csm"}},+ },+ )+ monkeypatch.setattr(inf, "get_inference_backend", lambda: unsloth())+ (entry,) = inf._openai_model_objects()+ assert entry["task"] == "text-to-speech"++ # the mlx worker rejects audio generation even when its model metadata is tts.+ unsloth.models["unsloth/csm-1b"]["is_mlx"] = True+ (entry,) = inf._openai_model_objects()+ assert "task" not in entry+++def test_downloaded_tts_model_is_not_advertised_without_switch_support(monkeypatch):+ tts = _Info(+ "models--unsloth--csm-1b",+ "csm-1b",+ model_id = "unsloth/csm-1b",+ task = "text-to-speech",+ is_gguf = False,+ )+ _catalog(monkeypatch, [tts], picks = {})+ assert asyncio.run(inf._openai_catalog_objects()) == []+++def test_resident_media_status(monkeypatch):+ import core.inference.media_keepwarm as mk++ monkeypatch.setattr(mk, "engine_if_imported", lambda owner: None)+ assert inf._resident_media_status("text-to-image") is None+ monkeypatch.setattr(+ mk, "engine_if_imported", lambda owner: SimpleNamespace(status = lambda: {"loaded": False})+ )+ assert inf._resident_media_status("text-to-video") is None+ loaded = {"loaded": True, "repo_id": "unsloth/LTX-2.3-GGUF"}+ monkeypatch.setattr(+ mk, "engine_if_imported", lambda owner: SimpleNamespace(status = lambda: loaded)+ )+ assert inf._resident_media_status("text-to-video") == loaded++ def _boom():+ raise RuntimeError("cuda")++ monkeypatch.setattr(mk, "engine_if_imported", lambda owner: SimpleNamespace(status = _boom))+ assert inf._resident_media_status("text-to-image") is None+++def test_engine_if_imported_stays_out_of_torch(monkeypatch):+ import core.inference.media_keepwarm as mk+ from core.inference.gpu_arbiter import DIFFUSION, VIDEO++ for name in (+ "core.inference.diffusion",+ "core.inference.sd_cpp_backend",+ "core.inference.video",+ ):+ monkeypatch.delitem(sys.modules, name, raising = False)+ assert mk.engine_if_imported(DIFFUSION) is None+ assert mk.engine_if_imported(VIDEO) is None+++def test_classified_catalog_tags_task(monkeypatch):+ from hub.services.models import catalog_classification++ class _Model(BaseModel):+ id: str+ task: Optional[str] = None+ audio_type: Optional[str] = None++ monkeypatch.setattr(+ catalog_classification,+ "_local_model_classification",+ lambda model: ("text-to-speech", "csm"),+ )+ plain = object()+ tagged, kept, passthrough = inf._classified_catalog(+ [_Model(id = "a"), _Model(id = "b", task = "text-generation"), plain]+ )+ assert tagged.task == "text-to-speech" and tagged.audio_type == "csm"+ assert kept.task == "text-generation"+ assert passthrough is plain+++def test_retrieve_and_list_media_models_over_http(monkeypatch):+ _catalog(monkeypatch, _INFOS)+ app = FastAPI()+ install_api_error_handlers(app)+ app.include_router(inf.router, prefix = "/v1")+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ client = TestClient(app)++ listing = client.get("/v1/models").json()+ assert listing["object"] == "list"+ assert {m["id"]: m.get("task") for m in listing["data"]} == {+ "Qwen3-Q4": None,+ "unsloth/Z-Image-Turbo-GGUF": "text-to-image",+ "Lightricks/LTX-2": "text-to-video",+ }+ model = client.get("/v1/models/unsloth/Z-Image-Turbo-GGUF").json()+ assert model["task"] == "text-to-image" and model["loaded"] is False+ assert client.get("/v1/models/nope/missing").status_code == 404diff --git a/studio/frontend/src/features/settings/api/openai-model-catalog.ts b/studio/frontend/src/features/settings/api/openai-model-catalog.tsnew file mode 100644index 00000000000..95cd2234963--- /dev/null+++ b/studio/frontend/src/features/settings/api/openai-model-catalog.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export type OpenAIModel = {+ id: string;+ // Resident in memory now; the rest are downloaded and servable.+ loaded?: boolean;+ // On-disk GGUF quant. Ids stay bare for OpenAI compat, so append `:quant` to pin it.+ quant?: string;+};++type ApiOpenAIModelList = {+ data?: { id?: unknown; loaded?: unknown; quant?: unknown; task?: unknown }[];+};++const CHAT_TASKS = new Set(["text-generation"]);++export function chatModelsFromCatalog(body: unknown): OpenAIModel[] {+ const data = (body as ApiOpenAIModelList | null)?.data;+ if (!Array.isArray(data)) {+ return [];+ }+ return data.flatMap((entry) =>+ typeof entry?.id === "string" &&+ entry.id &&+ (typeof entry.task !== "string" || CHAT_TASKS.has(entry.task))+ ? [+ {+ id: entry.id,+ loaded: entry.loaded === true,+ quant: typeof entry.quant === "string" ? entry.quant : undefined,+ },+ ]+ : [],+ );+}diff --git a/studio/frontend/src/features/settings/api/openai-models.ts b/studio/frontend/src/features/settings/api/openai-models.tsindex f7f858452ad..2e6fe6cee3e 100644--- a/studio/frontend/src/features/settings/api/openai-models.ts+++ b/studio/frontend/src/features/settings/api/openai-models.ts@@ -3,40 +3,18 @@import { authFetch } from "@/features/auth";-export type OpenAIModel = {- id: string;- // Resident in memory now; the rest are downloaded and servable.- loaded?: boolean;- // On-disk GGUF quant. Ids stay bare for OpenAI compat, so append `:quant` to pin it.- quant?: string;-};+import { chatModelsFromCatalog, type OpenAIModel } from "./openai-model-catalog";-type ApiOpenAIModelList = {- data?: { id?: unknown; loaded?: unknown; quant?: unknown }[];-};+export type { OpenAIModel };/**- * The models this server can serve: `/v1/models` returns exactly the ids- * `/v1/chat/completions` resolves against, and accepts the UI session JWT.+ * The chat-capable models this server can serve: `/v1/models` also lists image,+ * video and speech-to-text models, which `/v1/chat/completions` cannot resolve.*/export async function listOpenAIModels(): Promise<OpenAIModel[]> {const res = await authFetch("/v1/models");if (!res.ok) {throw new Error(`Failed to list models (${res.status})`);}- const body = (await res.json()) as ApiOpenAIModelList;- if (!Array.isArray(body?.data)) {- return [];- }- return body.data.flatMap((entry) =>- typeof entry?.id === "string" && entry.id- ? [- {- id: entry.id,- loaded: entry.loaded === true,- quant: typeof entry.quant === "string" ? entry.quant : undefined,- },- ]- : [],- );+ return chatModelsFromCatalog(await res.json());}diff --git a/studio/frontend/tests/openai-model-catalog.test.ts b/studio/frontend/tests/openai-model-catalog.test.tsnew file mode 100644index 00000000000..cf67b61e32b--- /dev/null+++ b/studio/frontend/tests/openai-model-catalog.test.ts@@ -0,0 +1,38 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { chatModelsFromCatalog } from "../src/features/settings/api/openai-model-catalog.ts";++test("non-chat entries never reach the chat example picker", () => {+ const models = chatModelsFromCatalog({+ data: [+ { id: "unsloth/Qwen3-8B-GGUF", loaded: true, quant: "Q4_K_M" },+ { id: "unsloth/Z-Image-Turbo-GGUF", loaded: true, quant: "Q4_K_S", task: "text-to-image" },+ { id: "Lightricks/LTX-2", loaded: false, task: "text-to-video" },+ { id: "tiny", loaded: false, task: "automatic-speech-recognition" },+ { id: "unsloth/orpheus-3b-0.1-ft-GGUF", loaded: false, quant: "Q8_0", task: "text-to-speech" },+ { id: "unsloth/Llama-3.2-1B-Instruct-GGUF", loaded: false, task: "text-generation" },+ ],+ });+ assert.deepEqual(models, [+ { id: "unsloth/Qwen3-8B-GGUF", loaded: true, quant: "Q4_K_M" },+ { id: "unsloth/Llama-3.2-1B-Instruct-GGUF", loaded: false, quant: undefined },+ ]);+});++test("older servers without a task field list every entry as before", () => {+ const models = chatModelsFromCatalog({ data: [{ id: "a", loaded: true }, { id: "b" }] });+ assert.deepEqual(models, [+ { id: "a", loaded: true, quant: undefined },+ { id: "b", loaded: false, quant: undefined },+ ]);+});++test("malformed bodies yield no models", () => {+ assert.deepEqual(chatModelsFromCatalog(null), []);+ assert.deepEqual(chatModelsFromCatalog({}), []);+ assert.deepEqual(chatModelsFromCatalog({ data: [{ id: 3 }, { id: "" }, {}] }), []);+});