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
fix(studio): return 404 for mistyped GGUF model ids on /v1 API (#8389)
Souravrajvi077e29f4d94a6
diff --git a/studio/backend/core/inference/openai_auto_download.py b/studio/backend/core/inference/openai_auto_download.pyindex 12b886c7076..a3c1a0d74de 100644--- a/studio/backend/core/inference/openai_auto_download.py+++ b/studio/backend/core/inference/openai_auto_download.py@@ -134,6 +134,27 @@ def is_downloadable_ref(requested: str) -> bool:return True+def looks_like_gguf_hub_repo_id(repo_id: str) -> bool:+ """Whether *repo_id* names a Studio catalog entry, not a LiteLLM/OpenRouter label.++ Namespaced ids without a GGUF suffix are foreign routing labels (``openai/gpt-4o``).+ ``-GGUF`` and the ``unsloth/`` namespace mark ids clients pick from this server's+ model list (GGUF and Transformers-backed entries alike); a mistyped one must 404+ instead of being answered by another loaded model.+ """+ text = (repo_id or "").strip()+ if "/" not in text:+ return False+ from hub.utils.paths import is_valid_repo_id++ if not is_valid_repo_id(text):+ return False+ name = text.rsplit("/", 1)[-1]+ if name.lower().endswith("-gguf"):+ return True+ return text.lower().startswith("unsloth/")++def looks_like_quant(variant: Optional[str]) -> bool:"""Whether a ``:suffix`` names a GGUF quant rather than a foreign tag.diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex a2e347214ff..88d579a8890 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -4729,6 +4729,25 @@ def _record_refused_request(api_monitor.fail(entry_id, refusal.message)+def _resident_id_is_namespaced() -> bool:+ """Whether what is serving has an ``org/name`` id to compare a request against.++ A model loaded from a plain directory is advertised under a bare name, so a+ namespaced request cannot be told apart from it. Refusing one there would 404+ the weights that are in fact serving, so treat it as undecidable instead.+ """+ llama_backend = get_llama_cpp_backend()+ if getattr(llama_backend, "is_loaded", False):+ candidates = (+ getattr(llama_backend, "model_identifier", None),+ getattr(llama_backend, "_openai_advertised_id", None),+ _llama_public_model_id(llama_backend),+ )+ else:+ candidates = (getattr(get_inference_backend(), "active_model_name", None),)+ return any("/" in (public_model_id(c) or "") for c in candidates if c)++def _loaded_satisfies(requested: str) -> bool:"""Whether what is serving right now actually answers to *requested*.@@ -4915,7 +4934,11 @@ async def _reject_unservable_model(locally is still a concrete reference. Only runs while something is serving:with nothing loaded, :func:`_no_model_loaded_error` already says the right thing."""- from core.inference.openai_auto_download import looks_like_quant, split_model_ref+ from core.inference.openai_auto_download import (+ looks_like_gguf_hub_repo_id,+ looks_like_quant,+ split_model_ref,+ )if (not isinstance(requested_model, str)@@ -4925,6 +4948,7 @@ async def _reject_unservable_model(returnbase, variant = split_model_ref(requested_model)quantified = looks_like_quant(variant)+ gguf_hub_repo = looks_like_gguf_hub_repo_id(base)from core.inference.local_model_resolver import (index_is_built,recently_downloaded,@@ -4998,13 +5022,21 @@ async def _reject_unservable_model(raiseexcept Exception as exc:# Can't verify: an explicit quant still proves intent, so refuse; let anything else by.+ # A catalog-shaped id is not enough here. This path cannot tell "not downloaded" from+ # "the scan broke", so refusing one would 404 models that are downloaded and servable.logger.debug("unservable-model check failed for %r: %s", requested_model, exc)if not quantified:returndownloaded = here = switchable = Falseif still_indexing:_raise_still_indexing(requested_model, fastapi_request)- if not (quantified or here):+ if gguf_hub_repo and not (quantified or here):+ # Decisive only against a resident carrying a hub-style id of its own; a+ # directory-loaded model advertises a bare name that no namespaced request+ # can be told apart from. Checked here, not with the other shape tests, so+ # a foreign label never pays for it.+ gguf_hub_repo = await asyncio.to_thread(_resident_id_is_namespaced)+ if not (quantified or here or gguf_hub_repo):returnif switchable:# On disk and switching allowed, so the swap failed: the resident model is wrong weights.diff --git a/studio/backend/tests/test_openai_auto_download.py b/studio/backend/tests/test_openai_auto_download.pyindex a869c39bd70..c48c2e2711a 100644--- a/studio/backend/tests/test_openai_auto_download.py+++ b/studio/backend/tests/test_openai_auto_download.py@@ -270,6 +270,32 @@ def test_downloadable(raw):assert auto_dl.is_downloadable_ref(raw) is True+ "repo_id,expected",+ [+ ("unsloth/gemma-4-E2B-it-GGUF", True),+ ("org/nope-GGUF", True),+ ("unsloth/typo-vision", True),+ ("openai/gpt-4o", False),+ ("anthropic/claude-3.5-sonnet", False),+ ("meta-llama/llama-3-70b-instruct", False),+ ("org/Unlisted", False),+ ("gpt-4", False),+ ],+)+def test_looks_like_gguf_hub_repo_id(repo_id, expected):+ assert auto_dl.looks_like_gguf_hub_repo_id(repo_id) is expected+++def test_a_mistyped_gguf_repo_is_refused_while_another_model_is_loaded(monkeypatch):+ # #8376: a mistyped GGUF catalog id must 404, not be answered by the resident model.+ loaded = _Loaded("unsloth/A-GGUF", "UD-Q4_K_XL")+ with pytest.raises(HTTPException) as excinfo:+ _reject("unsloth/typo-vision-GGUF", loaded, monkeypatch)+ assert excinfo.value.status_code == 404+ assert excinfo.value.detail["error"]["code"] == "model_not_found"++def test_gguf_variants_skips_companions():variants = auto_dl._gguf_variants(_gguf_repo_info().siblings)# Companions are not quants of their own...@@ -1059,6 +1085,40 @@ def test_diagnosis_failure_never_breaks_a_servable_request(monkeypatch):assert asyncio.run(inference_route._reject_unservable_model("unsloth/B-GGUF", _Req())) is None+def _reject_with_active(model, active, monkeypatch):+ """Refusal check with a non-GGUF backend resident under *active*."""+ idle = type("B", (), {"is_loaded": False, "model_identifier": None, "hf_variant": None})()+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: idle)+ monkeypatch.setattr(+ inference_route,+ "get_inference_backend",+ lambda: type("B", (), {"active_model_name": active})(),+ )+ monkeypatch.setattr(+ "core.inference.local_model_resolver.resolve_local_gguf", lambda _n, **_kw: None+ )+ monkeypatch.setattr(inference_route, "_unavailable_model_message", _fake_unavailable_message)+ return asyncio.run(inference_route._reject_unservable_model(model, _Req()))+++def test_a_directory_loaded_model_is_not_refused_under_its_own_hub_id(monkeypatch):+ # ModelConfig.identifier is the path for a local load, so the model is advertised+ # under a bare name that no org/name request can be told apart from. Refusing one+ # 404s the weights serving right now.+ local = "/srv/models/gemma-3-4b-it"+ assert _reject_with_active("unsloth/gemma-3-4b-it", local, monkeypatch) is None+ assert _reject_with_active("unsloth/gemma-3-4b-it:latest", local, monkeypatch) is None+++def test_an_hf_cache_load_keeps_its_namespace_and_still_refuses_a_typo(monkeypatch):+ # A cache path maps back to org/name, so the resident id stays comparable there.+ cache = "/h/.cache/huggingface/hub/models--unsloth--gemma-3-4b-it/snapshots/abc"+ assert _reject_with_active("unsloth/gemma-3-4b-it", cache, monkeypatch) is None+ with pytest.raises(HTTPException) as excinfo:+ _reject_with_active("unsloth/typo-vision-GGUF", cache, monkeypatch)+ assert excinfo.value.status_code == 404++def test_anthropic_surface_gets_its_own_envelope(monkeypatch):loaded = _Loaded("unsloth/A-GGUF", "UD-Q4_K_XL")monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: loaded)diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex b9d13a69499..1e1e4340ca7 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -4768,6 +4768,33 @@ def _chat_error(payload):return exc.value.status_code, exc.value.detail+def test_chat_mistyped_gguf_repo_404s_before_vision_guard(monkeypatch):+ # #8376: image request with a mistyped GGUF id must 404, not 400 on the loaded model.+ from fastapi import HTTPException++ backend = _FakeBackend("unsloth/text-only-GGUF", "UD-Q4_K_XL")+ rec = _LoadRecorder(backend)+ _wire(monkeypatch, enabled = True, resolves_to = None, backend = backend, recorder = rec)+ monkeypatch.setattr(+ "utils.openai_auto_switch_settings.get_openai_auto_download_enabled", lambda: False+ )+ monkeypatch.setattr(+ resolver,+ "describe_local_miss",+ lambda _m: (resolver.MISS_MODEL_NOT_FOUND, ()),+ )+ payload = _chat_request(+ model = "unsloth/typo-vision-GGUF",+ image_base64 = "aGVsbG8=",+ )+ request = type("_R", (), {"url": type("_U", (), {"path": "/v1/chat/completions"})()})()+ with pytest.raises(HTTPException) as exc:+ asyncio.run(inference_route.openai_chat_completions(payload, request, "tester"))+ assert exc.value.status_code == 404+ assert exc.value.detail["error"]["code"] == "model_not_found"+ assert rec.calls == []++def test_chat_names_undownloaded_model_404s_with_available_ids(monkeypatch):# The reported bug: the model is not here, so the switch did nothing and /inference/load# cannot fix it. Name it and list what can serve.