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: serve installed mlx models through the openai-compatible api (#8768)

Maheswar Kumar37d3b6fdf7d3
diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.py
index 3503c20a79d..1b1d3b6134d 100644
--- a/studio/backend/core/inference/local_model_resolver.py
+++ b/studio/backend/core/inference/local_model_resolver.py
@@ -1,14 +1,16 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Resolve an OpenAI-request ``model`` string to a downloaded local GGUF.
-
-Used by the opt-in auto-switch path. The match is conservative: only names
-that map to an already-downloaded local GGUF (and a quant that is actually on
-disk) are eligible, so an arbitrary OpenAI model string still falls through to
-the loaded model (drop-in compat) and no surprise multi-GB download is ever
-triggered. The local-model scan is cached for a few seconds since auto-switch
-consults it per request.
+"""Resolve an OpenAI-request ``model`` string to a downloaded local model.
+
+Used by the opt-in auto-switch path. Two kinds of local model qualify: a GGUF
+(served by llama.cpp, with a quant that is actually on disk) and a non-GGUF
+checkpoint such as safetensors or MLX weights (served by the inference
+orchestrator). The match is conservative either way: only names that map to
+something already downloaded are eligible, so an arbitrary OpenAI model string
+still falls through to the loaded model (drop-in compat) and no surprise
+multi-GB download is ever triggered. The local-model scan is cached for a few
+seconds since auto-switch consults it per request.
"""
from __future__ import annotations
@@ -29,6 +31,7 @@ class _LocalGgufEntry:
loader_id: str # advertised id (repo id / folder name), also the override key
load_path: str # concrete on-disk dir/file passed to /load so it never downloads
variants: tuple[str, ...] # local quant labels; () for a standalone .gguf
+ is_gguf: bool = True # False routes the load to the inference orchestrator
_CACHE_TTL_S = 5.0
@@ -149,11 +152,202 @@ def _local_gguf_entry(loader_id: str, info) -> Optional[_LocalGgufEntry]:
return None
-def local_gguf_quants(info) -> Optional[tuple[str, ...]]:
- """On-disk quant labels for *info*, or None when it is not a servable local
- GGUF. Read from the files, not ``info.model_format``: the HF-cache scanner
- leaves that unset for GGUF snapshots, so filtering on it drops every cached
- GGUF. One scan tells /v1/models what it can serve and which quant to name."""
+# A LoRA directory can carry a copied config.json and tokenizer beside these, and
+# ModelConfig would then resolve its base model and fetch weights this resolver
+# promises never to download.
+_ADAPTER_MARKERS = ("adapter_config.json", "adapter_model.safetensors", "adapter_model.bin")
+# The multimodal sub-configs the repo's own vision detector reads, which is what tells
+# a served VLM apart from a plain seq2seq wearing the same architecture suffix.
+_MULTIMODAL_CONFIG_KEYS = (
+ "vision_config",
+ "img_processor",
+ "image_token_index",
+ "projector_config",
+ "audio_config",
+)
+_SUPPORTED_CONDITIONAL_AUDIO_MODEL_TYPES = frozenset({"csm", "whisper"})
+
+
+def _read_json(path):
+ """Parsed JSON for *path*, or None when it is absent or unreadable."""
+ import json
+ try:
+ with path.open(encoding = "utf-8") as handle:
+ return json.load(handle)
+ except (OSError, ValueError):
+ return None
+
+
+def _host_serves_mlx() -> bool:
+ """Whether this host's inference worker would pick MLXInferenceBackend.
+
+ Reads the detected verdict without triggering detection, so an unknown device
+ reads as "not MLX" and the entry is simply withheld until startup has decided.
+ """
+ try:
+ from utils.hardware import hardware as hw
+ return hw.DEVICE == hw.DeviceType.MLX
+ except Exception:
+ return False
+
+
+def _host_has_a_non_gguf_backend() -> bool:
+ """Whether this host can serve non-GGUF weights at all.
+
+ The worker picks MLX on Apple Silicon and Transformers everywhere else, so a host
+ with neither leaves the load to fail after the swap has unloaded the resident GGUF.
+ An installed torch is not enough: the Transformers worker imports unsloth, whose
+ get_device_type raises outright on a host with no NVIDIA, AMD or Intel accelerator,
+ so a CPU-only or Vulkan-only box with a CPU wheel serves GGUF alone. Read the
+ detected device rather than importing torch, which costs seconds on this path.
+ """
+ if _host_serves_mlx():
+ return True
+ try:
+ from utils.hardware import hardware as hw
+
+ if hw.DEVICE not in (hw.DeviceType.CUDA, hw.DeviceType.XPU):
+ return False
+ from importlib.util import find_spec
+
+ return find_spec("torch") is not None
+ except Exception:
+ return False
+
+
+def _has_safetensors_weights(load_dir) -> bool:
+ """Whether safetensors weights sit under the names the loader looks for.
+
+ Safetensors only: a .bin checkpoint is pickle-backed, and an API request must not
+ execute one without an explicit load action. The loader receives no variant, so
+ ``model.fp16.safetensors`` or a stray ``optimizer.safetensors`` is not weights it
+ can open.
+ """
+ import re
+
+ if (load_dir / "model.safetensors").is_file():
+ return True
+ if (load_dir / "model.safetensors.index.json").is_file():
+ return True
+ try:
+ return any(
+ re.fullmatch(r"model-\d+-of-\d+\.safetensors", f.name) for f in load_dir.iterdir()
+ )
+ except OSError:
+ return False
+
+
+def _is_generative_chat_config(config: dict) -> bool:
+ """Whether a config.json describes a checkpoint the chat loader can generate with."""
+ architectures = config.get("architectures")
+ # model_type cannot stand in for the list: transformers' causal mapping lists bert and bart.
+ if not isinstance(architectures, list) or not architectures:
+ return False
+ names = [name for name in architectures if isinstance(name, str)]
+ # Not every causal checkpoint wears ForCausalLM: GPT2LMHeadModel and friends are
+ # selected from model_type by the loader, and withholding them is the invisibility
+ # this whole path exists to remove.
+ if any(name.endswith(("ForCausalLM", "LMHeadModel")) for name in names):
+ return True
+ if not any(name.endswith("ForConditionalGeneration") for name in names):
+ return False
+ # ForConditionalGeneration is overloaded: T5 and BART wear it too, and the serving
+ # path has no AutoModelForSeq2SeqLM branch, so require a multimodal sub-config.
+ if any(key in config for key in _MULTIMODAL_CONFIG_KEYS):
+ return True
+ # whisper is the audio model rather than wearing one, so it carries no such sub-config.
+ # the MLX worker refuses ASR and TTS outright, so only a Transformers host serves these.
+ return not _host_serves_mlx() and _model_type_is_audio(config.get("model_type"))
+
+
+def _model_type_is_audio(model_type) -> bool:
+ """Whether *model_type* has a supported conditional audio serving path."""
+ return isinstance(model_type, str) and model_type in _SUPPORTED_CONDITIONAL_AUDIO_MODEL_TYPES
+
+
+def _weights_are_servable(load_dir) -> bool:
+ """Whether *load_dir* holds weights the chat loader can be pointed at.
+
+ On-disk shape only, nothing parsed from the config: safetensors weights, and none
+ of the markers that make a directory something other than a chat model (a diffusers
+ pipeline, a bare LoRA adapter, an embedder).
+ """
+ from routes.models import _local_pipeline_index
+
+ if _local_pipeline_index(load_dir) or not (load_dir / "config.json").is_file():
+ return False
+ if not _has_safetensors_weights(load_dir):
+ return False
+ if any((load_dir / name).is_file() for name in _ADAPTER_MARKERS):
+ return False
+ # Same marker is_embedding_model reads for a local path, without its memo, which
+ # would pin a verdict for the process from one scan.
+ return not (load_dir / "modules.json").is_file()
+
+
+def _config_is_servable_here(load_dir, config: dict) -> bool:
+ """Whether *config* describes a chat model an API request may load on its own.
+
+ Not whether the load will succeed: /v1/models advertises what this server has and
+ could serve, and a load that then fails is an honest error to the caller. Only the
+ approval boundary and the category are decided here.
+ """
+ from utils.security.remote_code_scan import REMOTE_CODE_CONFIG_FILES
+
+ # trust_remote_code needs an approval fingerprint a switch has not got; read as data only.
+ for name in REMOTE_CODE_CONFIG_FILES:
+ candidate = config if name == "config.json" else _read_json(load_dir / name)
+ # truthiness like the consent gate's _config_has_auto_map: an empty map runs nothing.
+ if isinstance(candidate, dict) and candidate.get("auto_map"):
+ return False
+ return _is_generative_chat_config(config)
+
+
+def _local_weights_entry(loader_id: str, info) -> Optional[_LocalGgufEntry]:
+ """Build an entry for a local non-GGUF checkpoint (safetensors, MLX) the
+ inference orchestrator can serve, else None.
+
+ Requires a root ``config.json`` beside safetensors weights, so a bare LoRA adapter
+ or a tokenizer-only snapshot is never offered as a model. Diffusers pipelines,
+ embedders, custom-code repos and partial downloads are rejected too.
+ """
+ from pathlib import Path
+
+ path = getattr(info, "path", None)
+ if not isinstance(path, str) or getattr(info, "partial", False):
+ return None
+ # model-independent, so first: with no backend every row is withheld anyway.
+ if not _host_has_a_non_gguf_backend():
+ return None
+ try:
+ p = Path(path)
+ if not p.is_dir():
+ return None
+ load_dir = _resolve_load_dir(p)
+ if not _weights_are_servable(load_dir):
+ return None
+ config = _read_json(load_dir / "config.json")
+ if not isinstance(config, dict) or not _config_is_servable_here(load_dir, config):
+ return None
+ # No quants: quantization is baked in, so there is no ":<quant>" to pin.
+ return _LocalGgufEntry(loader_id, str(load_dir), (), is_gguf = False)
+ except Exception:
+ return None
+
+
+def _local_servable_entry(loader_id: str, info) -> Optional[_LocalGgufEntry]:
+ """Entry for whichever backend can serve *info* from disk, GGUF first."""
+ return _local_gguf_entry(loader_id, info) or _local_weights_entry(loader_id, info)
+
+
+def local_servable_model(info) -> Optional[tuple[bool, tuple[str, ...]]]:
+ """``(is_gguf, on-disk quant labels)`` when this server can serve *info* straight
+ from disk, else None. Non-GGUF weights carry no quant labels.
+
+ Read from the files, not ``info.model_format``: the HF-cache scanner leaves that
+ unset for GGUF snapshots, so filtering on it drops every cached GGUF. One scan
+ tells /v1/models what it can serve and which quant to name.
+ """
from pathlib import Path
path = getattr(info, "path", None)
@@ -164,17 +358,29 @@ def local_gguf_quants(info) -> Optional[tuple[str, ...]]:
seg in (".studio_links", "ollama_links") for seg in Path(path).parts
):
return None
- entry = _local_gguf_entry(getattr(info, "id", "") or "", info)
- return entry.variants if entry is not None else None
+ entry = _local_servable_entry(getattr(info, "id", "") or "", info)
+ return (entry.is_gguf, entry.variants) if entry is not None else None
+
+def local_load_dir(path: Optional[str]) -> Optional[str]:
+ """The concrete directory *path* loads from, or None when it names no directory.
-def info_has_local_gguf(info) -> bool:
- """True when *info* points to on-disk GGUF weights the auto-switch path can load."""
- return local_gguf_quants(info) is not None
+ An HF cache repo resolves to its snapshot, which is what the orchestrator records as
+ the active model, so a caller comparing a scanned catalog path against resident state
+ is comparing the same string the loader used. Touches the filesystem.
+ """
+ from pathlib import Path
+
+ if not isinstance(path, str) or not path:
+ return None
+ try:
+ return str(_resolve_load_dir(Path(path)))
+ except Exception:
+ return path
def _build_index() -> dict[str, _LocalGgufEntry]:
- """Map normalized id/model_id/display_name -> local GGUF entry.
+ """Map normalized id/model_id/display_name -> local model entry.
Scans the same roots Unsloth's model picker lists (./models, the active plus
legacy/default HF caches, LM Studio dirs, and user scan folders) so a named
@@ -273,7 +479,7 @@ def _build_index() -> dict[str, _LocalGgufEntry]:
continue
# Advertise a client-facing alias, not an absolute filesystem path.
loader_id = _advertised_loader_id(info)
- entry = _local_gguf_entry(loader_id, info)
+ entry = _local_servable_entry(loader_id, info)
if entry is None:
continue
# Index every alias (including the path) so a client can resolve by any of
@@ -288,8 +494,9 @@ def _build_index() -> dict[str, _LocalGgufEntry]:
index.setdefault(key.strip().lower(), entry)
# Other revisions of the same repo resolve to their own weights, so a pin on
# one keeps working after Hugging Face writes a newer snapshot.
- for name, sibling_entry in _sibling_revision_entries(raw_id, loader_id):
- index.setdefault(name.strip().lower(), sibling_entry)
+ if entry.is_gguf:
+ for name, sibling_entry in _sibling_revision_entries(raw_id, loader_id):
+ index.setdefault(name.strip().lower(), sibling_entry)
return index
@@ -312,6 +519,9 @@ def _sibling_revision_entries(raw_id: str, loader_id: str):
(``<root>/models--org--name/snapshots/<rev>``). A scan folder that merely happens
to be called ``snapshots`` holds unrelated models, and treating those as
revisions would silently serve one model in place of another.
+
+ GGUF only: ``snapshot_variants_all_complete`` reports a revision offering no quants
+ as incomplete, so a non-GGUF repo pins to its scanned revision alone.
"""
from pathlib import Path
from types import SimpleNamespace
@@ -487,6 +697,7 @@ def resolve_local_gguf(
``load_path`` is the concrete on-disk path to hand /load (so it never fetches
a remote), ``loader_id`` is the advertised id used as the launch-override key.
+ ``gguf_variant`` is None for a non-GGUF checkpoint, which has no quant to pin.
``requested`` is ``repo`` or ``repo:VARIANT``. An exact id match wins first
(so ids containing a colon still resolve); else the last ``:VARIANT`` is split
off and resolves only when that quant is on disk, unless it names no quant at
@@ -539,6 +750,32 @@ def _resolve_from_index(
return None
+def local_target_is_gguf(load_path: Optional[str], loader_id: Optional[str] = None) -> bool:
+ """Whether an auto-switch target is served by llama.cpp rather than the orchestrator.
+
+ Reads the weights the load will actually open, so a rebuilt index that no longer
+ carries the entry cannot flip the answer mid-switch. Falls back to the indexed
+ entry, then to True, which is what the callers need for a target that is not a
+ concrete path: llama.cpp is the only backend auto-switch used before non-GGUF
+ support, and the idle-unload reload stash only ever holds a freed GGUF.
+
+ Touches the filesystem, so call it off the event loop.
+ """
+ from pathlib import Path
+ from types import SimpleNamespace
+
+ if isinstance(load_path, str) and load_path:
+ try:
+ if Path(load_path).exists():
+ return _local_gguf_entry("", SimpleNamespace(path = load_path)) is not None
+ except OSError:
+ pass
+ if not isinstance(loader_id, str) or not loader_id.strip():
+ return True
+ entry = _scan[1].get(loader_id.strip().lower())
+ return entry.is_gguf if entry is not None else True
+
+
MISS_MODEL_NOT_FOUND = "model_not_found"
MISS_VARIANT_NOT_FOUND = "variant_not_found"
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 7336028c8a7..f4a2f03abd7 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -5778,9 +5778,10 @@ def _monitor_active_model() -> Optional[str]:
# Peek: the monitor overlay is on by default and polls this read-only, so building
# the singleton to answer "nothing loaded" would import torch on a warm-disabled host.
backend = _peek_inference_backend()
- if backend is None:
+ # The advertised alias outlives an unload, so read it only while a model is active.
+ if backend is None or not backend.active_model_name:
return None
- return public_model_id(backend.active_model_name) or backend.active_model_name
+ return _orchestrator_public_model_id(backend) or backend.active_model_name
@asynccontextmanager
@@ -6550,6 +6551,16 @@ def _llama_public_model_id(llama_backend, fallback: Optional[str] = None) -> Opt
)
+def _orchestrator_public_model_id(backend) -> Optional[str]:
+ """The id to report for the model loaded in the inference orchestrator
+ (safetensors, MLX): the advertised repo id from an auto-switch load, else the
+ cleaned public id. Only meaningful while ``active_model_name`` is set -- an
+ unload leaves the alias behind, and every caller reads it through that gate."""
+ return getattr(backend, "_openai_advertised_id", None) or public_model_id(
+ getattr(backend, "active_model_name", None)
+ )
+
+
def _llama_status_model_ids(llama_backend) -> "tuple[Optional[str], Optional[str]]":
"""The ``(active_model, model_identifier)`` pair ``/api/inference/status`` publishes
for a loaded GGUF. A native-lease load reports only the display label, never the
@@ -6628,6 +6639,161 @@ def _target_is_vision(
return True
+def _target_accepts_audio_input(load_path: str) -> bool:
+ """Whether a local non-GGUF checkpoint accepts audio input (ASR or an audio VLM).
+
+ Read from the repo's own tokenizer special tokens, offline: the resolver only
+ yields local paths, and a detection failure must not block a swap. The ambient
+ HF token goes through for the same reason as the vision probe above.
+ """
+ from utils.models.model_config import detect_audio_type, is_audio_input_type
+ try:
+ return is_audio_input_type(
+ detect_audio_type(
+ load_path,
+ hf_token = os.environ.get("HF_TOKEN"),
+ local_files_only = True,
+ )
+ )
+ except Exception as exc:
+ logger.debug("auto-switch: audio probe failed for %s: %s", load_path, exc)
+ return True
+
+
+def _target_accepts_request_input(
+ load_path: str,
+ is_gguf: bool,
+ needs_vision: bool,
+ needs_audio: bool,
+ gguf_variant: Optional[str] = None,
+ need_image: bool = True,
+ needs_video: bool = False,
+) -> bool:
+ """Whether a switch target can accept this request's image or audio input.
+
+ A local GGUF takes both capabilities from its companion mmproj, so one probe
+ answers for either, modality-aware through ``need_image``. Other checkpoints
+ declare them apart: vision in the config architecture, audio input in the
+ tokenizer's special tokens.
+ """
+ if is_gguf:
+ return _target_is_vision(load_path, gguf_variant, need_image)
+ # input_video is llama.cpp's own part type, so a clip is refused right after the load.
+ if needs_video:
+ return False
+ if needs_audio and not _target_accepts_audio_input(load_path):
+ return False
+ # need_image, not needs_vision: an audio request sets needs_vision so a GGUF is
+ # asked for its projector, and demanding a vision tower here would refuse the
+ # audio checkpoints that can actually serve it.
+ return _target_is_vision(load_path) if (needs_vision and need_image) else True
+
+
+_AUDIO_IMAGE_INPUT_DETAIL = (
+ "This model takes audio or an image in one message, not both."
+ " Send the image on its own turn."
+)
+
+
+async def _preflight_audio_for_switch(audio_preflight: dict, target_is_gguf: bool) -> None:
+ """Apply the pre-switch audio rules that depend on the target's serving format.
+
+ Only for a swap that is about to run: these exist so a request the target cannot
+ serve fails before the load evicts the resident model, and where no swap happens the
+ serving branch decides for itself. A GGUF target is validated through
+ :func:`_prepare_audio_for_llama`, which accepts a ``data:`` URI and the containers
+ torchaudio cannot open, and supports ``continue_final_message``. A non-GGUF target is served by
+ :func:`_decode_audio_base64`, so the upload is validated with that same decoder and
+ the array handed back under ``decoded`` for the audio branch to reuse.
+ """
+ if target_is_gguf:
+ try:
+ audio_preflight["prepared"] = await asyncio.to_thread(
+ _prepare_audio_for_llama, audio_preflight["b64"]
+ )
+ except Exception:
+ raise HTTPException(
+ status_code = 400,
+ detail = openai_error_body(
+ "The 'audio_base64' value could not be decoded as audio.",
+ status = 400,
+ code = "invalid_value",
+ param = "audio_base64",
+ ),
+ ) from None
+ return
+ if audio_preflight.get("continue_final"):
+ raise HTTPException(
+ status_code = 400,
+ detail = "continue_final_message is not supported with audio input.",
+ )
+ if audio_preflight.get("has_image"):
+ raise HTTPException(status_code = 400, detail = _AUDIO_IMAGE_INPUT_DETAIL)
+ if not _audio_decoder_is_available():
+ raise HTTPException(
+ status_code = 400,
+ detail = openai_error_body(
+ "This server cannot decode audio input for a non-GGUF model: "
+ "torchaudio is not installed.",
+ status = 400,
+ code = "invalid_value",
+ param = "model",
+ ),
+ )
+ try:
+ audio_preflight["decoded"] = await asyncio.to_thread(
+ _decode_audio_base64, audio_preflight["b64"]
+ )
+ except Exception:
+ raise HTTPException(
+ status_code = 400,
+ detail = openai_error_body(
+ "The 'audio_base64' value could not be decoded as audio.",
+ status = 400,
+ code = "invalid_value",
+ param = "audio_base64",
+ ),
+ ) from None
+
+
+def _validate_image_base64(encoded: str) -> None:
+ """Decode one image far enough to reject malformed bytes before a switch."""
+ from io import BytesIO
+ from PIL import Image
+
+ image_data = base64.b64decode(encoded)
+ with Image.open(BytesIO(image_data)) as image:
+ image.load()
+
+
+async def _preflight_image_for_switch(image_preflight: dict, target_is_gguf: bool) -> None:
+ """Apply target-specific image checks before loading the resolved target."""
+ if not target_is_gguf and image_preflight.get("multiple"):
+ raise HTTPException(
+ status_code = 400,
+ detail = (
+ "This model takes one image per message. Attach one, or load a"
+ " GGUF build of it, which accepts several."
+ ),
+ )
+ if not target_is_gguf and image_preflight.get("remote") and image_preflight.get("b64") is None:
+ raise HTTPException(
+ status_code = 400,
+ detail = "Remote image URLs are not supported. Use a base64 data URL.",
+ )
+ encoded_images = (
+ image_preflight.get("b64s", ()) if target_is_gguf else (image_preflight.get("b64"),)
+ )
+ for encoded in encoded_images:
+ if encoded is None:
+ continue
+ try:
+ await asyncio.to_thread(_validate_image_base64, encoded)
+ except Exception:
+ detail = "Failed to process image." if target_is_gguf else "Failed to decode image"
+ raise HTTPException(status_code = 400, detail = detail) from None
+
+
def _messages_have_image(messages) -> bool:
return any(
isinstance(m.content, list) and any(isinstance(p, ImageContentPart) for p in m.content)
@@ -6635,6 +6801,17 @@ def _messages_have_image(messages) -> bool:
)
+def _messages_have_remote_image(messages) -> bool:
+ return any(
+ isinstance(m.content, list)
+ and any(
+ isinstance(p, ImageContentPart) and not p.image_url.url.startswith("data:")
+ for p in m.content
+ )
+ for m in messages
+ )
+
+
def _request_has_image(payload) -> bool:
if getattr(payload, "image_base64", None):
return True
@@ -6655,6 +6832,28 @@ def _anthropic_request_has_image(payload) -> bool:
return False
+def _anthropic_local_image_payloads(payload) -> list[str]:
+ """Base64 image sources translated by the Anthropic endpoint."""
+ encoded_images = []
+ for msg in getattr(payload, "messages", None) or ():
+ content = msg.get("content") if isinstance(msg, dict) else msg.content
+ if not isinstance(content, list):
+ continue
+ for block in content:
+ block_type = block.get("type") if isinstance(block, dict) else block.type
+ if block_type != "image":
+ continue
+ source = block.get("source") if isinstance(block, dict) else block.source
+ source_type = source.get("type") if isinstance(source, dict) else source.type
+ data = source.get("data") if isinstance(source, dict) else source.data
+ if source_type == "base64" and isinstance(data, str):
+ encoded_images.append(data)
+ url = source.get("url") if isinstance(source, dict) else source.url
+ if source_type == "url" and isinstance(url, str) and url.startswith("data:"):
+ encoded_images.append(url.partition(",")[2])
+ return encoded_images
+
+
def disable_openai_auto_switch_for_request(scope) -> None:
"""Opt a request out of OpenAI auto-switch. The public preview route uses this:
it always serves its pinned checkpoint, so a caller-supplied model must never
@@ -6922,7 +7121,13 @@ def _resident_id_is_namespaced() -> bool:
_llama_public_model_id(llama_backend),
)
else:
- candidates = (getattr(get_inference_backend(), "active_model_name", None),)
+ orchestrator = get_inference_backend()
+ active = getattr(orchestrator, "active_model_name", None)
+ # The alias outlives an unload, so it only describes a resident model while
+ # active_model_name is set, the same gate every other alias reader applies.
+ candidates = (
+ (active, getattr(orchestrator, "_openai_advertised_id", None)) if active else ()
+ )
return any("/" in (public_model_id(c) or "") for c in candidates if c)
@@ -6952,13 +7157,17 @@ def _loaded_satisfies(requested: str) -> bool:
# An Ollama-style tag (":latest", ":8b") names no file, so the repo is enough.
return True
return (getattr(llama_backend, "hf_variant", None) or "").lower() == variant.lower()
- active = getattr(get_inference_backend(), "active_model_name", None)
+ backend = get_inference_backend()
+ active = getattr(backend, "active_model_name", None)
if not active:
return False
# Only llama.cpp carries a quant identity, so this backend can only match on the repo.
if looks_like_quant(variant):
return False
- return _matches_any(base, [active, public_model_id(active)])
+ # The alias too: auto-switch records the repo id there, not in active_model_name.
+ return _matches_any(
+ base, [active, public_model_id(active), getattr(backend, "_openai_advertised_id", None)]
+ )
def _loaded_identity_satisfies(requested: str) -> bool:
@@ -6984,8 +7193,15 @@ def _loaded_identity_satisfies(requested: str) -> bool:
if advertised is None and identifier and _looks_like_local_path(identifier):
return False
return _matches_any(base, (identifier, advertised)) and _loaded_satisfies(requested)
- active = getattr(get_inference_backend(), "active_model_name", None)
- return bool(active and _matches_any(base, [active]) and _loaded_satisfies(requested))
+ backend = get_inference_backend()
+ active = getattr(backend, "active_model_name", None)
+ if not active:
+ return False
+ advertised = getattr(backend, "_openai_advertised_id", None)
+ # Same rule as the llama branch: answering from the path alone skips the recording.
+ if advertised is None and _looks_like_local_path(active):
+ return False
+ return _matches_any(base, (active, advertised)) and _loaded_satisfies(requested)
def _raise_still_indexing(requested_model: str, fastapi_request) -> None:
@@ -7047,17 +7263,27 @@ def _resident_quant_is(variant: Optional[str]) -> bool:
return bool(variant) and resident.lower() == variant.strip().lower()
-def _resolves_to_resident(load_path: Optional[str], *, llama_only: bool = False) -> bool:
+def _resolves_to_resident(
+ load_path: Optional[str],
+ *,
+ llama_only: bool = False,
+ exact_only: bool = False,
+) -> bool:
"""Whether a resolved on-disk path is what is already loaded.
``llama_only`` drops the Transformers backend: only llama.cpp carries a quant
identity, so a Transformers model active from a directory that also holds GGUF
- exports would otherwise answer a request for one of those quants.
+ exports would otherwise answer a request for one of those quants. ``exact_only``
+ drops the directory prefix rules, which exist for a GGUF loaded out of a directory
+ and would otherwise let a checkpoint nested under the loaded one read as resident.
"""
if not load_path:
return False
target = _norm_path(load_path)
llama_backend = get_llama_cpp_backend()
+ orchestrator_model = (
+ None if llama_only else getattr(get_inference_backend(), "active_model_name", None)
+ )
for candidate in (
getattr(llama_backend, "gguf_path", None)
if getattr(llama_backend, "is_loaded", False)
@@ -7065,13 +7291,17 @@ def _resolves_to_resident(load_path: Optional[str], *, llama_only: bool = False)
getattr(llama_backend, "model_identifier", None)
if getattr(llama_backend, "is_loaded", False)
else None,
- None if llama_only else getattr(get_inference_backend(), "active_model_name", None),
+ orchestrator_model,
):
if not candidate:
continue
current = _norm_path(candidate)
if current == target:
return True
+ # A non-GGUF checkpoint loads from its own directory, so a row nested under the
+ # loaded one is different weights however that model was loaded.
+ if exact_only or (candidate is orchestrator_model and orchestrator_model is not None):
+ continue
if current.startswith(f"{target}/"):
# A model directory holding the weights loaded from it. Nested entries
# (/models/A alongside /models/A/sub/B) matched too, so a request for A was
@@ -7086,6 +7316,22 @@ def _resolves_to_resident(load_path: Optional[str], *, llama_only: bool = False)
return False
+def _classify_and_probe_residency(
+ load_path: str, alias: Optional[str], llama_only: bool
+) -> tuple[bool, bool]:
+ """Classify a switch target's serving format and probe residency, in one pass.
+
+ Both touch the filesystem, so they share a single off-loop hop, and the format is
+ what decides how residency is matched: a non-GGUF checkpoint loads from its own
+ directory, so the GGUF prefix rules must not let a model nested under the loaded
+ one answer for it. Returns ``(is_gguf, is_resident)``.
+ """
+ from core.inference.local_model_resolver import local_target_is_gguf
+
+ is_gguf = local_target_is_gguf(load_path, alias)
+ return is_gguf, _resolves_to_resident(load_path, llama_only = llama_only, exact_only = not is_gguf)
+
+
def _innermost_indexed_owner(path: str) -> Optional[str]:
"""Longest catalog-listed model path containing *path*, or None if none does."""
best = None
@@ -7170,20 +7416,27 @@ async def _reject_unservable_model(
# would be answered by a resident Q4_K_M.
# Off-loop: reads the Transformers singleton, and the llama.cpp short-circuits above
# skip the offloaded reads, so on a restart this built the singleton on the loop.
- if (
+ resolved_is_resident = (
resolved is not None
- and await asyncio.to_thread(_resolves_to_resident, resolved[0], llama_only = quantified)
- and (not quantified or _resident_quant_is(variant))
- ):
+ and (
+ await asyncio.to_thread(
+ _classify_and_probe_residency, resolved[0], resolved[2], quantified
+ )
+ )[1]
+ )
+ if resolved_is_resident and (not quantified or _resident_quant_is(variant)):
return
downloaded = resolved is not None
# /v1/models may have advertised this id off its own scan while the index is cold.
advertised = _advertised_local_path(base)
- if (
+ # classified from the advertised path itself, since a resolver miss left the pair above safe.
+ advertised_is_resident = (
advertised is not None
- and await asyncio.to_thread(_resolves_to_resident, advertised, llama_only = quantified)
- and (not quantified or _resident_quant_is(variant))
- ):
+ and (
+ await asyncio.to_thread(_classify_and_probe_residency, advertised, base, quantified)
+ )[1]
+ )
+ if advertised_is_resident and (not quantified or _resident_quant_is(variant)):
return
# The exact ref may miss on the quant alone, so ask about the repo too.
here = (
@@ -7259,23 +7512,38 @@ async def _maybe_auto_switch_model(
require_image: bool = True,
modality_label: str = "image or audio",
claim_resident: bool = True,
+ require_audio_input: bool = False,
+ require_video: bool = False,
+ gguf_only: bool = False,
+ audio_preflight: Optional[dict] = None,
+ image_preflight: Optional[dict] = None,
) -> None:
- """Load a downloaded local GGUF named by an OpenAI request when auto-switch is on.
+ """Load a downloaded local model named by an OpenAI request when auto-switch is on.
+ Covers both formats this server can serve from disk: a GGUF through llama.cpp
+ and a non-GGUF checkpoint (safetensors, MLX) through the inference orchestrator.
No-op unless enabled and ``requested_model`` resolves to a downloaded local
model different from the loaded one. Unknown names fall through (drop-in
compat); a miss only reaches the network when auto-download is also on, and
even then only for ``namespace/name`` ids. ``require_vision`` rejects a swap
- to a text-only target before it runs, so an image request can't evict the
- resident vision model only to 400 afterwards. ``claim_resident`` claims a
- resident model the request adopts (clears the preview marker) at the no-load
- exits; a route that still has its own capability/backend checks that can reject
- (e.g. GGUF-only /v1/completions, /audio/generate) passes ``False`` and claims
- itself only after those checks pass, so a later rejection can't strand a
- preview-owned model as Unsloth-owned. ``require_image`` makes the vision check
- that rejection modality-aware, since an audio request needs the projector but
- not a vision tower. ``modality_label`` names the inputs actually attached, so
- the rejection does not report a modality the request never carried.
+ to a target that cannot accept the request's input before it runs, so an image
+ or audio request can't evict the resident model only to 400 afterwards.
+ ``claim_resident`` claims a resident model the request adopts (clears the preview
+ marker) at the no-load exits; a route that still has its own capability/backend
+ checks that can reject (e.g. GGUF-only /v1/completions, /audio/generate) passes
+ ``False`` and claims itself only after those checks pass, so a later rejection
+ can't strand a preview-owned model as Unsloth-owned. ``require_image`` makes that
+ rejection modality-aware for a GGUF, whose one projector carries both, and
+ ``require_audio_input`` covers a non-GGUF checkpoint, which declares the two
+ separately, and ``require_video`` rules a non-GGUF target out entirely, since
+ only llama.cpp takes a clip. ``modality_label`` names the inputs attached, so the
+ rejection does not report a modality the request never carried. ``gguf_only``
+ marks an endpoint that reads llama.cpp alone, where loading a non-GGUF model
+ would unload the resident one and leave the handler with nothing to serve.
+ ``audio_preflight`` carries an audio upload whose format-dependent
+ checks only the resolved target can decide; see
+ :func:`_preflight_audio_for_switch`. ``image_preflight`` does the same for
+ non-GGUF image count and byte validation.
"""
from utils.openai_auto_switch_settings import (
get_openai_auto_switch_enabled,
@@ -7284,6 +7552,7 @@ async def _maybe_auto_switch_model(
model_override_load_kwargs,
)
from core.inference.local_model_resolver import (
+ local_target_is_gguf,
resolve_local_gguf,
resolve_trusted_cached_local_gguf,
warm_index_soon,
@@ -7336,12 +7605,31 @@ async def _maybe_auto_switch_model(
if isinstance(scope, dict) and scope.get(_DISABLE_OPENAI_AUTO_SWITCH_SCOPE_KEY):
return
auto_switch_on = get_openai_auto_switch_enabled()
- # The reload-stash path also runs when idle-unload is active on its own (a
- # standalone UNSLOTH_MODEL_IDLE_TTL with auto-switch off), so a model the idle
- # loop freed is restored on the next request. The resolver-based switch still
- # requires the auto-switch toggle.
- # Configured, not effective: residency zeroes the TTL, and the stash still
- # has to be restorable after it is turned on.
+
+ def _refuse_non_gguf_endpoint() -> None:
+ """Refuse a switch target this endpoint cannot serve.
+
+ Raised only for a target the resolver found and that is not already serving:
+ a resident non-GGUF model reaches the handler's own error instead, since no
+ swap is pending to refuse.
+ """
+ message = (
+ f"This endpoint serves GGUF models only, and '{requested_model}' is not one. "
+ "Use /v1/chat/completions for this model."
+ )
+ # error_body_for_path, not the OpenAI shape: the Anthropic routes reach this too
+ # and the global handler passes an already-formatted body through as is.
+ path = getattr(getattr(fastapi_request, "url", None), "path", None)
+ raise HTTPException(
+ status_code = 400,
+ detail = (
+ error_body_for_path(path, message, status = 400, code = "invalid_value", param = "model")
+ if isinstance(path, str)
+ else message
+ ),
+ )
+
+ # configured, not effective: residency zeroes the TTL, and the stash still has to restore.
if not auto_switch_on and not idle_unload_is_configured():
# No switching to do, but a named model must still not be answered by another.
# Reject first: a request that is turned away here must not claim the slot.
@@ -7395,7 +7683,9 @@ async def _maybe_auto_switch_model(
await _maybe_auto_download_model(
requested_model,
fastapi_request,
- require_vision = require_vision,
+ # GGUF carries both from one mmproj, so the download guard takes
+ # either need; splitting them here would fetch a text-only repo.
+ require_vision = require_vision or require_audio_input,
current_subject = current_subject,
)
# Idle-unload may have freed the model; reload exactly what it freed
@@ -7440,6 +7730,22 @@ async def _maybe_auto_switch_model(
# takes the local branch and cannot trigger a download. override_id is the
# advertised repo id, the launch-override key and the public model id.
target_id, variant, override_id = resolved
+ # Not inferred from the quant: a GGUF loaded from a local directory carries none.
+ target_is_gguf = await asyncio.to_thread(local_target_is_gguf, target_id, override_id)
+ # no orchestrator means nothing non-GGUF is resident, so the cold build only precedes a 400.
+ if (
+ gguf_only
+ and not target_is_gguf
+ and resolved is not None
+ and _peek_inference_backend() is None
+ ):
+ _refuse_non_gguf_endpoint()
+ # Resolved once, off the loop: a cold orchestrator build waits on hardware detection.
+ target_backend = (
+ get_llama_cpp_backend()
+ if target_is_gguf
+ else await asyncio.to_thread(get_inference_backend)
+ )
backend = get_llama_cpp_backend()
# A bare model id (no :VARIANT) is satisfied by any loaded quant of that
# repo, so it never reloads a different local quant that already serves it.
@@ -7454,6 +7760,20 @@ async def _maybe_auto_switch_model(
# so a model loaded manually by repo id (identifier = repo id) and one
# loaded by auto-switch (identifier = path, advertised = repo id) both
# count as already serving rather than triggering a needless reswap.
+ if not target_is_gguf:
+ active = getattr(target_backend, "active_model_name", None)
+ if not active:
+ return False
+ # _matches_any, not a lowercased set: two scan roots differing only by
+ # case are different weights on a case-sensitive filesystem, and a false
+ # match here records the alias on the wrong resident model.
+ loaded_keys = [active, getattr(target_backend, "_openai_advertised_id", None)]
+ if _matches_any(target_id, loaded_keys):
+ return True
+ # two scan roots can advertise one basename, so it cannot vouch for a path.
+ if _looks_like_local_path(target_id) and _looks_like_local_path(active):
+ return False
+ return _matches_any(override_id, loaded_keys)
if not backend.is_loaded or not backend.model_identifier:
return False
loaded_keys = {backend.model_identifier.lower()}
@@ -7478,9 +7798,8 @@ async def _maybe_auto_switch_model(
# busy guard), so the loaded model can't change under this.
if resolved is None or not override_id:
return
- b = get_llama_cpp_backend()
- if getattr(b, "_openai_advertised_id", None) != override_id:
- b._openai_advertised_id = override_id
+ if getattr(target_backend, "_openai_advertised_id", None) != override_id:
+ target_backend._openai_advertised_id = override_id
if _already_serving():
# A non-preview request adopting this model claims it for Unsloth, so a later
@@ -7489,16 +7808,31 @@ async def _maybe_auto_switch_model(
_set_preview_resident(None)
_record_serving_alias()
return
- # An image/audio request naming a different text-only GGUF would load it
+ # Loading a non-GGUF model unloads the resident GGUF, and these endpoints read
+ # llama.cpp alone, so the swap would strand them with nothing to serve.
+ if gguf_only and not target_is_gguf and resolved is not None:
+ _refuse_non_gguf_endpoint()
+ # An image/audio request naming a different text-only target would load it
# here and only 400 below, evicting the working model. Reject before the
# swap. Only the resolver branch (an explicit new target); the reload-stash
- # path just restores the model the request was already using. Both vision and
- # audio input come from a companion mmproj (a filesystem probe) -- run it off
- # the loop, like the resolver above.
+ # path just restores the model the request was already using. The probe hits
+ # the filesystem, so run it off the loop like the resolver above.
+ target_requires_image = require_image
+ if require_audio_input and not target_is_gguf and audio_preflight is not None:
+ target_requires_image = bool(audio_preflight.get("has_image"))
if (
- require_vision
+ (require_vision or require_audio_input)
and resolved is not None
- and not await asyncio.to_thread(_target_is_vision, target_id, variant, require_image)
+ and not await asyncio.to_thread(
+ _target_accepts_request_input,
+ target_id,
+ target_is_gguf,
+ require_vision,
+ require_audio_input,
+ variant,
+ target_requires_image,
+ require_video,
+ )
):
raise HTTPException(
status_code = 400,
@@ -7509,6 +7843,15 @@ async def _maybe_auto_switch_model(
param = "model",
),
)
+ # resolver branch only, like the probe above: a reload-stash restore changes no format.
+ if audio_preflight is not None and resolved is not None:
+ await _preflight_audio_for_switch(audio_preflight, target_is_gguf)
+ if (
+ image_preflight is not None
+ and resolved is not None
+ and (target_is_gguf or not require_audio_input)
+ ):
+ await _preflight_image_for_switch(image_preflight, target_is_gguf)
key = _switch_key(override_id, variant)
_note_switch_waiter(key, 1)
waiter_noted = True
@@ -7545,12 +7888,7 @@ async def _maybe_auto_switch_model(
)
load_kwargs = {"model_path": target_id, "gguf_variant": variant}
load_kwargs.update(
- model_override_load_kwargs(
- override,
- # Set for every GGUF the resolver returns; the reload
- # stash carries the quant it froze.
- is_gguf = bool(variant) or target_id.lower().endswith(".gguf"),
- )
+ model_override_load_kwargs(override, is_gguf = target_is_gguf)
)
saved_gpu_ids = load_kwargs.get("gpu_ids")
if saved_gpu_ids and not await _override_gpu_ids_still_resolve(
@@ -7615,20 +7953,17 @@ async def _maybe_auto_switch_model(
current_request_counted = True,
**durable_cancel_kw,
)
- _raise_if_generation_cancelled()
_switch_loaded_ok = True
+ # publish the completed load before a late cancellation is observed.
+ target_backend._openai_advertised_id = override_id
+ target_backend._loaded_by_user_action = False
+ _raise_if_generation_cancelled()
finally:
if not claim_resident:
if _switch_loaded_ok or _loaded_slot_ident() == target_id:
_set_preview_resident(_loaded_slot_ident())
else:
_set_preview_resident(_switch_prior_marker)
- # Advertise the repo id (not the concrete load path) as the loaded
- # model's public id and override key for /v1/models and idle stash.
- get_llama_cpp_backend()._openai_advertised_id = override_id
- # API provenance: idle auto-unload may free this one even when
- # scoped to API loads.
- get_llama_cpp_backend()._loaded_by_user_action = False
finally:
# Deregister before releasing the gate: otherwise a swap on another
# loop counts this finished request as queued and unloads its model.
@@ -7644,7 +7979,12 @@ async def _maybe_auto_switch_model(
await _reject_unservable_model(requested_model, fastapi_request)
-async def _auto_switch_from_request_body(request: Request, current_subject: str):
+async def _auto_switch_from_request_body(
+ request: Request,
+ current_subject: str,
+ *,
+ gguf_only: bool = False,
+):
"""Run auto-switch from a raw-body endpoint's ``model`` without changing its
pre-feature status codes: a malformed/non-dict body yields no model (so an
unloaded backend still 503s, not 500), and the caller re-reads to surface the
@@ -7665,7 +8005,9 @@ async def _auto_switch_from_request_body(request: Request, current_subject: str)
# GGUF model loaded" after this returns. Don't claim here (claim_resident=False); the
# caller claims only once it confirms a GGUF is loaded, so that 503 can't strand a
# preview-owned non-GGUF model as Unsloth-owned.
- await _maybe_auto_switch_model(model, request, current_subject, claim_resident = False)
+ await _maybe_auto_switch_model(
+ model, request, current_subject, claim_resident = False, gguf_only = gguf_only
+ )
return body
@@ -12048,6 +12390,23 @@ async def load_model_gated(
_finish_load_attempt(attempt)
+def _restore_alias_if_failed_load_left_the_prior_model(
+ backend, prior_alias: Optional[str], prior_active: Optional[str]
+) -> None:
+ """Put the advertised alias back when a failed load left the previous model serving.
+
+ :func:`_load_model_impl` clears the alias before calling ``load_model`` so a request
+ naming the old model cannot be answered by the new weights. A repair raises
+ ``SidecarSwapInProgress`` before the old worker is torn down, so the orchestrator keeps
+ ``active_model_name`` and its mirrors and that model goes on serving. Without this it
+ would go on serving stripped of the id ``/v1/models``, the monitor and response ids
+ report it under.
+ """
+ if prior_active is None or getattr(backend, "active_model_name", None) != prior_active:
+ return
+ backend._openai_advertised_id = prior_alias
+
+
async def _load_model_impl(
request: LoadRequest,
fastapi_request: Request,
@@ -12787,6 +13146,12 @@ async def _load_model_impl(
# Load in a thread so the event loop stays free for download progress
# polling and other requests.
+ # Cleared before the load, not after: load_model publishes active_model_name for
+ # the new weights, and a concurrent request matching the old alias in that window
+ # would be answered by them. Auto-switch sets the repo id once this returns.
+ _prior_alias = getattr(backend, "_openai_advertised_id", None)
+ _prior_active = getattr(backend, "active_model_name", None)
+ backend._openai_advertised_id = None
try:
success = await asyncio.to_thread(
backend.load_model,
@@ -12804,10 +13169,12 @@ async def _load_model_impl(
)
except Exception:
_restore_marker_if_prior_preview_still_resident()
+ _restore_alias_if_failed_load_left_the_prior_model(backend, _prior_alias, _prior_active)
raise
if not success:
_restore_marker_if_prior_preview_still_resident()
+ _restore_alias_if_failed_load_left_the_prior_model(backend, _prior_alias, _prior_active)
# Check if YAML says this model needs trust_remote_code.
if not request.trust_remote_code:
model_defaults = load_model_defaults(config.identifier)
@@ -15143,7 +15510,7 @@ async def _generate_tts_wav(
model_info = backend.models.get(backend.active_model_name, {})
if not model_info.get("is_audio"):
raise HTTPException(status_code = 400, detail = "Active model is not an audio model.")
- model_name = public_model_id(backend.active_model_name)
+ model_name = _orchestrator_public_model_id(backend)
audio_type = model_info.get("audio_type")
supported_audio_types = _TRANSFORMERS_TTS_AUDIO_TYPES
_audio_model_id = getattr(backend, "active_model_name", None) or model_name
@@ -16248,6 +16615,16 @@ async def transcribe_audio_raw(
# =====================================================================
+def _audio_decoder_is_available() -> bool:
+ """Whether _decode_audio_base64 can run here; it needs torchaudio, which a
+ GGUF-only install does not ship. find_spec keeps this off the import path."""
+ try:
+ from importlib.util import find_spec
+ return find_spec("torchaudio") is not None
+ except Exception:
+ return False
+
+
def _decode_audio_base64(b64: str) -> "np.ndarray":
"""Decode base64 audio (any format) → float32 numpy array at 16kHz."""
import torchaudio
@@ -16640,6 +17017,32 @@ def _latest_user_image_payload(messages) -> "Optional[str]":
return None
+def _local_image_payloads_from_messages(messages) -> list[str]:
+ """All data-URL image payloads in OpenAI-format messages."""
+ encoded_images = []
+ for message in messages or ():
+ content = message.get("content") if isinstance(message, dict) else message.content
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ part_type = part.get("type") if isinstance(part, dict) else part.type
+ if part_type != "image_url":
+ continue
+ image_url = part.get("image_url") if isinstance(part, dict) else part.image_url
+ url = image_url.get("url") if isinstance(image_url, dict) else image_url.url
+ if isinstance(url, str) and url.startswith("data:"):
+ encoded_images.append(url.partition(",")[2])
+ return encoded_images
+
+
+def _request_local_image_payloads(payload) -> list[str]:
+ """All data-URL and distinct legacy image payloads forwarded locally."""
+ encoded_images = _local_image_payloads_from_messages(getattr(payload, "messages", None) or ())
+ if _legacy_image_is_distinct(payload):
+ encoded_images.append(payload.image_base64)
+ return encoded_images
+
+
# ── External provider proxy ──────────────────────────────────────
@@ -18262,6 +18665,11 @@ async def produce_openai_chat_completions(
_needs_vision = False
_needs_image = False
_modality_label = "image or audio"
+ _needs_audio_input = False
+ _needs_video = False
+ _predecoded_audio = None
+ _preprepared_audio = None
+ _image_preflight = None
if _should_validate_before_switch():
_pre_parsed = _extract_content_parts(payload.messages)
if not _pre_parsed[1]:
@@ -18346,10 +18754,7 @@ async def produce_openai_chat_completions(
param = "tool_choice",
),
)
- # Reject an oversized audio upload before the switch: the size cap is a
- # cheap, target-independent length check, so a too-large payload must not
- # load a GGUF only to 413 afterward (the decode itself stays post-switch to
- # avoid decoding a valid upload twice).
+ # target-independent, unlike the format-dependent checks the switch itself runs.
if payload.audio_base64 and len(payload.audio_base64) > _MAX_AUDIO_B64_CHARS:
raise HTTPException(status_code = 413, detail = "Audio file is too large (max ~25 MB).")
# Reject streaming n>1 before the switch: only the non-streaming GGUF path
@@ -18363,12 +18768,14 @@ async def produce_openai_chat_completions(
# Audio input rides the same companion-mmproj projector as vision, so a
# text-only target can't serve it either; guard both before the switch. An
# audio-only request asks for the projector alone, since an audio model's
- # projector carries no vision tower.
+ # projector carries no vision tower. A safetensors or MLX checkpoint
+ # declares audio input separately, so it is tracked apart as well.
_needs_image = bool(_pre_parsed[2]) or _request_has_image(payload)
# Video rides that projector too. Its own /props gate can only run after
# the load, so this at least keeps a text-only target from evicting a
# working model to serve a clip it could never take.
- _needs_vision = _needs_image or bool(payload.audio_base64) or bool(payload.video_base64)
+ _needs_video = bool(payload.video_base64)
+ _needs_vision = _needs_image or bool(payload.audio_base64) or _needs_video
# Name what is actually attached, so the refusal does not report a
# modality the request never carried.
_modality_label = (
@@ -18389,6 +18796,35 @@ async def produce_openai_chat_completions(
_, _video_rejection = _video_b64_rejection(payload.video_base64)
if _video_rejection is not None:
raise HTTPException(status_code = _video_rejection[0], detail = _video_rejection[1])
+ _needs_audio_input = bool(payload.audio_base64)
+
+ # the rest of the audio checks depend on the target's format, so the switch runs them.
+ _audio_preflight = (
+ {
+ "b64": payload.audio_base64,
+ "continue_final": _continue_final_message(payload),
+ "has_image": _images_in_last_user_message(payload.messages)
+ or _legacy_image_is_distinct(payload),
+ }
+ if _needs_audio_input
+ else None
+ )
+ if _needs_image and _pre_parsed is not None:
+ _images_on_turn = _images_in_last_user_message(payload.messages)
+ _legacy_image_distinct = _legacy_image_is_distinct(payload)
+ _local_image_payloads = _request_local_image_payloads(payload)
+ _image_b64 = _pre_parsed[2] or payload.image_base64
+ if _image_b64 is None and _local_image_payloads:
+ _image_b64 = _local_image_payloads[0]
+ _image_preflight = {
+ "b64": _image_b64,
+ "b64s": _local_image_payloads,
+ "remote": _messages_have_remote_image(payload.messages),
+ "multiple": (
+ _images_on_turn + int(_legacy_image_distinct) > 1
+ or bool(_pre_parsed[2] and _legacy_image_distinct)
+ ),
+ }
# Defer the resident claim: chat has several post-switch capability checks that can still
# reject (Whisper without audio, n>1 on a non-GGUF backend, tool or response_format
@@ -18403,7 +18839,14 @@ async def produce_openai_chat_completions(
require_image = _needs_image,
modality_label = _modality_label,
claim_resident = False,
+ require_audio_input = _needs_audio_input,
+ require_video = _needs_video,
+ audio_preflight = _audio_preflight,
+ image_preflight = _image_preflight,
)
+ if _audio_preflight is not None:
+ _predecoded_audio = _audio_preflight.get("decoded")
+ _preprepared_audio = _audio_preflight.get("prepared")
llama_backend = get_llama_cpp_backend()
using_gguf = llama_backend.is_loaded
@@ -18507,7 +18950,7 @@ async def produce_openai_chat_completions(
raise HTTPException(status_code = _status, detail = _detail)
# Clean public id so the response never echoes a local path; the audio
# branch below receives this sanitized label too.
- model_name = public_model_id(backend.active_model_name) or payload.model
+ model_name = _orchestrator_public_model_id(backend) or payload.model
# Restated here because the pre-switch check runs only when an automatic
# load may: one SSE stream carries a single choice either way.
if payload.stream and _wants_multiple_choices(payload):
@@ -18573,14 +19016,17 @@ async def produce_openai_chat_completions(
# refusing would break asking by voice about a picture attached before.
# api_monitor directly: _reject is not bound this early in the handler.
if _images_in_last_user_message(payload.messages) or _legacy_image_is_distinct(payload):
- _audio_image_detail = (
- "This model takes audio or an image in one message, not both."
- " Send the image on its own turn."
- )
+ _audio_image_detail = _AUDIO_IMAGE_INPUT_DETAIL
api_monitor.fail(monitor_id, _audio_image_detail)
raise HTTPException(status_code = 400, detail = _audio_image_detail)
try:
- audio_array = _decode_audio_base64(payload.audio_base64)
+ # Decoded before the switch; only a path that skipped that preflight
+ # (no automatic load could run) still has to do it here.
+ audio_array = (
+ _predecoded_audio
+ if _predecoded_audio is not None
+ else _decode_audio_base64(payload.audio_base64)
+ )
system_prompt, chat_messages, _ = _extract_content_parts(payload.messages)
except Exception as e:
api_monitor.fail(monitor_id, _friendly_error(e))
@@ -19019,8 +19465,10 @@ async def produce_openai_chat_completions(
if len(payload.audio_base64) > _MAX_AUDIO_B64_CHARS:
raise _reject(413, "Audio file is too large (max ~25 MB).")
try:
- audio_b64, audio_format = await asyncio.to_thread(
- _prepare_audio_for_llama, payload.audio_base64
+ audio_b64, audio_format = (
+ _preprepared_audio
+ if _preprepared_audio is not None
+ else await asyncio.to_thread(_prepare_audio_for_llama, payload.audio_base64)
)
except Exception as e:
logger.warning("Audio decode failed: %s", e, exc_info = True)
@@ -22328,7 +22776,8 @@ def _openai_model_objects() -> list[dict]:
if backend.active_model_name:
model_info = backend.models.get(backend.active_model_name, {})
entry = {
- "id": public_model_id(backend.active_model_name),
+ # The alias, or an LM Studio model switched to by repo id loses its publisher.
+ "id": _orchestrator_public_model_id(backend),
"object": "model",
"created": _created,
"owned_by": _OWNED_BY,
@@ -22446,6 +22895,29 @@ async def _cached_local_catalog() -> list:
return _CATALOG_CACHE["models"]
+def _servable_catalog_rows(catalog) -> list[tuple[object, bool, tuple[str, ...], bool]]:
+ """``(info, is_gguf, quants, resident)`` per catalog entry this server can serve
+ from disk. Module scope, and always called through ``asyncio.to_thread``: the file
+ checks stat many files and the residency check reads the inference singleton."""
+ from core.inference.local_model_resolver import local_load_dir, local_servable_model
+
+ rows = []
+ for info in catalog:
+ servable = local_servable_model(info)
+ if servable is None:
+ continue
+ is_gguf, quants = servable
+ path = getattr(info, "path", None)
+ # the load dir, since an HF cache repo loads as a snapshot exact_only cannot match.
+ resident = _resolves_to_resident(
+ path if is_gguf else local_load_dir(path),
+ llama_only = is_gguf,
+ exact_only = not is_gguf,
+ )
+ rows.append((info, is_gguf, quants, resident))
+ return rows
+
+
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
@@ -22459,39 +22931,28 @@ async def _openai_catalog_objects() -> list[dict]:
for entry in await asyncio.to_thread(_openai_model_objects):
by_id[entry["id"]] = {**entry, "loaded": True}
- # Locally available (downloaded/cached) models that are not already loaded.
- # Advertise only GGUF models /v1 can actually serve (llama.cpp). GGUF-ness is
- # read from the on-disk files, not model_format: the HF-cache scanner leaves
- # model_format unset for GGUF snapshots, so a model_format filter would drop
- # every cached GGUF. The file checks run off the loop.
- from core.inference.local_model_resolver import local_gguf_quants
-
+ # Downloaded but unloaded: GGUF via llama.cpp, other weights via the orchestrator.
catalog = await _cached_local_catalog()
- # One scan yields both "is this servable" and its on-disk quants, so no second pass.
- servable = await asyncio.to_thread(
- lambda: [(i, q) for i in catalog if (q := local_gguf_quants(i)) is not None]
- )
- for info, quants in servable:
+ for info, is_gguf, quants, loaded in await asyncio.to_thread(_servable_catalog_rows, catalog):
cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))
if not cid or cid in by_id:
continue
+ if loaded and not is_gguf:
+ resident_id = _orchestrator_public_model_id(get_inference_backend())
+ if resident_id in by_id:
+ continue
obj = {
"id": cid,
"object": "model",
"created": _created,
"owned_by": _OWNED_BY,
- # A manual load keys the resident entry by path basename while the catalog
- # uses the alias, so match on the path or the alias reads as not loaded.
- # llama-only: a Transformers model live from a directory that also holds
- # GGUF exports must not mark one of these GGUF entries loaded, or the
- # examples pin a quant nothing can serve with switching off.
- "loaded": _resolves_to_resident(getattr(info, "path", None), llama_only = True),
+ "loaded": loaded,
}
# The id stays bare for OpenAI compat; a client appends ":<quant>" to pin one.
# For the resident model that must be the quant actually loaded, not the
# preferred one on disk, or the listing advertises alias:Q4 while Q8 serves.
resident_quant = getattr(get_llama_cpp_backend(), "hf_variant", None)
- if obj["loaded"] and resident_quant:
+ if is_gguf and loaded and resident_quant:
obj["quant"] = resident_quant
elif quants:
obj["quant"] = quants[0]
@@ -22564,9 +23025,7 @@ async def openai_retrieve_model(model_id: str, current_subject: str = Depends(ge
(llama_backend.model_identifier, _llama_public_model_id(llama_backend))
)
if backend.active_model_name:
- raw_to_public.append(
- (backend.active_model_name, public_model_id(backend.active_model_name))
- )
+ raw_to_public.append((backend.active_model_name, _orchestrator_public_model_id(backend)))
for raw, clean in raw_to_public:
if model_id_matches(model_id, raw):
for entry in _loaded:
@@ -22648,7 +23107,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
raise HTTPException(status_code = 400, detail = "Request body must be a JSON object")
# Opt-in: load the requested local GGUF before the loaded-state check.
- body = await _auto_switch_from_request_body(request, current_subject)
+ body = await _auto_switch_from_request_body(request, current_subject, gguf_only = True)
if not llama_backend.is_loaded:
_status, _detail = await _no_model_loaded_error(
"No GGUF model loaded. Load a GGUF model first.",
@@ -22962,7 +23421,7 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(get
# no reliable pre-load probe -- is_embedding_model keys on a sentence-transformers
# modules.json a bare .gguf never has -- so embeddings auto-switch is best-effort:
# a non-embedding target switches, then llama-server returns a no-pooling error.
- body = await _auto_switch_from_request_body(request, current_subject)
+ body = await _auto_switch_from_request_body(request, current_subject, gguf_only = True)
if not llama_backend.is_loaded:
_status, _detail = await _no_model_loaded_error(
"No GGUF model loaded. Load a GGUF model first.",
@@ -23665,7 +24124,7 @@ async def _responses_non_streaming(
try:
_sink_token = _monitor_perf_sink.set(inner_perf if monitor_id else None)
try:
- result = await openai_chat_completions(chat_req, request)
+ result = await openai_chat_completions(chat_req, request, current_subject)
finally:
_monitor_perf_sink.reset(_sink_token)
@@ -24923,23 +25382,27 @@ async def openai_responses(
param = "tool_choice",
),
)
- # After input validation so a 400 never triggers a load. Switches the
- # streaming path; non-streaming re-checks via the idempotent chat handler.
- # require_vision rejects a swap to a text-only target before it runs, so an
- # image request can't evict the resident vision model only to 400 afterwards
- # (the non-streaming chat re-check short-circuits on _already_serving).
- await _maybe_auto_switch_model(
- _switch_model_for_payload(payload),
- request,
- current_subject,
- require_vision = _messages_have_image(messages),
- # Streaming Responses require a GGUF backend and 400 in _responses_stream after this
- # switch; claiming here would strand a preview-owned model as Unsloth-owned for a
- # request that never generates. Defer to the middleware, which claims on a 2xx.
- claim_resident = False,
- )
-
if payload.stream:
+ # streaming preflights here; non-streaming delegates its complete preflight to chat.
+ _responses_has_image = _messages_have_image(messages)
+ _responses_image_b64s = _local_image_payloads_from_messages(messages)
+ await _maybe_auto_switch_model(
+ _switch_model_for_payload(payload),
+ request,
+ current_subject,
+ require_vision = _responses_has_image,
+ claim_resident = False,
+ gguf_only = True,
+ image_preflight = (
+ {
+ "b64": _responses_image_b64s[0],
+ "b64s": _responses_image_b64s,
+ "multiple": False,
+ }
+ if _responses_image_b64s
+ else None
+ ),
+ )
monitor_id = None
if not getattr(request.state, "skip_api_monitor", False):
monitor_id = api_monitor.start(
@@ -25399,6 +25862,7 @@ async def anthropic_count_tokens(
# count_tokens only tokenizes (no generation), so it must not adopt the resident
# model; the middleware likewise excludes count_tokens from its claim.
claim_resident = False,
+ gguf_only = True,
)
llama_backend = get_llama_cpp_backend()
@@ -25515,6 +25979,9 @@ async def anthropic_messages(
# invalid request never evicts the loaded model.
_validate_anthropic_client_tools(payload.tools)
+ _anthropic_has_image = _anthropic_request_has_image(payload)
+ _anthropic_image_b64s = _anthropic_local_image_payloads(payload)
+
# Mixing Anthropic server tools with custom client tools is unsupported (the
# server-tool loop can't relay client functions back to the caller). Reject
# before the switch too -- it depends only on the payload -- so an invalid
@@ -25558,9 +26025,7 @@ async def anthropic_messages(
_selects_server_tools = _anthropic_selects_server_tools(
payload, requested_studio_tools, _has_client_tool
)
- _server_tools_requested_pre = _selects_server_tools and not _anthropic_request_has_image(
- payload
- )
+ _server_tools_requested_pre = _selects_server_tools and not _anthropic_has_image
if _server_tools_requested_pre:
from core.inference.tools import ALL_TOOLS as _ALL_TOOLS_PRE
@@ -25600,11 +26065,21 @@ async def anthropic_messages(
_switch_model_for_payload(payload),
request,
current_subject,
- require_vision = _anthropic_request_has_image(payload),
+ require_vision = _anthropic_has_image,
# The image normalization below can still 400 after this switch, so defer the claim:
# the middleware claims on a 2xx, so a rejected request never strands a preview-owned
# model.
claim_resident = False,
+ gguf_only = True,
+ image_preflight = (
+ {
+ "b64": _anthropic_image_b64s[0],
+ "b64s": _anthropic_image_b64s,
+ "multiple": False,
+ }
+ if _anthropic_image_b64s
+ else None
+ ),
)
if not llama_backend.is_loaded:
_status, _detail = await _no_model_loaded_error(
@@ -25642,7 +26117,7 @@ async def anthropic_messages(
# Enforce vision guard + re-encode embedded images to PNG so the Anthropic
# endpoint matches /v1/chat/completions.
- if _anthropic_request_has_image(payload):
+ if _anthropic_has_image:
_has_image = await asyncio.to_thread(
_normalize_anthropic_openai_images,
openai_messages,
diff --git a/studio/backend/tests/test_active_generations.py b/studio/backend/tests/test_active_generations.py
index 8a4d2b44df0..5e4180f8fd2 100644
--- a/studio/backend/tests/test_active_generations.py
+++ b/studio/backend/tests/test_active_generations.py
@@ -1193,7 +1193,7 @@ def _install_completions_stream_mock(monkeypatch, events):
)
monkeypatch.setattr(inf_mod, "_automatic_model_load_may_run", lambda: False)
- async def _no_auto_switch(request, current_subject):
+ async def _no_auto_switch(request, current_subject, **_kwargs):
return await request.json()
monkeypatch.setattr(inf_mod, "_auto_switch_from_request_body", _no_auto_switch)
@@ -1315,7 +1315,7 @@ def test_completions_proxy_non_stream_is_visible_to_the_swap_gate(monkeypatch):
)
monkeypatch.setattr(inf_mod, "_automatic_model_load_may_run", lambda: False)
- async def _no_auto_switch(request, current_subject):
+ async def _no_auto_switch(request, current_subject, **_kwargs):
return await request.json()
monkeypatch.setattr(inf_mod, "_auto_switch_from_request_body", _no_auto_switch)
@@ -1388,7 +1388,7 @@ def test_embeddings_proxy_is_visible_to_the_swap_gate(monkeypatch):
)
monkeypatch.setattr(inf_mod, "_automatic_model_load_may_run", lambda: False)
- async def _no_auto_switch(request, current_subject):
+ async def _no_auto_switch(request, current_subject, **_kwargs):
return await request.json()
monkeypatch.setattr(inf_mod, "_auto_switch_from_request_body", _no_auto_switch)
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index aee220ffb40..98d5d698f7e 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -22,6 +22,24 @@ from models.inference import LoadRequest
from core.inference import local_model_resolver as resolver
from utils import openai_auto_switch_settings as settings
+# captured before the autouse fixture below pins it, so its own test can reach the real one.
+_REAL_HOST_HAS_NON_GGUF_BACKEND = resolver._host_has_a_non_gguf_backend
+
+
[email protected](autouse = True)
+def _host_serves_non_gguf(monkeypatch):
+ """Pin the host-capability gates for the classifier tests.
+
+ They are about the config rules, not about whether this machine happens to have
+ torch or MLX installed, and an unpinned MLX verdict made the whole file pass or fail
+ by platform. Each gate is covered by its own test below.
+ """
+ from utils.hardware import hardware as hw
+
+ monkeypatch.setattr(resolver, "_host_has_a_non_gguf_backend", lambda: True)
+ # the device itself, not the helper, so a test setting DEVICE for itself still wins.
+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CUDA, raising = False)
+
@pytest.fixture(autouse = True)
def _clean_resolver_index():
@@ -124,6 +142,10 @@ def _wire(monkeypatch, *, enabled, resolves_to, backend, recorder):
monkeypatch.setattr(inference_route, "_auto_switch_waiters", {})
+async def _noop_reject(*_args, **_kwargs):
+ return None
+
+
def _run_hook(model = "some/model"):
asyncio.run(inference_route._maybe_auto_switch_model(model, object(), "tester"))
@@ -188,6 +210,51 @@ def test_known_unloaded_model_switches_once(monkeypatch):
assert backend.model_identifier == "unsloth/B-GGUF"
+def test_a_late_cancel_keeps_the_completed_switch_metadata(monkeypatch):
+ backend = _FakeBackend("unsloth/A-GGUF")
+ cancel_event = threading.Event()
+ calls = []
+
+ async def _load(
+ request,
+ *_args,
+ load_cancel_event = None,
+ **_kwargs,
+ ):
+ assert load_cancel_event is cancel_event
+ calls.append(request)
+ backend.model_identifier = request.model_path
+ backend.is_loaded = True
+ cancel_event.set()
+
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/models/B.gguf", "Q4_K_M", "unsloth/B-GGUF"),
+ backend = backend,
+ recorder = _load,
+ )
+ request = types.SimpleNamespace(
+ state = types.SimpleNamespace(generation_cancel_event = cancel_event)
+ )
+ inference_route._set_preview_resident(None)
+ try:
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route._maybe_auto_switch_model(
+ "unsloth/B-GGUF", request, "tester", claim_resident = False
+ )
+ )
+
+ assert exc.value.status_code == 409
+ assert len(calls) == 1
+ assert backend._openai_advertised_id == "unsloth/B-GGUF"
+ assert backend._loaded_by_user_action is False
+ assert inference_route._is_preview_resident("/models/B.gguf")
+ finally:
+ inference_route._set_preview_resident(None)
+
+
def test_resident_model_skips_the_filesystem_resolver(monkeypatch):
backend = _FakeBackend("unsloth/Muse-Glimmer-30B-GGUF", "UD-Q4_K_XL")
rec = _LoadRecorder(backend)
@@ -413,17 +480,42 @@ def test_same_repo_same_variant_does_not_reload(monkeypatch):
assert rec.calls == []
-def test_responses_endpoint_wires_auto_switch_before_dispatch():
- # The /v1/responses endpoint must invoke the auto-switch hook before either
- # dispatcher so streaming requests switch too. Asserted on the source, which
- # is immune to test-ordering effects on the shared inference module.
+def test_responses_endpoint_wires_auto_switch_before_streaming_dispatch():
+ # streaming bypasses chat, so its switch must run before dispatch.
import inspect
src = inspect.getsource(inference_route.openai_responses)
assert "_maybe_auto_switch_model" in src
hook_at = src.index("_maybe_auto_switch_model")
+ assert src.index("if payload.stream:") < hook_at
assert hook_at < src.index("_responses_stream")
- assert hook_at < src.index("_responses_non_streaming")
+
+
+def test_nonstreaming_responses_passes_subject_to_chat(monkeypatch):
+ from models.inference import ResponsesRequest
+
+ seen = {}
+
+ async def _capture(_payload, _request, current_subject):
+ seen["current_subject"] = current_subject
+ raise RuntimeError("stop after dispatch")
+
+ monkeypatch.setattr(inference_route, "openai_chat_completions", _capture)
+ request = types.SimpleNamespace(
+ state = types.SimpleNamespace(skip_api_monitor = True),
+ url = types.SimpleNamespace(path = "/v1/responses"),
+ method = "POST",
+ )
+ with pytest.raises(RuntimeError, match = "stop after dispatch"):
+ asyncio.run(
+ inference_route.openai_responses(
+ ResponsesRequest(model = "org/B-GGUF", input = "hi"),
+ request,
+ "tester",
+ )
+ )
+
+ assert seen == {"current_subject": "tester"}
def test_embeddings_endpoint_wires_auto_switch_before_loaded_check():
@@ -519,7 +611,7 @@ def test_local_gguf_entry_rejects_standalone_companions(tmp_path, monkeypatch):
proj = tmp_path / "mmproj-F16.gguf"
proj.write_text("x")
assert resolver._local_gguf_entry("p", SimpleNamespace(path = str(proj))) is None
- assert resolver.info_has_local_gguf(SimpleNamespace(id = str(proj), path = str(proj))) is False
+ assert resolver.local_servable_model(SimpleNamespace(id = str(proj), path = str(proj))) is None
root = tmp_path / "MTP"
root.mkdir()
main = root / "Qwen3.6-27B-MTP-Q6_K.gguf"
@@ -2486,23 +2578,76 @@ def test_build_index_survives_a_failing_scanner(tmp_path, monkeypatch):
assert any(e.loader_id == "org/Repo-GGUF" for e in index.values())
-def test_info_has_local_gguf_reads_files_not_model_format(tmp_path):
+def test_non_gguf_entries_skip_gguf_sibling_revision_scans(tmp_path, monkeypatch):
+ from types import SimpleNamespace
+
+ import routes.models as models_route
+ from storage import studio_db
+ from utils import hf_cache_settings
+ import utils.paths as paths
+
+ snapshot = tmp_path / "models--org--Repo" / "snapshots" / "rev-new"
+ info = SimpleNamespace(
+ id = str(snapshot),
+ path = str(snapshot),
+ model_id = "org/Repo",
+ display_name = "Repo",
+ )
+ monkeypatch.setattr(models_route, "_scan_models_dir", lambda *a, **k: [info])
+ monkeypatch.setattr(models_route, "_scan_hf_cache", lambda *a, **k: [])
+ monkeypatch.setattr(models_route, "_scan_lmstudio_dir", lambda *a, **k: [])
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: tmp_path)
+ monkeypatch.setattr(models_route, "_is_hidden_model", lambda *a, **k: False)
+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [])
+ monkeypatch.setattr(paths, "legacy_hf_cache_dir", lambda: None)
+ monkeypatch.setattr(paths, "hf_default_cache_dir", lambda: None)
+ monkeypatch.setattr(paths, "lmstudio_model_dirs", lambda: [])
+ monkeypatch.setattr(studio_db, "list_scan_folders", lambda: [])
+ monkeypatch.setattr(
+ resolver,
+ "_local_servable_entry",
+ lambda loader_id, _info: resolver._LocalGgufEntry(
+ loader_id, str(snapshot), (), is_gguf = False
+ ),
+ )
+ monkeypatch.setattr(
+ resolver,
+ "_sibling_revision_entries",
+ lambda *_a: pytest.fail("non-GGUF discovery walked GGUF sibling revisions"),
+ )
+
+ index = resolver._build_index()
+
+ assert any(not entry.is_gguf for entry in index.values())
+
+
+def test_local_servable_model_reads_files_not_model_format(tmp_path):
# Codex: HF-cache GGUF snapshots leave model_format unset, so /v1/models must
- # decide GGUF-ness from the on-disk files. A standalone .gguf (no model_format)
- # is servable; a safetensors-only dir is not.
+ # decide the format from the on-disk files. A checkpoint dir needs a root
+ # config.json to prove it is a model and not a bare adapter.
from types import SimpleNamespace
gguf = tmp_path / "model-Q4_K_M.gguf"
gguf.write_bytes(b"x" * 32)
- assert resolver.info_has_local_gguf(SimpleNamespace(id = str(gguf), path = str(gguf))) is True
+ assert resolver.local_servable_model(SimpleNamespace(id = str(gguf), path = str(gguf))) == (
+ True,
+ (),
+ )
st = tmp_path / "safetensors_model"
st.mkdir()
- (st / "model.safetensors").write_bytes(b"x" * 32)
- assert resolver.info_has_local_gguf(SimpleNamespace(id = str(st), path = str(st))) is False
+ (st / "model.safetensors").write_bytes(_safetensors_bytes())
+ (st / "tokenizer.json").write_text("{}")
+ (st / "tokenizer_config.json").write_text('{"chat_template": "{{ messages }}"}')
+ assert resolver.local_servable_model(SimpleNamespace(id = str(st), path = str(st))) is None
+ (st / "config.json").write_text(_CHAT_CONFIG)
+ assert resolver.local_servable_model(SimpleNamespace(id = str(st), path = str(st))) == (
+ False,
+ (),
+ )
-def test_info_has_local_gguf_excludes_ollama_links(tmp_path):
+def test_local_servable_model_excludes_ollama_links(tmp_path):
# Codex P2: Ollama entries come from a scanner _build_index skips, so their
# advertised ids never resolve; the catalog must not report them as servable.
from types import SimpleNamespace
@@ -2512,13 +2657,18 @@ def test_info_has_local_gguf_excludes_ollama_links(tmp_path):
ollama_gguf = links / "model-Q4_K_M.gguf"
ollama_gguf.write_bytes(b"x" * 32)
assert (
- resolver.info_has_local_gguf(SimpleNamespace(id = "ollama/foo:latest", path = str(ollama_gguf)))
- is False
+ resolver.local_servable_model(
+ SimpleNamespace(id = "ollama/foo:latest", path = str(ollama_gguf))
+ )
+ is None
)
# The same GGUF outside an ollama-link dir is still servable.
plain = tmp_path / "model-Q4_K_M.gguf"
plain.write_bytes(b"x" * 32)
- assert resolver.info_has_local_gguf(SimpleNamespace(id = str(plain), path = str(plain))) is True
+ assert resolver.local_servable_model(SimpleNamespace(id = str(plain), path = str(plain))) == (
+ True,
+ (),
+ )
def test_embeddings_input_present_helper():
@@ -3035,7 +3185,12 @@ def _chat_msg(text = "hi"):
return ChatMessage(role = "user", content = text)
-def _responses_payload(*, tools = None, set_model = True):
+def _responses_payload(
+ *,
+ tools = None,
+ set_model = True,
+ stream = None,
+):
from models.inference import ResponsesRequest
kwargs = dict(input = "hi")
@@ -3043,6 +3198,8 @@ def _responses_payload(*, tools = None, set_model = True):
kwargs["model"] = "org/B-GGUF"
if tools is not None:
kwargs["tools"] = tools
+ if stream is not None:
+ kwargs["stream"] = stream
return ResponsesRequest(**kwargs)
@@ -3243,7 +3400,8 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):
# target can't be loaded and evict the working audio model. Assert the handler
# flags require_vision so the hook's multimodal probe runs, and that it asks for
# the projector alone: an audio model's projector carries no vision tower, so
- # requiring one would refuse the very models that serve the request.
+ # requiring one would refuse the very models that serve the request. A
+ # safetensors or MLX checkpoint declares audio apart, so that flag rides along.
from models.inference import ChatMessage, ImageContentPart, ImageUrl
class _Reached(Exception):
@@ -3260,12 +3418,21 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):
require_image = True,
modality_label = "image or audio",
claim_resident = True,
+ require_audio_input = False,
+ require_video = False,
+ gguf_only = False,
+ audio_preflight = None,
+ image_preflight = None,
):
captured.update(
require_vision = require_vision,
require_image = require_image,
modality_label = modality_label,
claim_resident = claim_resident,
+ require_audio_input = require_audio_input,
+ audio_preflight_has_image = (
+ audio_preflight.get("has_image") if audio_preflight is not None else None
+ ),
)
raise _Reached()
@@ -3280,6 +3447,8 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):
"require_image": False,
"modality_label": "audio",
"claim_resident": False,
+ "require_audio_input": True,
+ "audio_preflight_has_image": False,
}
# An image in the same request does need the vision tower.
@@ -3296,8 +3465,25 @@ def test_chat_audio_input_guards_target_before_switch(monkeypatch):
"require_image": True,
"modality_label": "image or audio",
"claim_resident": False,
+ "require_audio_input": True,
+ "audio_preflight_has_image": True,
}
+ # an image on an earlier turn stays valid: the non-GGUF audio route listens to
+ # the current recording and deliberately permits referring back to prior images.
+ payload = _chat_request(
+ model = "org/B-GGUF",
+ audio_base64 = "AAAA",
+ messages = [
+ ChatMessage(role = "user", content = [img]),
+ ChatMessage(role = "assistant", content = "I can see it."),
+ ChatMessage(role = "user", content = "Tell me more."),
+ ],
+ )
+ with pytest.raises(_Reached):
+ asyncio.run(inference_route.openai_chat_completions(payload, object(), "tester"))
+ assert captured["audio_preflight_has_image"] is False
+
def test_completions_rejects_object_prompt_before_switch(monkeypatch):
# Codex P2: an object prompt like {"prompt": {}} is a deterministic client error
@@ -3653,9 +3839,12 @@ def test_count_tokens_forwards_vision_guard_to_switch(monkeypatch):
*,
require_vision = False,
claim_resident = True,
+ require_audio_input = False,
+ gguf_only = False,
):
captured["require_vision"] = require_vision
captured["claim_resident"] = claim_resident
+ captured["gguf_only"] = gguf_only
raise _Reached()
monkeypatch.setattr(inference_route, "_anthropic_request_has_image", lambda p: True)
@@ -3665,6 +3854,8 @@ def test_count_tokens_forwards_vision_guard_to_switch(monkeypatch):
asyncio.run(inference_route.anthropic_count_tokens(payload, object(), "tester"))
assert captured["require_vision"] is True
assert captured["claim_resident"] is False
+ # llama.cpp serves this endpoint alone, so a non-GGUF swap must not be attempted.
+ assert captured["gguf_only"] is True
# ── /chat/count_tokens: what the recount prices ───────────────────
@@ -8243,12 +8434,17 @@ def test_a_video_request_labels_the_switch_refusal_video(monkeypatch):
require_image = True,
modality_label = "image or audio",
claim_resident = True,
+ require_audio_input = False,
+ require_video = False,
+ audio_preflight = None,
+ image_preflight = None,
):
captured.update(
require_vision = require_vision,
require_image = require_image,
modality_label = modality_label,
claim_resident = claim_resident,
+ require_video = require_video,
)
raise _Reached()
@@ -8263,9 +8459,63 @@ def test_a_video_request_labels_the_switch_refusal_video(monkeypatch):
"require_image": False,
"modality_label": "video",
"claim_resident": False,
+ "require_video": True,
}
+def test_a_video_request_never_switches_to_a_non_gguf_target():
+ """A clip is served through llama.cpp's input_video part alone, so the chat handler
+ rejects one on any other backend. Without this the swap unloads the resident GGUF
+ and the request 400s straight after, which is what the guard exists to prevent."""
+ # need_image False is the combination that used to fall through to the accepting branch.
+ assert (
+ inference_route._target_accepts_request_input(
+ "/srv/models/VL-MLX",
+ False,
+ True,
+ False,
+ None,
+ False,
+ True,
+ )
+ is False
+ )
+ # an image alongside the clip must not talk it back into the swap either.
+ assert (
+ inference_route._target_accepts_request_input(
+ "/srv/models/VL-MLX",
+ False,
+ True,
+ False,
+ None,
+ True,
+ True,
+ )
+ is False
+ )
+ # the GGUF arm still decides on the companion mmproj, so needs_video does not short it.
+ seen = {}
+
+ def _probe(
+ path,
+ variant = None,
+ need_image = True,
+ ):
+ seen.update(path = path, need_image = need_image)
+ return True
+
+ import unittest.mock as _mock
+
+ with _mock.patch.object(inference_route, "_target_is_vision", _probe):
+ assert (
+ inference_route._target_accepts_request_input(
+ "/srv/models/A.gguf", True, True, False, None, False, True
+ )
+ is True
+ )
+ assert seen == {"path": "/srv/models/A.gguf", "need_image": False}
+
+
# Preview ownership regressions.
@@ -8332,3 +8582,1410 @@ def test_count_tokens_does_not_own_an_independent_load(monkeypatch):
asyncio.run(drive())
assert not inference_route._is_preview_resident("/outputs/studio-b")
+
+
+# ── non-GGUF discovery and switching ──
+
+
+# Chat generation is the only route these entries feed, so the classifier requires a
+# generative architecture; every fixture below is a plain causal LM unless it says otherwise.
+_CHAT_CONFIG = '{"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3"}'
+
+
+def _safetensors_bytes(nbytes = 32):
+ """Filler standing in for a .safetensors file. The resolver checks the name, not the
+ contents: whether the bytes load is the loader's answer to give."""
+ return b"\0" * nbytes
+
+
+def _local_checkpoint(root, name = "Qwen3-MLX-4bit"):
+ """An on-disk non-GGUF checkpoint: config.json and a tokenizer beside safetensors."""
+ path = root / name
+ path.mkdir()
+ (path / "config.json").write_text(_CHAT_CONFIG)
+ (path / "model.safetensors").write_bytes(_safetensors_bytes())
+ (path / "tokenizer.json").write_text("{}")
+ (path / "tokenizer_config.json").write_text("{}")
+ return path
+
+
+def test_a_diffusers_pipeline_is_not_a_servable_chat_model(tmp_path):
+ # The Images and Video backends own these; /v1/chat/completions cannot serve them.
+ from types import SimpleNamespace
+
+ pipeline = _local_checkpoint(tmp_path, "SomeDiffusionPipeline")
+ (pipeline / "model_index.json").write_text("{}")
+ info = SimpleNamespace(id = str(pipeline), path = str(pipeline))
+ assert resolver.local_servable_model(info) is None
+
+
+def test_a_partial_download_is_not_a_servable_chat_model(tmp_path):
+ # Advertising an incomplete snapshot hands out an id whose load must fail.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path)
+ info = SimpleNamespace(id = str(path), path = str(path), partial = True)
+ assert resolver.local_servable_model(info) is None
+
+
+def test_an_adapter_only_directory_is_not_a_servable_chat_model(tmp_path):
+ # A bare LoRA adapter has no config.json and cannot be served on its own.
+ from types import SimpleNamespace
+
+ path = tmp_path / "adapter"
+ path.mkdir()
+ (path / "adapter_config.json").write_text("{}")
+ (path / "adapter_model.safetensors").write_bytes(_safetensors_bytes())
+ info = SimpleNamespace(id = str(path), path = str(path))
+ assert resolver.local_servable_model(info) is None
+
+
+def test_an_installed_mlx_model_is_indexed_and_resolves(tmp_path, monkeypatch):
+ # Issue #8748: an unloaded MLX model was invisible to the resolver, so a request
+ # naming it 404'd as not downloaded.
+ import routes.models as models_route
+ from utils import paths
+
+ from utils.hardware import hardware as hw
+
+ path = _local_checkpoint(tmp_path)
+ (path / "config.json").write_text(
+ '{"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3", "quantization": {"group_size": 64, "bits": 4}}'
+ )
+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.MLX)
+ monkeypatch.setattr(models_route, "_scan_hf_cache", lambda *a, **k: [])
+ monkeypatch.setattr(models_route, "_scan_lmstudio_dir", lambda *a, **k: [])
+ monkeypatch.setattr(paths, "legacy_hf_cache_dir", lambda: None)
+ monkeypatch.setattr(paths, "hf_default_cache_dir", lambda: None)
+ monkeypatch.setattr(paths, "lmstudio_model_dirs", lambda: [])
+ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [{"path": str(tmp_path)}])
+
+ resolver._scan = (0.0, {})
+ assert resolver.resolve_local_gguf(str(path)) == (str(path), None, path.name)
+ # No quant to pin: these weights carry their quantization internally.
+ assert resolver.resolve_local_gguf(f"{path.name}:Q4_K_M") is None
+ assert resolver.local_target_is_gguf(str(path), path.name) is False
+ # An index that no longer carries the entry must not flip the answer to GGUF.
+ resolver._scan = (0.0, {})
+ assert resolver.local_target_is_gguf(str(path), path.name) is False
+
+
+# The families mlx-lm rewrites before it imports anything. Their own module names do
+# not exist, so a find_spec on model_type hid every quant of them from /v1/models.
+_REMAPPED_MLX_FAMILIES = ("mistral", "kimi_k2", "llava", "falcon_mamba", "minimax_m2")
+
+
[email protected]("model_type", _REMAPPED_MLX_FAMILIES)
+def test_a_family_mlx_lm_remaps_is_listed_in_the_catalog(tmp_path, monkeypatch, model_type):
+ # #8748 for Mistral, Devstral, Ministral, Magistral, Codestral and Kimi K2: the
+ # loader applies MODEL_REMAPPING first, so predicting the import from model_type
+ # withheld every quant these ship. The catalog advertises what is on disk.
+ from types import SimpleNamespace
+ from utils.hardware import hardware as hw
+
+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.MLX)
+ path = _local_checkpoint(tmp_path, f"{model_type}-4bit")
+ (path / "config.json").write_text(
+ json.dumps(
+ {
+ "architectures": ["MistralForCausalLM"],
+ "model_type": model_type,
+ "quantization": {"group_size": 64, "bits": 4},
+ }
+ )
+ )
+ monkeypatch.setattr(
+ inference_route,
+ "get_inference_backend",
+ lambda: SimpleNamespace(active_model_name = None, models = {}),
+ )
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _FakeBackend(None))
+ info = SimpleNamespace(id = str(path), model_id = str(path), path = str(path))
+ assert resolver.local_servable_model(info) == (False, ())
+ rows = inference_route._servable_catalog_rows([info])
+ assert [(is_gguf, quants) for _i, is_gguf, quants, _r in rows] == [(False, ())]
+
+
+def test_mlx_lm_resolves_these_families_only_after_the_remap():
+ # Read from mlx-lm itself rather than restated here, so the catalog cannot drift
+ # back onto a rule that lives in someone else's release cadence.
+ from importlib.util import find_spec
+ mlx_lm_utils = pytest.importorskip("mlx_lm.utils")
+ for model_type in _REMAPPED_MLX_FAMILIES:
+ remapped = mlx_lm_utils.MODEL_REMAPPING.get(model_type)
+ assert remapped, model_type
+ assert find_spec(f"mlx_lm.models.{model_type}") is None, model_type
+ assert find_spec(f"mlx_lm.models.{remapped}") is not None, model_type
+
+
+def test_auto_switch_loads_an_unloaded_mlx_model(monkeypatch):
+ # The other half of #8748: the switch must load it through the orchestrator.
+ llama = _FakeBackend(None)
+
+ class _FakeOrchestrator:
+ active_model_name = None
+ models: dict = {}
+
+ orchestrator = _FakeOrchestrator()
+ calls = []
+
+ async def _load(request, *args, **kwargs):
+ calls.append(request)
+ orchestrator.active_model_name = request.model_path
+ return None
+
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/srv/models/Qwen3-MLX", None, "unsloth/Qwen3-MLX"),
+ backend = llama,
+ recorder = _load,
+ )
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: orchestrator)
+ entry = resolver._LocalGgufEntry(
+ "unsloth/Qwen3-MLX", "/srv/models/Qwen3-MLX", (), is_gguf = False
+ )
+ monkeypatch.setattr(resolver, "_scan", (time.monotonic(), {"unsloth/qwen3-mlx": entry}))
+
+ _run_hook("unsloth/Qwen3-MLX")
+
+ assert [c.model_path for c in calls] == ["/srv/models/Qwen3-MLX"]
+ assert calls[0].gguf_variant is None
+ # The alias lands on the orchestrator, leaving the llama.cpp backend untouched.
+ assert orchestrator._openai_advertised_id == "unsloth/Qwen3-MLX"
+ assert getattr(llama, "_openai_advertised_id", None) is None
+ assert inference_route._openai_model_objects()[0]["id"] == "unsloth/Qwen3-MLX"
+
+
+def test_auto_switch_does_not_reload_a_resident_mlx_model(monkeypatch):
+ # Either guard alone stops the reload, so both are asserted directly as well.
+ llama = _FakeBackend(None)
+
+ class _FakeOrchestrator:
+ active_model_name = "/srv/models/Qwen3-MLX"
+ models: dict = {}
+ _openai_advertised_id = "unsloth/Qwen3-MLX"
+
+ calls = []
+
+ async def _load(request, *args, **kwargs):
+ calls.append(request)
+ return None
+
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/srv/models/Qwen3-MLX", None, "unsloth/Qwen3-MLX"),
+ backend = llama,
+ recorder = _load,
+ )
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _FakeOrchestrator())
+ entry = resolver._LocalGgufEntry(
+ "unsloth/Qwen3-MLX", "/srv/models/Qwen3-MLX", (), is_gguf = False
+ )
+ monkeypatch.setattr(resolver, "_scan", (time.monotonic(), {"unsloth/qwen3-mlx": entry}))
+
+ assert inference_route._loaded_satisfies("unsloth/Qwen3-MLX") is True
+ assert inference_route._loaded_identity_satisfies("unsloth/Qwen3-MLX") is True
+ _run_hook("unsloth/Qwen3-MLX")
+ assert calls == []
+
+
+def test_a_resident_mlx_alias_counts_as_a_namespaced_identity(monkeypatch):
+ # Without the alias this reads a bare basename, so an unknown org/model would be
+ # answered by the resident MLX model instead of refused.
+ class _FakeOrchestrator:
+ active_model_name = "/srv/models/Qwen3-MLX"
+ _openai_advertised_id = "unsloth/Qwen3-MLX"
+
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _FakeBackend(None))
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _FakeOrchestrator())
+ assert inference_route._resident_id_is_namespaced() is True
+
+
+def test_a_gguf_only_endpoint_refuses_a_non_gguf_target_before_loading(monkeypatch):
+ # Codex P1: /v1/completions, /v1/embeddings and the Anthropic routes read llama.cpp
+ # alone, and loading a non-GGUF model unloads the resident GGUF, so an unguarded
+ # switch left them with nothing to serve and a 503.
+ llama = _FakeBackend("org/A-GGUF", hf_variant = "Q4_K_M")
+
+ class _FakeOrchestrator:
+ active_model_name = None
+ models: dict = {}
+
+ calls = []
+
+ async def _load(request, *args, **kwargs):
+ calls.append(request)
+ return None
+
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/srv/models/Qwen3-MLX", None, "unsloth/Qwen3-MLX"),
+ backend = llama,
+ recorder = _load,
+ )
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _FakeOrchestrator())
+ entry = resolver._LocalGgufEntry(
+ "unsloth/Qwen3-MLX", "/srv/models/Qwen3-MLX", (), is_gguf = False
+ )
+ monkeypatch.setattr(resolver, "_scan", (time.monotonic(), {"unsloth/qwen3-mlx": entry}))
+
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(
+ inference_route._maybe_auto_switch_model(
+ "unsloth/Qwen3-MLX", object(), "tester", gguf_only = True
+ )
+ )
+ assert excinfo.value.status_code == 400
+ assert calls == [], "the resident GGUF was unloaded for a swap the endpoint cannot use"
+ assert llama.is_loaded is True
+
+
+def test_two_scan_roots_sharing_a_basename_do_not_answer_for_each_other(monkeypatch):
+ """A scanned directory with no repo alias is advertised under its basename, so
+ /root1/model and /root2/model both advertise "model". Accepting that shared alias as
+ proof of residency answered an explicit request for the second path with the first
+ path's weights, defeating the exact filesystem keys _build_index deliberately holds."""
+ llama = _FakeBackend("org/A-GGUF")
+ llama.is_loaded = False
+
+ class _FakeOrchestrator:
+ active_model_name = "/root1/model"
+ models = {"/root1/model": object()}
+ _openai_advertised_id = "model"
+
+ orchestrator = _FakeOrchestrator()
+ calls = []
+
+ async def _load(request, *args, **kwargs):
+ calls.append(request)
+ orchestrator.active_model_name = "/root2/model"
+ return None
+
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/root2/model", None, "model"),
+ backend = llama,
+ recorder = _load,
+ )
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(inference_route, "_peek_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(inference_route, "_reject_unservable_model", _noop_reject)
+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_kw: False)
+
+ asyncio.run(inference_route._maybe_auto_switch_model("/root2/model", object(), "tester"))
+ assert [getattr(c, "model_path", None) for c in calls] == [
+ "/root2/model"
+ ], "the request named the second path and was answered by the first model"
+
+
+def test_the_resident_path_still_short_circuits_its_own_request(monkeypatch):
+ # the guard above must not cost a reload when the request names the resident path.
+ llama = _FakeBackend("org/A-GGUF")
+ llama.is_loaded = False
+
+ class _FakeOrchestrator:
+ active_model_name = "/root1/model"
+ models = {"/root1/model": object()}
+ _openai_advertised_id = "model"
+
+ orchestrator = _FakeOrchestrator()
+ calls = []
+
+ async def _load(request, *args, **kwargs):
+ calls.append(request)
+ return None
+
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/root1/model", None, "model"),
+ backend = llama,
+ recorder = _load,
+ )
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(inference_route, "_peek_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(inference_route, "_reject_unservable_model", _noop_reject)
+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_kw: False)
+
+ asyncio.run(inference_route._maybe_auto_switch_model("/root1/model", object(), "tester"))
+ assert calls == []
+
+
+def test_a_repo_id_resident_still_matches_a_path_request_through_the_alias(monkeypatch):
+ # a repo-id resident is not a path, so the alias arm still answers a path request
+ # naming the same model rather than reloading it.
+ llama = _FakeBackend("org/A-GGUF")
+ llama.is_loaded = False
+
+ class _FakeOrchestrator:
+ active_model_name = "mlx-community/Qwen3-8B-4bit"
+ models = {"mlx-community/Qwen3-8B-4bit": object()}
+ _openai_advertised_id = None
+
+ orchestrator = _FakeOrchestrator()
+ calls = []
+
+ async def _load(request, *args, **kwargs):
+ calls.append(request)
+ return None
+
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/cache/snapshots/abc", None, "mlx-community/Qwen3-8B-4bit"),
+ backend = llama,
+ recorder = _load,
+ )
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(inference_route, "_peek_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(inference_route, "_reject_unservable_model", _noop_reject)
+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_kw: False)
+
+ asyncio.run(
+ inference_route._maybe_auto_switch_model("/cache/snapshots/abc", object(), "tester")
+ )
+ assert calls == []
+
+
+def test_an_audio_request_probes_audio_capability_on_a_non_gguf_target(monkeypatch):
+ # Codex P2: audio rides a companion mmproj only for a GGUF. Probing vision on a
+ # safetensors Whisper rejected a model the non-GGUF chat branch can serve.
+ seen = {}
+
+ monkeypatch.setattr(
+ inference_route,
+ "_target_is_vision",
+ lambda path, *_a: seen.setdefault("vision", path) and False,
+ )
+ monkeypatch.setattr(
+ inference_route,
+ "_target_accepts_audio_input",
+ lambda path: seen.setdefault("audio", path) or True,
+ )
+ assert (
+ inference_route._target_accepts_request_input("/srv/models/Whisper", False, False, True)
+ is True
+ )
+ assert "vision" not in seen
+ # A GGUF still answers both from the one mmproj probe.
+ inference_route._target_accepts_request_input("/srv/models/A.gguf", True, False, True)
+ assert seen.get("vision") == "/srv/models/A.gguf"
+
+
+def test_a_custom_code_checkpoint_is_not_switchable(tmp_path):
+ # Codex P2: an auto_map repo needs trust_remote_code plus the subject's approval
+ # fingerprint, and a switch carries neither, so advertising it guarantees a load
+ # that fails after evicting the resident model.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "CustomCode")
+ (path / "config.json").write_text(
+ '{"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3", "auto_map": {"AutoModel": "modeling.MyModel"}}'
+ )
+ info = SimpleNamespace(id = str(path), path = str(path))
+ assert resolver.local_servable_model(info) is None
+
+
+def test_an_embedding_checkpoint_is_not_switchable(tmp_path):
+ # Codex P2: only the generative chat path consumes non-GGUF entries, and
+ # /v1/embeddings is GGUF-only, so a SentenceTransformer would be loaded as a
+ # language model and fail after the swap evicted the resident model.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "bge-small")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ assert resolver.local_servable_model(info) is not None
+ (path / "modules.json").write_text("[]")
+ assert resolver.local_servable_model(info) is None
+
+
+def test_streaming_responses_refuses_a_non_gguf_swap(monkeypatch):
+ # Codex P1: _responses_stream reads llama.cpp alone, so a streaming Responses
+ # request naming a non-GGUF model unloaded the resident GGUF and then 400'd.
+ captured = {}
+
+ async def _capture(model, request, subject, **kwargs):
+ captured.update(kwargs)
+ raise RuntimeError("reached the switch")
+
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _capture)
+ for streaming in (True, False):
+ captured.clear()
+ payload = _responses_payload(stream = streaming)
+ with pytest.raises(RuntimeError):
+ asyncio.run(inference_route.openai_responses(payload, object(), "tester"))
+ assert captured["gguf_only"] is streaming
+
+
+def test_a_pickle_checkpoint_is_not_switchable(tmp_path):
+ # Codex P2: .bin weights are pickle-backed, so an API request must not be able to
+ # load one without an explicit load action.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "PickleOnly")
+ (path / "model.safetensors").unlink()
+ (path / "pytorch_model.bin").write_bytes(b"x" * 32)
+ info = SimpleNamespace(id = str(path), path = str(path))
+ assert resolver.local_servable_model(info) is None
+
+
+def test_auto_map_in_a_processor_config_is_not_switchable(tmp_path):
+ # Codex P2: trust_remote_code runs auto_map from any of the scanner's config
+ # files, not just config.json, and a switch carries no approval fingerprint.
+ from types import SimpleNamespace
+ from utils.security.remote_code_scan import REMOTE_CODE_CONFIG_FILES
+ for name in REMOTE_CODE_CONFIG_FILES:
+ path = _local_checkpoint(tmp_path, f"custom-{name}")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ assert resolver.local_servable_model(info) is not None
+ blob = '{"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3", "auto_map": {"A": "m.M"}}'
+ (path / name).write_text(blob)
+ assert resolver.local_servable_model(info) is None, name
+
+
+def test_a_non_generative_checkpoint_is_not_switchable(tmp_path):
+ # Codex P2: chat generation is the only route these entries feed, so an
+ # encoder-only or classifier checkpoint would fail in the language-model load.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "bert-base")
+ (path / "config.json").write_text('{"architectures": ["BertForSequenceClassification"]}')
+ info = SimpleNamespace(id = str(path), path = str(path))
+ assert resolver.local_servable_model(info) is None
+
+
+def test_a_lora_directory_with_a_copied_config_is_not_switchable(tmp_path):
+ # Codex P2: ModelConfig resolves an adapter's base_model_name_or_path, so the
+ # switch could fetch weights this resolver promises never to download.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "SomeLoRA")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ assert resolver.local_servable_model(info) is not None
+ (path / "adapter_config.json").write_text("{}")
+ assert resolver.local_servable_model(info) is None
+
+
+def test_an_audio_only_request_does_not_demand_vision_from_a_non_gguf_target(monkeypatch):
+ # Codex P2: the chat route sets needs_vision for audio so a GGUF is asked for its
+ # projector. Applying that to a non-GGUF target refused the very audio checkpoints
+ # that can serve the request.
+ monkeypatch.setattr(inference_route, "_target_accepts_audio_input", lambda path: True)
+ monkeypatch.setattr(
+ inference_route, "_target_is_vision", lambda *_a: pytest.fail("vision probed")
+ )
+ assert (
+ inference_route._target_accepts_request_input(
+ "/srv/models/Whisper", False, True, True, None, False
+ )
+ is True
+ )
+
+
+def test_a_nested_non_gguf_row_is_not_marked_resident(monkeypatch):
+ # Codex P2: a non-GGUF model loads from its own directory, so a catalog row nested
+ # under the loaded one is different weights and must not read as loaded.
+ class _FakeOrchestrator:
+ active_model_name = "/models/A"
+
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _FakeBackend(None))
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _FakeOrchestrator())
+ assert inference_route._resolves_to_resident("/models/A") is True
+ assert inference_route._resolves_to_resident("/models/A/sub/B") is False
+
+
+def test_a_text_seq2seq_checkpoint_is_not_switchable(tmp_path):
+ # Codex P2: ForConditionalGeneration is overloaded. T5 and BART wear it, and the
+ # serving path has no seq2seq branch, so only a multimodal sub-config qualifies.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "t5-base")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ (path / "config.json").write_text(
+ '{"architectures": ["T5ForConditionalGeneration"], "model_type": "t5"}'
+ )
+ assert resolver.local_servable_model(info) is None
+ (path / "config.json").write_text(
+ '{"architectures": ["Gemma3ForConditionalGeneration"], "model_type": "gemma3", "vision_config": {}}'
+ )
+ assert resolver.local_servable_model(info) == (False, ())
+
+
+def test_a_whisper_checkpoint_is_switchable(tmp_path):
+ """Whisper wears ForConditionalGeneration and carries no multimodal sub-config, being
+ the audio model rather than wearing one, so requiring that key filtered it out with T5.
+ The orchestrator loads it through WhisperForConditionalGeneration and chat routes the
+ request to generate_whisper_response, so it is a target this server actually serves."""
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "whisper-large-v3")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ (path / "config.json").write_text(
+ '{"architectures": ["WhisperForConditionalGeneration"], "model_type": "whisper"}'
+ )
+ assert resolver.local_servable_model(info) == (False, ())
+ assert resolver._model_type_is_audio("whisper") is True
+ assert resolver._model_type_is_audio("csm") is True
+ assert resolver._model_type_is_audio("t5") is False
+ assert resolver._model_type_is_audio(None) is False
+
+
+ ("architecture", "model_type"),
+ [
+ ("Speech2TextForConditionalGeneration", "speech_to_text"),
+ ("MusicgenForConditionalGeneration", "musicgen"),
+ ],
+)
+def test_unsupported_conditional_audio_checkpoints_are_not_switchable(
+ tmp_path, architecture, model_type
+):
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, model_type)
+ info = SimpleNamespace(id = str(path), path = str(path))
+ (path / "config.json").write_text(
+ json.dumps({"architectures": [architecture], "model_type": model_type})
+ )
+ assert resolver.local_servable_model(info) is None
+
+
+def test_an_mlx_host_does_not_advertise_an_asr_checkpoint(tmp_path, monkeypatch):
+ """The MLX worker refuses ASR outright at worker.py:823 and TTS at 1103, so a Whisper
+ checkpoint on Apple Silicon can only be loaded to fail. Same host-capability rule as
+ _host_has_a_non_gguf_backend, not a prediction about the load."""
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "whisper-large-v3")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ (path / "config.json").write_text(
+ '{"architectures": ["WhisperForConditionalGeneration"], "model_type": "whisper"}'
+ )
+ monkeypatch.setattr(resolver, "_host_serves_mlx", lambda: True)
+ assert resolver.local_servable_model(info) is None
+ # an audio VLM declares a multimodal sub-config, which MLX does serve, so it stays listed.
+ (path / "config.json").write_text(
+ '{"architectures": ["Gemma3nForConditionalGeneration"], "model_type": "gemma3n",'
+ ' "audio_config": {}}'
+ )
+ assert resolver.local_servable_model(info) == (False, ())
+
+
+def test_an_empty_auto_map_is_not_remote_code(tmp_path):
+ """The consent gate reads auto_map for truthiness (_config_has_auto_map in
+ utils/security/consent.py), so an empty or null mapping names no implementation and
+ executes nothing. Rejecting on the key's presence alone hid a loadable checkpoint
+ while adding no approval boundary."""
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "EmptyAutoMap")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ base = '{"architectures": ["Qwen3ForCausalLM"], "model_type": "qwen3", "auto_map": %s}'
+ for empty in ("{}", "null"):
+ (path / "config.json").write_text(base % empty)
+ assert resolver.local_servable_model(info) == (False, ()), empty
+ # a mapping that does name an implementation is still refused without approval.
+ (path / "config.json").write_text(base % '{"AutoModel": "modeling.MyModel"}')
+ assert resolver.local_servable_model(info) is None
+
+
+def test_a_host_without_a_non_gguf_backend_advertises_none(tmp_path, monkeypatch):
+ # Codex P2: with neither torch nor MLX the worker has nothing to load safetensors
+ # with, and _load_model_impl unloads the resident GGUF before that fails.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "NoBackend")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ monkeypatch.setattr(resolver, "_host_has_a_non_gguf_backend", lambda: False)
+ assert resolver.local_servable_model(info) is None
+
+
+def test_a_nested_row_is_not_resident_against_a_loaded_gguf_directory(monkeypatch):
+ # Codex P2: llama.cpp loading out of /models/A must not mark the separately
+ # cataloged /models/A/sub/B resident through the directory prefix rule.
+ llama = _FakeBackend("/models/A")
+ llama.gguf_path = "/models/A"
+
+ class _FakeOrchestrator:
+ active_model_name = None
+
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: llama)
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _FakeOrchestrator())
+ assert inference_route._resolves_to_resident("/models/A/sub/B", exact_only = True) is False
+ assert inference_route._resolves_to_resident("/models/A", exact_only = True) is True
+
+
+def test_a_non_canonical_safetensors_name_is_not_switchable(tmp_path):
+ # Codex P2: the loader receives no variant, so model.fp16.safetensors or a stray
+ # optimizer.safetensors is not weights it can open.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "VariantOnly")
+ (path / "model.safetensors").rename(path / "model.fp16.safetensors")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ assert resolver.local_servable_model(info) is None
+
+
+def test_a_causal_model_without_the_suffix_stays_switchable(tmp_path):
+ # the loader selects GPT2LMHeadModel too, so requiring ForCausalLM alone hid working models.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "gpt2")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ (path / "config.json").write_text(
+ '{"architectures": ["GPT2LMHeadModel"], "model_type": "gpt2"}'
+ )
+ assert resolver.local_servable_model(info) == (False, ())
+
+
+def test_a_model_type_without_architectures_is_not_switchable(tmp_path):
+ # the causal mapping holds bert and bart, so model_type alone stays withheld either way.
+ from types import SimpleNamespace
+
+ path = _local_checkpoint(tmp_path, "no-arch")
+ info = SimpleNamespace(id = str(path), path = str(path))
+ for model_type in ("t5", "deberta-v2", "qwen3"):
+ (path / "config.json").write_text(json.dumps({"model_type": model_type}))
+ assert resolver.local_servable_model(info) is None, model_type
+
+ import transformers # noqa: F401
+
+ for model_type in ("t5", "deberta-v2", "qwen3"):
+ (path / "config.json").write_text(json.dumps({"model_type": model_type}))
+ assert resolver.local_servable_model(info) is None, model_type
+
+
+def test_the_advertised_alias_is_cleared_before_a_replacement_load(tmp_path):
+ # Codex P1: load_model publishes active_model_name for the new weights, so an alias
+ # cleared afterwards leaves a window where a request for the old model matches it
+ # and is answered by the new ones. The clear must precede the load call.
+ import inspect
+
+ src = inspect.getsource(inference_route._load_model_impl)
+ # Anchored on the line start: llama_backend.load_model appears earlier and would
+ # otherwise match as a substring of the orchestrator call this guards.
+ clear = src.index("\n backend._openai_advertised_id = None")
+ load = src.index("\n backend.load_model,")
+ assert clear < load, "the alias must be cleared before load_model publishes the new model"
+
+
+def test_a_failed_replacement_keeps_the_surviving_model_advertised():
+ """A repair raises SidecarSwapInProgress before the old worker is torn down, so the
+ orchestrator keeps active_model_name and that model goes on serving. The alias was
+ already cleared for the load that never happened, so without restoring it the still
+ resident model loses the id /v1/models and response ids report it under."""
+
+ class _Orchestrator:
+ def __init__(self, active):
+ self.active_model_name = active
+ self._openai_advertised_id = None
+
+ # the load raised but the previous model survived, so its alias comes back.
+ survived = _Orchestrator("/srv/models/Qwen3-8B-MLX")
+ inference_route._restore_alias_if_failed_load_left_the_prior_model(
+ survived, "mlx-community/Qwen3-8B-4bit", "/srv/models/Qwen3-8B-MLX"
+ )
+ assert survived._openai_advertised_id == "mlx-community/Qwen3-8B-4bit"
+
+ # a real failure clears active_model_name, so nothing is resident to advertise.
+ torn_down = _Orchestrator(None)
+ inference_route._restore_alias_if_failed_load_left_the_prior_model(
+ torn_down, "mlx-community/Qwen3-8B-4bit", "/srv/models/Qwen3-8B-MLX"
+ )
+ assert torn_down._openai_advertised_id is None
+
+ # a different model is resident, so the old alias must not be pinned onto it.
+ replaced = _Orchestrator("/srv/models/Other")
+ inference_route._restore_alias_if_failed_load_left_the_prior_model(
+ replaced, "mlx-community/Qwen3-8B-4bit", "/srv/models/Qwen3-8B-MLX"
+ )
+ assert replaced._openai_advertised_id is None
+
+ # nothing was loaded before the attempt, so there is no alias to put back.
+ cold = _Orchestrator(None)
+ inference_route._restore_alias_if_failed_load_left_the_prior_model(cold, None, None)
+ assert cold._openai_advertised_id is None
+
+
+def test_both_failed_load_exits_restore_the_alias():
+ # the raise and the falsy-success exit are separate paths; a fix on one alone leaks.
+ import inspect
+
+ src = inspect.getsource(inference_route._load_model_impl)
+ assert src.count("_restore_alias_if_failed_load_left_the_prior_model(") == 2
+ clear = src.index("\n backend._openai_advertised_id = None")
+ assert src.index("_restore_alias_if_failed_load_left_the_prior_model(") > clear
+ # the second call sits on the falsy-success exit, past the raise the first one guards.
+ assert (
+ src.index("_restore_alias_if_failed_load_left_the_prior_model(", clear)
+ < src.index("\n if not success:")
+ < src.rindex("_restore_alias_if_failed_load_left_the_prior_model(")
+ )
+
+
+def test_a_stale_alias_after_unload_is_not_a_resident_identity(monkeypatch):
+ # Codex P2: the alias outlives an unload, so reading it ungated made an unrelated
+ # org/model request look like a mismatch against a model that is no longer loaded.
+ class _FakeOrchestrator:
+ active_model_name = None
+ _openai_advertised_id = "unsloth/Qwen3-MLX"
+
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _FakeBackend(None))
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _FakeOrchestrator())
+ assert inference_route._resident_id_is_namespaced() is False
+
+
+def test_the_audio_preflight_only_binds_a_non_gguf_target(monkeypatch):
+ import base64 as _b64
+ import io
+ import wave
+
+ # _prepare_audio_for_llama takes a data: URI and a continuation.
+ from fastapi import HTTPException
+
+ monkeypatch.setattr(
+ inference_route,
+ "_decode_audio_base64",
+ lambda _b64: pytest.fail("the non-GGUF decoder ran for a GGUF target"),
+ )
+ monkeypatch.setattr(inference_route, "_audio_decoder_is_available", lambda: False)
+ wav = io.BytesIO()
+ with wave.open(wav, "wb") as audio:
+ audio.setnchannels(1)
+ audio.setsampwidth(2)
+ audio.setframerate(16000)
+ audio.writeframes(b"\x00\x00" * 16)
+ preflight = {
+ "b64": f"data:audio/wav;base64,{_b64.b64encode(wav.getvalue()).decode()}",
+ "continue_final": True,
+ }
+ asyncio.run(inference_route._preflight_audio_for_switch(preflight, True))
+ assert preflight["prepared"][1] == "wav"
+ assert "decoded" not in preflight
+
+ # the non-GGUF branch runs _decode_audio_base64, so it refuses the same input, before the load.
+ monkeypatch.setattr(inference_route, "_audio_decoder_is_available", lambda: True)
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(inference_route._preflight_audio_for_switch(dict(preflight), False))
+ assert exc.value.status_code == 400
+ assert "continue_final_message" in exc.value.detail
+ assert "audio input" in exc.value.detail
+
+
+def test_a_prior_turn_image_does_not_block_a_non_gguf_audio_switch(monkeypatch):
+ llama = _FakeBackend("org/A-GGUF")
+
+ class _FakeOrchestrator:
+ active_model_name = None
+ models: dict = {}
+
+ orchestrator = _FakeOrchestrator()
+ calls = []
+
+ async def _load(request, *_args, **_kwargs):
+ calls.append(request)
+ orchestrator.active_model_name = request.model_path
+
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/srv/models/Whisper", None, "org/Whisper"),
+ backend = llama,
+ recorder = _load,
+ )
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(inference_route, "_peek_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_kw: False)
+ monkeypatch.setattr(inference_route, "_target_accepts_audio_input", lambda _path: True)
+ monkeypatch.setattr(
+ inference_route,
+ "_target_is_vision",
+ lambda *_a, **_kw: pytest.fail("a prior-turn image demanded vision"),
+ )
+ monkeypatch.setattr(inference_route, "_audio_decoder_is_available", lambda: True)
+ monkeypatch.setattr(inference_route, "_decode_audio_base64", lambda _b64: "pcm")
+
+ asyncio.run(
+ inference_route._maybe_auto_switch_model(
+ "org/Whisper",
+ object(),
+ "tester",
+ require_vision = True,
+ require_image = True,
+ require_audio_input = True,
+ audio_preflight = {
+ "b64": "valid",
+ "continue_final": False,
+ "has_image": False,
+ },
+ )
+ )
+
+ assert [request.model_path for request in calls] == ["/srv/models/Whisper"]
+ assert orchestrator._openai_advertised_id == "org/Whisper"
+
+
+ "image_preflight",
+ [
+ {"b64": "bm90IGFuIGltYWdl", "multiple": False},
+ "truncated image",
+ {"b64": None, "multiple": True},
+ ],
+ ids = ["malformed bytes", "truncated image", "multiple images"],
+)
+def test_invalid_non_gguf_images_are_rejected_before_switch(monkeypatch, image_preflight):
+ if image_preflight == "truncated image":
+ import base64 as _b64
+ import io
+ from PIL import Image
+
+ encoded = io.BytesIO()
+ Image.new("RGB", (8, 8), "red").save(encoded, format = "JPEG")
+ image_preflight = {
+ "b64": _b64.b64encode(encoded.getvalue()[:-1]).decode(),
+ "multiple": False,
+ }
+ llama = _FakeBackend("org/A-GGUF")
+
+ class _FakeOrchestrator:
+ active_model_name = None
+ models: dict = {}
+
+ orchestrator = _FakeOrchestrator()
+ calls = []
+
+ async def _load(request, *_args, **_kwargs):
+ calls.append(request)
+ orchestrator.active_model_name = request.model_path
+
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/srv/models/Vision", None, "org/Vision"),
+ backend = llama,
+ recorder = _load,
+ )
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(inference_route, "_peek_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_kw: False)
+ monkeypatch.setattr(inference_route, "_target_accepts_request_input", lambda *_a: True)
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route._maybe_auto_switch_model(
+ "org/Vision",
+ object(),
+ "tester",
+ require_vision = True,
+ image_preflight = image_preflight,
+ )
+ )
+
+ assert exc.value.status_code == 400
+ assert calls == []
+ assert llama.model_identifier == "org/A-GGUF"
+
+
+def test_a_malformed_gguf_image_is_rejected_before_switch(monkeypatch):
+ llama = _FakeBackend("org/A-GGUF")
+ recorder = _LoadRecorder(llama)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/srv/models/B.gguf", "Q4_K_M", "org/B-GGUF"),
+ backend = llama,
+ recorder = recorder,
+ )
+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_kw: True)
+ monkeypatch.setattr(inference_route, "_target_accepts_request_input", lambda *_a: True)
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route._maybe_auto_switch_model(
+ "org/B-GGUF",
+ object(),
+ "tester",
+ require_vision = True,
+ image_preflight = {
+ "b64": "bm90IGFuIGltYWdl",
+ "b64s": ["bm90IGFuIGltYWdl"],
+ "multiple": False,
+ },
+ )
+ )
+
+ assert exc.value.status_code == 400
+ assert exc.value.detail == "Failed to process image."
+ assert recorder.calls == []
+ assert llama.model_identifier == "org/A-GGUF"
+
+
+def test_gguf_image_preflight_allows_multiple_valid_images():
+ import base64 as _b64
+ import io
+ from PIL import Image
+
+ encoded = io.BytesIO()
+ Image.new("RGB", (8, 8), "red").save(encoded, format = "PNG")
+ image_b64 = _b64.b64encode(encoded.getvalue()).decode()
+
+ asyncio.run(
+ inference_route._preflight_image_for_switch(
+ {"b64s": [image_b64, image_b64], "multiple": True},
+ True,
+ )
+ )
+
+
+def test_the_image_preflight_collects_every_local_request_image():
+ from models.inference import ChatMessage, ImageContentPart, ImageUrl
+ payload = _chat_request(
+ image_base64 = "legacy",
+ messages = [
+ ChatMessage(
+ role = "user",
+ content = [
+ ImageContentPart(
+ type = "image_url",
+ image_url = ImageUrl(url = "data:image/png;base64,first"),
+ ),
+ ImageContentPart(
+ type = "image_url",
+ image_url = ImageUrl(url = "https://example.com/remote.png"),
+ ),
+ ImageContentPart(
+ type = "image_url",
+ image_url = ImageUrl(url = "data:image/png;base64,second"),
+ ),
+ ],
+ )
+ ],
+ )
+
+ assert inference_route._request_local_image_payloads(payload) == [
+ "first",
+ "second",
+ "legacy",
+ ]
+
+
+def _wire_image_switch_target(monkeypatch, *, target_is_gguf):
+ backend = _FakeBackend("org/A-GGUF")
+ recorder = _LoadRecorder(backend)
+ target_path = "/srv/models/B.gguf" if target_is_gguf else "/srv/models/B"
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = (target_path, None, "org/B-GGUF"),
+ backend = backend,
+ recorder = recorder,
+ )
+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_kw: target_is_gguf)
+ monkeypatch.setattr(inference_route, "_target_accepts_request_input", lambda *_a: True)
+ if not target_is_gguf:
+ orchestrator = types.SimpleNamespace(active_model_name = None, models = {})
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: orchestrator)
+ monkeypatch.setattr(inference_route, "_peek_inference_backend", lambda: orchestrator)
+ return backend, recorder
+
+
+ ("url", "detail"),
+ [
+ ("data:image/png;base64,", "Failed to decode image"),
+ (
+ "https://example.com/image.png",
+ "Remote image URLs are not supported. Use a base64 data URL.",
+ ),
+ ],
+ ids = ["empty data url", "remote url"],
+)
+def test_chat_rejects_unsupported_openai_images_before_non_gguf_switch(monkeypatch, url, detail):
+ from models.inference import ChatMessage, ImageContentPart, ImageUrl
+
+ backend, recorder = _wire_image_switch_target(monkeypatch, target_is_gguf = False)
+ payload = _chat_request(
+ model = "org/B-GGUF",
+ messages = [
+ ChatMessage(
+ role = "user",
+ content = [
+ ImageContentPart(
+ type = "image_url",
+ image_url = ImageUrl(url = url),
+ )
+ ],
+ )
+ ],
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(inference_route.openai_chat_completions(payload, object(), "tester"))
+
+ assert exc.value.status_code == 400
+ assert exc.value.detail == detail
+ assert recorder.calls == []
+ assert backend.model_identifier == "org/A-GGUF"
+
+
+def _responses_image_payload(*images, stream):
+ from models.inference import ResponsesRequest
+ return ResponsesRequest(
+ model = "org/B-GGUF",
+ stream = stream,
+ input = [
+ {
+ "type": "message",
+ "role": "user",
+ "content": [
+ {
+ "type": "input_image",
+ "image_url": f"data:image/png;base64,{image}",
+ }
+ for image in images
+ ],
+ }
+ ],
+ )
+
+
+def test_streaming_responses_rejects_a_malformed_gguf_image_before_switch(monkeypatch):
+ backend, recorder = _wire_image_switch_target(monkeypatch, target_is_gguf = True)
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route.openai_responses(
+ _responses_image_payload("bm90IGFuIGltYWdl", stream = True),
+ object(),
+ "tester",
+ )
+ )
+
+ assert exc.value.status_code == 400
+ assert exc.value.detail == "Failed to process image."
+ assert recorder.calls == []
+ assert backend.model_identifier == "org/A-GGUF"
+
+
+def test_nonstreaming_responses_defers_multiple_image_preflight_to_chat(monkeypatch):
+ backend, recorder = _wire_image_switch_target(monkeypatch, target_is_gguf = False)
+ request = types.SimpleNamespace(
+ state = types.SimpleNamespace(skip_api_monitor = True),
+ url = types.SimpleNamespace(path = "/v1/responses"),
+ method = "POST",
+ scope = {},
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route.openai_responses(
+ _responses_image_payload("first", "second", stream = False),
+ request,
+ "tester",
+ )
+ )
+
+ assert exc.value.status_code == 400
+ assert "one image per message" in exc.value.detail
+ assert recorder.calls == []
+ assert backend.model_identifier == "org/A-GGUF"
+
+
+def test_nonstreaming_responses_defers_malformed_gguf_preflight_to_chat(monkeypatch):
+ backend, recorder = _wire_image_switch_target(monkeypatch, target_is_gguf = True)
+ request = types.SimpleNamespace(
+ state = types.SimpleNamespace(skip_api_monitor = True),
+ url = types.SimpleNamespace(path = "/v1/responses"),
+ method = "POST",
+ scope = {},
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route.openai_responses(
+ _responses_image_payload("bm90IGFuIGltYWdl", stream = False),
+ request,
+ "tester",
+ )
+ )
+
+ assert exc.value.status_code == 400
+ assert exc.value.detail == "Failed to process image."
+ assert recorder.calls == []
+ assert backend.model_identifier == "org/A-GGUF"
+
+
+ "source",
+ [
+ {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "bm90IGFuIGltYWdl",
+ },
+ {
+ "type": "url",
+ "url": "data:image/png;base64,bm90IGFuIGltYWdl",
+ },
+ {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "",
+ },
+ ],
+ ids = ["base64 source", "data url source", "empty base64 source"],
+)
+def test_anthropic_rejects_a_malformed_gguf_image_before_switch(monkeypatch, source):
+ from models.inference import AnthropicMessage, AnthropicMessagesRequest
+
+ backend, recorder = _wire_image_switch_target(monkeypatch, target_is_gguf = True)
+ payload = AnthropicMessagesRequest(
+ model = "org/B-GGUF",
+ max_tokens = 16,
+ messages = [
+ AnthropicMessage(
+ role = "user",
+ content = [
+ {
+ "type": "image",
+ "source": source,
+ }
+ ],
+ )
+ ],
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(inference_route.anthropic_messages(payload, object(), "tester"))
+
+ assert exc.value.status_code == 400
+ assert exc.value.detail == "Failed to process image."
+ assert recorder.calls == []
+ assert backend.model_identifier == "org/A-GGUF"
+
+
+def test_mixed_audio_and_image_is_rejected_before_a_non_gguf_switch(monkeypatch):
+ llama = _FakeBackend("org/A-GGUF")
+
+ class _FakeOrchestrator:
+ active_model_name = None
+ models: dict = {}
+
+ recorder = _LoadRecorder(llama)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/srv/models/Audio-VLM", None, "org/Audio-VLM"),
+ backend = llama,
+ recorder = recorder,
+ )
+ monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _FakeOrchestrator())
+ monkeypatch.setattr(inference_route, "_peek_inference_backend", lambda: _FakeOrchestrator())
+ monkeypatch.setattr(resolver, "local_target_is_gguf", lambda *_a, **_kw: False)
+ monkeypatch.setattr(inference_route, "_target_accepts_request_input", lambda *_a: True)
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route._maybe_auto_switch_model(
+ "org/Audio-VLM",
+ object(),
+ "tester",
+ require_vision = True,
+ require_image = True,
+ require_audio_input = True,
+ audio_preflight = {
+ "b64": "AAAA",
+ "continue_final": False,
+ "has_image": True,
+ },
+ )
+ )
+
+ assert exc.value.status_code == 400
+ assert exc.value.detail == inference_route._AUDIO_IMAGE_INPUT_DETAIL
+ assert recorder.calls == []
+ assert llama.is_loaded is True
+
+
+def test_the_gguf_audio_preflight_takes_the_base64_llama_cpp_takes():
+ """The preflight must refuse exactly what _prepare_audio_for_llama refuses.
+
+ That helper decodes with the lenient default, which drops whitespace, so a
+ validate = True preflight 400'd MIME-wrapped and newline-padded uploads the same
+ server served before the preflight existed."""
+ import base64 as _b64
+ import io
+ import wave
+
+ from fastapi import HTTPException
+
+ wav = io.BytesIO()
+ with wave.open(wav, "wb") as audio:
+ audio.setnchannels(1)
+ audio.setsampwidth(2)
+ audio.setframerate(16000)
+ audio.writeframes(b"\x00\x00" * 16)
+ payload = wav.getvalue()
+ plain = _b64.b64encode(payload).decode()
+ for name, encoded in (
+ ("plain", plain),
+ ("trailing newline", plain + "\n"),
+ ("surrounding spaces", f" {plain} "),
+ ("mime wrapped", _b64.encodebytes(payload).decode()),
+ ("data uri", f"data:audio/wav;base64,{plain}"),
+ ):
+ try:
+ asyncio.run(
+ inference_route._preflight_audio_for_switch(
+ {"b64": encoded, "continue_final": False}, True
+ )
+ )
+ except HTTPException:
+ pytest.fail(f"the preflight refused {name} base64 that llama.cpp decodes")
+ # undecodable input is still a 400, so dropping validate = True did not open the gate.
+ for bad in ("abc", "!!!!", "AA!!AA==", " ", "data:audio/wav;base64", "\n\n"):
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route._preflight_audio_for_switch(
+ {"b64": bad, "continue_final": False}, True
+ )
+ )
+ assert exc.value.status_code == 400, bad
+
+
+def test_non_audio_bytes_are_rejected_before_a_gguf_switch(monkeypatch):
+ import base64 as _b64
+
+ llama = _FakeBackend("org/A-GGUF")
+ recorder = _LoadRecorder(llama)
+ _wire(
+ monkeypatch,
+ enabled = True,
+ resolves_to = ("/srv/models/B.gguf", "Q4_K_M", "org/B-GGUF"),
+ backend = llama,
+ recorder = recorder,
+ )
+ monkeypatch.setattr(inference_route, "_target_accepts_request_input", lambda *_a: True)
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route._maybe_auto_switch_model(
+ "org/B-GGUF",
+ object(),
+ "tester",
+ require_audio_input = True,
+ audio_preflight = {
+ "b64": _b64.b64encode(b"not audio").decode(),
+ "continue_final": False,
+ },
+ )
+ )
+
+ assert exc.value.status_code == 400
+ assert "decoded as audio" in json.dumps(exc.value.detail)
+ assert recorder.calls == []
+ assert llama.model_identifier == "org/A-GGUF"
+
+
+def test_a_non_gguf_audio_target_is_refused_without_a_decoder(monkeypatch):
+ # on a torch-free host the swap used to unload the resident model, then fail importing torchaudio.
+ from fastapi import HTTPException
+
+ monkeypatch.setattr(inference_route, "_audio_decoder_is_available", lambda: False)
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route._preflight_audio_for_switch(
+ {"b64": "AAAA", "continue_final": False}, False
+ )
+ )
+ assert exc.value.status_code == 400
+ assert "torchaudio" in exc.value.detail["error"]["message"]
+
+
+def test_non_audio_bytes_are_rejected_before_a_non_gguf_switch(monkeypatch):
+ # non-audio bytes are a deterministic 400, and the decoded array is reused downstream.
+ from fastapi import HTTPException
+
+ monkeypatch.setattr(inference_route, "_audio_decoder_is_available", lambda: True)
+
+ def _decode(b64):
+ if b64 != "GOOD":
+ raise ValueError("not audio")
+ return "pcm"
+
+ monkeypatch.setattr(inference_route, "_decode_audio_base64", _decode)
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(
+ inference_route._preflight_audio_for_switch(
+ {"b64": "AAAA", "continue_final": False}, False
+ )
+ )
+ assert exc.value.status_code == 400
+
+ preflight = {"b64": "GOOD", "continue_final": False}
+ asyncio.run(inference_route._preflight_audio_for_switch(preflight, False))
+ assert preflight["decoded"] == "pcm"
+
+
+def test_a_gguf_only_host_does_not_need_torchaudio_to_accept_audio(monkeypatch):
+ # Codex P2: _decode_audio_base64 imports torchaudio, which a GGUF-only install does
+ # not ship, so requiring it in the preflight 400'd valid llama.cpp audio requests.
+ reached = {}
+
+ async def _capture(*_a, **_kw):
+ reached["switch"] = True
+ raise RuntimeError("reached the switch")
+
+ monkeypatch.setattr(settings, "get_openai_auto_switch_enabled", lambda: True)
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _capture)
+ monkeypatch.setattr(inference_route, "_audio_decoder_is_available", lambda: False)
+ monkeypatch.setattr(
+ inference_route,
+ "_decode_audio_base64",
+ lambda _b64: pytest.fail("torchaudio decoder ran on a GGUF-only host"),
+ )
+ payload = _chat_request(model = "org/B-GGUF", audio_base64 = "AAAA")
+ with pytest.raises(RuntimeError):
+ asyncio.run(inference_route.openai_chat_completions(payload, object(), "tester"))
+ assert reached.get("switch")
+
+
+def test_a_host_with_no_accelerator_serves_gguf_only(monkeypatch):
+ # codex P2: unsloth's get_device_type raises without a GPU, so a CPU wheel proves nothing.
+ from utils.hardware import hardware as hw
+
+ monkeypatch.setattr(resolver, "_host_serves_mlx", lambda: False)
+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CPU, raising = False)
+ assert _REAL_HOST_HAS_NON_GGUF_BACKEND() is False
+ monkeypatch.setattr(hw, "DEVICE", hw.DeviceType.CUDA, raising = False)
+ assert _REAL_HOST_HAS_NON_GGUF_BACKEND() is True
+
+
+def test_a_serving_hf_cache_row_is_reported_loaded(tmp_path, monkeypatch):
+ # the scanner lists the models--* dir but the orchestrator records the snapshot it loaded.
+ from types import SimpleNamespace
+
+ repo = tmp_path / "models--org--Chat"
+ snapshot = repo / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ (snapshot / "config.json").write_text(_CHAT_CONFIG)
+ (snapshot / "tokenizer.json").write_text("{}")
+ (snapshot / "tokenizer_config.json").write_text('{"chat_template": "{{ messages }}"}')
+ (snapshot / "model.safetensors").write_bytes(_safetensors_bytes())
+
+ monkeypatch.setattr(
+ inference_route,
+ "get_inference_backend",
+ lambda: SimpleNamespace(active_model_name = str(snapshot), models = {}),
+ )
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _FakeBackend(None))
+ info = SimpleNamespace(id = "org/Chat", model_id = "org/Chat", path = str(repo))
+ rows = inference_route._servable_catalog_rows([info])
+ assert [(is_gguf, quants, resident) for _i, is_gguf, quants, resident in rows] == [
+ (False, (), True)
+ ]
diff --git a/studio/backend/tests/test_openai_catalog.py b/studio/backend/tests/test_openai_catalog.py
index 801d8908cfa..3574302a378 100644
--- a/studio/backend/tests/test_openai_catalog.py
+++ b/studio/backend/tests/test_openai_catalog.py
@@ -59,14 +59,16 @@ def test_catalog_lists_loaded_and_available(monkeypatch):
# HF-cache GGUF: model_format is unset for these, so a files-based check
# (not model_format) must still list it.
_Info("models--org--Foo", "Foo", model_id = "org/Foo"),
- # Non-GGUF (safetensors) can't be served via /v1: must NOT be advertised.
+ # Non-GGUF (safetensors/MLX): the orchestrator serves it, so it is listed too.
_Info("/data/models/Mistral-7B", "Mistral-7B", is_gguf = False),
]
monkeypatch.setattr(inf, "_cached_local_catalog", _fake_catalog)
- # GGUF-ness and the quant labels come from one on-disk scan; drive both off the flag.
+ # Format and the quant labels come from one on-disk scan; drive both off the flag.
monkeypatch.setattr(
- resolver, "local_gguf_quants", lambda info: ("Q8_0",) if info.is_gguf else None
+ resolver,
+ "local_servable_model",
+ lambda info: (True, ("Q8_0",)) if info.is_gguf else (False, ()),
)
data = asyncio.run(inf._openai_catalog_objects())
@@ -80,8 +82,9 @@ def test_catalog_lists_loaded_and_available(monkeypatch):
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
- # The non-GGUF model is filtered out (/v1 can never serve it).
- assert "Mistral-7B" not in ids
+ # The non-GGUF model is listed so an API client can switch to it, with no quant to pin.
+ assert ids["Mistral-7B"]["loaded"] is False
+ assert "quant" not in ids["Mistral-7B"]
# 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.
@@ -91,6 +94,96 @@ def test_catalog_lists_loaded_and_available(monkeypatch):
assert "/data/" not in blob
+def test_a_resident_non_gguf_model_is_marked_loaded_and_stays_quantless(monkeypatch):
+ # llama-only residency lists the model that is serving as unloaded, and the ungated
+ # hf_variant read stamps a stale quant on this row.
+ class _Orchestrator:
+ active_model_name = "/data/models/Mistral-7B"
+ models: dict = {}
+ context_length = None
+ max_seq_length = None
+
+ llama = _FakeLlama(loaded = False)
+ llama.hf_variant = "Q4_K_M"
+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: llama)
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _Orchestrator())
+
+ async def _fake_catalog():
+ return [_Info("/data/models/Mistral-7B", "Mistral-7B", is_gguf = False)]
+
+ monkeypatch.setattr(inf, "_cached_local_catalog", _fake_catalog)
+ monkeypatch.setattr(resolver, "local_servable_model", lambda info: (False, ()))
+ ids = {m["id"]: m for m in asyncio.run(inf._openai_catalog_objects())}
+ assert ids["Mistral-7B"]["loaded"] is True
+ assert "quant" not in ids["Mistral-7B"]
+
+
+def test_a_manually_loaded_non_gguf_model_has_one_catalog_row(monkeypatch):
+ class _Orchestrator:
+ active_model_name = "/srv/lmstudio/mlx-community/Qwen3-8B-4bit"
+ models: dict = {}
+ context_length = 8192
+ max_seq_length = None
+
+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama(loaded = False))
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _Orchestrator())
+
+ info = _Info(
+ "/srv/lmstudio/mlx-community/Qwen3-8B-4bit",
+ "Qwen3-8B-4bit",
+ model_id = "mlx-community/Qwen3-8B-4bit",
+ is_gguf = False,
+ )
+ info.path = info.id
+
+ async def _fake_catalog():
+ return [info]
+
+ monkeypatch.setattr(inf, "_cached_local_catalog", _fake_catalog)
+ monkeypatch.setattr(resolver, "local_servable_model", lambda _info: (False, ()))
+ data = asyncio.run(inf._openai_catalog_objects())
+
+ assert data == [
+ {
+ "id": "Qwen3-8B-4bit",
+ "object": "model",
+ "created": data[0]["created"],
+ "owned_by": "unsloth-studio",
+ "context_length": 8192,
+ "loaded": True,
+ }
+ ]
+
+
+def test_non_gguf_catalog_dedupe_keeps_a_distinct_same_basename_path(monkeypatch):
+ class _Orchestrator:
+ active_model_name = "/srv/a/publisher/model"
+ models: dict = {}
+ context_length = None
+ max_seq_length = None
+
+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama(loaded = False))
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _Orchestrator())
+
+ resident = _Info("/srv/a/publisher/model", "model", model_id = "publisher-a/model", is_gguf = False)
+ available = _Info(
+ "/srv/b/publisher/model", "model", model_id = "publisher-b/model", is_gguf = False
+ )
+ resident.path = resident.id
+ available.path = available.id
+
+ async def _fake_catalog():
+ return [resident, available]
+
+ monkeypatch.setattr(inf, "_cached_local_catalog", _fake_catalog)
+ monkeypatch.setattr(resolver, "local_servable_model", lambda _info: (False, ()))
+ ids = {entry["id"]: entry for entry in asyncio.run(inf._openai_catalog_objects())}
+
+ assert set(ids) == {"model", "publisher-b/model"}
+ assert ids["model"]["loaded"] is True
+ assert ids["publisher-b/model"]["loaded"] is False
+
+
def test_catalog_lock_is_per_loop():
# Codex P2: a module-level asyncio.Lock ties its waiters to the loop that first
# awaited it, so a second event loop awaiting it in a multi-loop process can
@@ -234,6 +327,42 @@ def test_monitor_active_model_cleans_a_path_with_no_advertised_id(monkeypatch):
assert "/" not in label and ".gguf" not in label
+def test_monitor_reports_nothing_once_a_non_gguf_model_is_unloaded(monkeypatch):
+ # An auto-switch load records the requested repo id on the orchestrator, and an
+ # unload clears active_model_name without clearing that alias. Reading the alias
+ # ungated made the monitor report a ready model with nothing loaded.
+ class _Orchestrator:
+ active_model_name = None
+ _openai_advertised_id = "unsloth/Qwen3-MLX"
+
+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama(loaded = False))
+ monkeypatch.setattr(inf, "_peek_inference_backend", lambda: _Orchestrator())
+ assert inf._monitor_active_model() is None
+
+
+def test_a_non_gguf_model_reports_one_id_across_every_v1_surface(monkeypatch):
+ # /v1/models, GET /v1/models/{id} and the chat-completions response body must all
+ # name an auto-switched model the same way, or a client cannot round-trip the id.
+ class _Orchestrator:
+ active_model_name = "/srv/lmstudio/mlx-community/Qwen3-8B-4bit"
+ _openai_advertised_id = "mlx-community/Qwen3-8B-4bit"
+ models: dict = {}
+ context_length = None
+ max_seq_length = None
+
+ orchestrator = _Orchestrator()
+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _FakeLlama(loaded = False))
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: orchestrator)
+
+ listed = inf._openai_model_objects()[0]["id"]
+ retrieved = asyncio.run(
+ inf.openai_retrieve_model(orchestrator.active_model_name, current_subject = "t")
+ )
+ assert listed == "mlx-community/Qwen3-8B-4bit"
+ assert retrieved["id"] == listed and retrieved["loaded"] is True
+ assert inf._orchestrator_public_model_id(orchestrator) == listed
+
+
def test_lifecycle_label_recovers_the_repo_id_from_an_hf_cache_path():
# An auto-switch load gets the snapshot dir, whose basename is a commit sha.
snap = "/home/me/.cache/huggingface/hub/models--unsloth--gemma-4-E4B-it-GGUF/snapshots/bfc15c3"
@@ -294,7 +423,7 @@ def test_a_loaded_alias_advertises_the_quant_that_is_actually_loaded(monkeypatch
return [alias]
monkeypatch.setattr(inf, "_cached_local_catalog", _fake_catalog)
- monkeypatch.setattr(resolver, "local_gguf_quants", lambda info: ("Q4_K_M", "Q8_0"))
+ monkeypatch.setattr(resolver, "local_servable_model", lambda info: (True, ("Q4_K_M", "Q8_0")))
ids = {m["id"]: m for m in asyncio.run(inf._openai_catalog_objects())}
assert ids["publisher/Qwen3"]["loaded"] is True
assert ids["publisher/Qwen3"]["quant"] == "Q8_0"
@@ -340,7 +469,7 @@ def test_a_transformers_model_does_not_mark_a_gguf_alias_loaded(monkeypatch):
return [alias]
monkeypatch.setattr(inf, "_cached_local_catalog", _fake_catalog)
- monkeypatch.setattr(resolver, "local_gguf_quants", lambda info: ("Q4_K_M",))
+ monkeypatch.setattr(resolver, "local_servable_model", lambda info: (True, ("Q4_K_M",)))
ids = {m["id"]: m for m in asyncio.run(inf._openai_catalog_objects())}
assert ids["publisher/Qwen3"]["loaded"] is False
@@ -358,6 +487,6 @@ def test_an_alias_for_the_resident_weights_is_not_listed_as_unloaded(monkeypatch
return [alias]
monkeypatch.setattr(inf, "_cached_local_catalog", _fake_catalog)
- monkeypatch.setattr(resolver, "local_gguf_quants", lambda info: ("Q4_K_M",))
+ monkeypatch.setattr(resolver, "local_servable_model", lambda info: (True, ("Q4_K_M",)))
ids = {m["id"]: m for m in asyncio.run(inf._openai_catalog_objects())}
assert ids["publisher/Qwen3"]["loaded"] is True
diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.py
index 72eff7e5ef0..12dcb206cb1 100644
--- a/studio/backend/utils/openai_auto_switch_settings.py
+++ b/studio/backend/utils/openai_auto_switch_settings.py
@@ -5,8 +5,10 @@
All off by default so existing API behavior is unchanged:
- ``openai_api_auto_switch_model``: when on, a ``/v1`` request whose ``model``
- names a downloaded local GGUF different from the loaded one transparently
- loads it before serving (llama-swap-style). Unknown names pass through.
+ names a downloaded local model different from the loaded one transparently
+ loads it before serving (llama-swap-style). Covers GGUF through llama.cpp and
+ non-GGUF weights (safetensors, MLX) through the inference orchestrator.
+ Unknown names pass through.
- ``openai_api_auto_download_model``: when on, a ``/v1`` request naming an
undownloaded GGUF repo starts a background download instead of failing.
Gated on auto-switch, which is what serves the model once it lands.
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 0d493c89ee2..775d1eb166f 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -688,7 +688,7 @@ export const ar = {
sectionTitle: "التبديل التلقائي للنموذج (OpenAI API)",
enable: "تبديل النموذج حسب الطلب",
enableDescription:
- "تحميل ملف GGUF منزّل ومذكور في طلب API قبل تلبية الطلب. مُعطّل افتراضيًا.",
+ "تحميل نموذج منزّل ومذكور في طلب API قبل تلبية الطلب. مُعطّل افتراضيًا.",
idleUnload: "التفريغ التلقائي عند الخمول",
idleUnloadDescription:
"حرّر ذاكرة VRAM بعد هذا العدد من ثواني الخمول. تُبقي القيمة 0 النموذج محمّلًا، والحد الأدنى 60 ثانية.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 721b11fa970..d5b30116b58 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -702,7 +702,7 @@ export const de = {
sectionTitle: "Automatischer Modellwechsel (OpenAI API)",
enable: "Modell je Anfrage wechseln",
enableDescription:
- "Lädt vor der Verarbeitung einer API-Anfrage ein darin angegebenes, bereits heruntergeladenes GGUF. Standardmäßig deaktiviert.",
+ "Lädt vor der Verarbeitung einer API-Anfrage ein darin angegebenes, bereits heruntergeladenes Modell. Standardmäßig deaktiviert.",
idleUnload: "Automatisches Entladen bei Inaktivität",
idleUnloadDescription:
"Gibt VRAM nach der angegebenen Anzahl von Sekunden ohne Aktivität frei. Bei 0 bleibt das Modell geladen; der Mindestwert ist 60.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index d0ed479087a..7e66d6cf199 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -687,7 +687,7 @@ export const en = {
sectionTitle: "Model auto-switch (OpenAI API)",
enable: "Switch model by request",
enableDescription:
- "Load a downloaded GGUF named in an API request before serving. Off by default.",
+ "Load a downloaded model named in an API request before serving. Off by default.",
autoDownload: "Download missing models",
autoDownloadDescription:
"Fetch a GGUF named in an API request that is not downloaded yet. Anyone with an API key can then use disk and bandwidth.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 590ff14bdc2..61f25bf0c90 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -698,7 +698,7 @@ export const es = {
sectionTitle: "Cambio automático de modelo (API de OpenAI)",
enable: "Cambiar de modelo según la solicitud",
enableDescription:
- "Si una solicitud de la API especifica un GGUF que ya está descargado, carga ese modelo antes de responder. Desactivado por defecto.",
+ "Si una solicitud de la API especifica un modelo que ya está descargado, carga ese modelo antes de responder. Desactivado por defecto.",
idleUnload: "Liberar automáticamente por inactividad",
idleUnloadDescription:
"Libera la VRAM después de este número de segundos de inactividad. El valor 0 mantiene el modelo cargado; el mínimo es 60.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index a29a689e24f..812a47a8c5b 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -700,7 +700,7 @@ export const fr = {
sectionTitle: "Changement automatique de modèle (API OpenAI)",
enable: "Changer de modèle par requête",
enableDescription:
- "Charger, avant de répondre, un GGUF téléchargé indiqué dans une requête API. Désactivé par défaut.",
+ "Charger, avant de répondre, un modèle téléchargé indiqué dans une requête API. Désactivé par défaut.",
idleUnload: "Déchargement automatique en cas d'inactivité",
idleUnloadDescription:
"Libérer la VRAM après ce nombre de secondes d’inactivité. 0 maintient le modèle chargé ; le minimum est 60.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index dd0f87ee81e..4e0694cc279 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -692,7 +692,7 @@ export const hi = {
sectionTitle: "मॉडल ऑटो-स्विच (OpenAI API)",
enable: "अनुरोध के अनुसार मॉडल बदलें",
enableDescription:
- "API अनुरोध में दिए गए डाउनलोड किए गए GGUF को सेवा देने से पहले लोड करें। डिफ़ॉल्ट रूप से बंद।",
+ "API अनुरोध में दिए गए डाउनलोड किए गए मॉडल को सेवा देने से पहले लोड करें। डिफ़ॉल्ट रूप से बंद।",
idleUnload: "निष्क्रिय ऑटो-अनलोड",
idleUnloadDescription:
"इतने सेकंड तक निष्क्रिय रहने के बाद VRAM खाली करें। 0 पर मॉडल लोड रहता है; न्यूनतम 60 सेकंड।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index b47e6ca341f..f5b9fec3ac9 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -665,7 +665,7 @@ export const it = {
sectionTitle: "Cambio automatico del modello (API OpenAI)",
enable: "Cambia modello in base alla richiesta",
enableDescription:
- "Carica un GGUF già scaricato indicato in una richiesta API prima di rispondere. Disattivato per impostazione predefinita.",
+ "Carica un modello già scaricato indicato in una richiesta API prima di rispondere. Disattivato per impostazione predefinita.",
autoDownload: "Scarica i modelli mancanti",
autoDownloadDescription:
"Scarica un GGUF indicato in una richiesta API se non è ancora presente. Chiunque abbia una chiave API potrà così consumare spazio su disco e banda.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 1d58e5fd3f7..3f1077686c6 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -683,7 +683,7 @@ export const ja = {
sectionTitle: "モデル自動切り替え (OpenAI API)",
enable: "リクエストごとにモデルを切り替え",
enableDescription:
- "API リクエストで指定されたダウンロード済みの GGUF を、応答前に読み込みます。デフォルトではオフです。",
+ "API リクエストで指定されたダウンロード済みのモデルを、応答前に読み込みます。デフォルトではオフです。",
idleUnload: "アイドル時の自動アンロード",
idleUnloadDescription:
"指定した秒数だけアイドル状態が続くと、モデルをアンロードして VRAM を解放します。0 にすると読み込んだままになります。最小値は 60 秒です。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 4b18b5b050e..f79c74fd56e 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -686,7 +686,7 @@ export const ko = {
sectionTitle: "모델 자동 전환 (OpenAI API)",
enable: "요청에 따라 모델 전환",
enableDescription:
- "API 요청에 지정된 GGUF가 다운로드되어 있으면 응답 전에 해당 모델을 불러옵니다. 기본값은 꺼짐입니다.",
+ "API 요청에 지정된 모델이 다운로드되어 있으면 응답 전에 해당 모델을 불러옵니다. 기본값은 꺼짐입니다.",
idleUnload: "유휴 시 자동 해제",
idleUnloadDescription:
"지정한 유휴 시간(초)이 지나면 모델을 해제하여 VRAM을 확보합니다. 다음 요청 시 다시 불러옵니다. 0으로 설정하면 계속 로드된 상태로 유지됩니다. 최소 60초입니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 5388e135542..52b3821a3c0 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -694,7 +694,7 @@ export const ptBR = {
sectionTitle: "Troca automática de modelo (API OpenAI)",
enable: "Trocar de modelo por requisição",
enableDescription:
- "Carrega, antes de responder, um GGUF baixado indicado em uma requisição da API. Desativado por padrão.",
+ "Carrega, antes de responder, um modelo baixado indicado em uma requisição da API. Desativado por padrão.",
idleUnload: "Descarregamento automático por inatividade",
idleUnloadDescription:
"Libera a VRAM após esta quantidade de segundos de inatividade. 0 mantém o modelo carregado; o mínimo é 60.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index cc8fb4cd54e..6abe5cafe52 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -693,7 +693,7 @@ export const ru = {
sectionTitle: "Автопереключение модели (OpenAI API)",
enable: "Переключать модель по запросу",
enableDescription:
- "Загружать скачанную модель GGUF, указанную в запросе к API, перед обработкой запроса. По умолчанию выключено.",
+ "Загружать скачанную модель, указанную в запросе к API, перед обработкой запроса. По умолчанию выключено.",
idleUnload: "Автовыгрузка при простое",
idleUnloadDescription:
"Освобождать VRAM после указанного числа секунд простоя. 0 оставляет модель загруженной; минимальное значение: 60.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 295eb260482..909e7be963e 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -673,7 +673,7 @@ export const zhCN = {
sectionTitle: "模型自动切换(OpenAI API)",
enable: "按请求切换模型",
enableDescription:
- "在提供服务前,加载 API 请求中指定的已下载 GGUF。默认关闭。",
+ "在提供服务前,加载 API 请求中指定的已下载模型。默认关闭。",
idleUnload: "空闲自动卸载",
idleUnloadDescription:
"空闲达到该秒数后释放 VRAM。设为 0 则保持加载,最小值为 60 秒。",
diff --git a/tests/studio/probe_dismiss_guard.py b/tests/studio/probe_dismiss_guard.py
index 6c050661f80..f6669ee4906 100644
--- a/tests/studio/probe_dismiss_guard.py
+++ b/tests/studio/probe_dismiss_guard.py
@@ -75,10 +75,10 @@ and too much nowhere:
non-focusable element and the probe FAILS rather than falling back if none
exists, because a probe that cannot tell you it missed is worse than none.
-Every verdict is a DOM fact: did the assistant message count go down, did the menu close, did
-the watched click land. Clicks go through `page.mouse` / `page.touchscreen`, real hit tests that
-honour pointer-events. `locator.click()` throws on interception and `element.click()` skips hit
-testing, and each would lie in a different direction.
+Every verdict is a DOM fact: did the assistant message count go down, did the menu close or
+reopen from its focused trigger, did the watched click land. Clicks go through `page.mouse` /
+`page.touchscreen`, real hit tests that honour pointer-events. `locator.click()` throws on
+interception and `element.click()` skips hit testing, and each would lie in a different direction.
Run against the PR head AND the merge base. On the merge base these menus are modal, the body
carries `pointer-events: none`, and no variant reaches the control at all.
@@ -304,7 +304,6 @@ async def one_case(
if not rect:
return {"case": case, "error": "no Delete button"}
x, y = rect["x"], rect["y"]
-
if case == "quick":
await page.mouse.move(x, y)
await page.mouse.down()