Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: gate image input on effective vision capability (#5492)
Etherll11e5b5882783
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex cf46d580af5..286fddda11b 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -2215,6 +2215,35 @@ class LlamaCppBackend:logger.warning(f"Could not download mmproj: {e}")return None+ def _resolve_launch_mmproj_path(+ self,+ *,+ model_path: str,+ mmproj_path: Optional[str],+ ) -> Optional[str]:+ """Return mmproj_path iff it exists on disk AND matches the model family.++ Returns None if mmproj_path is None, missing on disk, or family-mismatched.+ """+ if not mmproj_path:+ return None++ mmproj = Path(mmproj_path)+ if not mmproj.is_file():+ logger.warning(f"mmproj file not found: {mmproj_path}")+ return None++ from utils.models.model_config import mmproj_matches_model_family++ if not mmproj_matches_model_family(model_path, str(mmproj)):+ logger.warning(+ f"mmproj does not match model family: model={Path(model_path).name} "+ f"mmproj={mmproj.name}"+ )+ return None++ return str(mmproj)+# ── Lifecycle ─────────────────────────────────────────────────def load_model(@@ -2518,6 +2547,20 @@ class LlamaCppBackend:gpu_indices, use_fit = None, Trueeffective_ctx = n_ctx # fall back to original+ launch_mmproj_path = self._resolve_launch_mmproj_path(+ model_path = model_path,+ mmproj_path = mmproj_path,+ )+ # Need both a resolved mmproj AND the config vision flag; a stray+ # mmproj passing the family-name heuristic must not flip a non-VLM+ # GGUF into vision mode.+ effective_is_vision = bool(launch_mmproj_path) and bool(is_vision)+ if is_vision and not effective_is_vision:+ logger.warning(+ "Vision-capable GGUF loaded without a usable mmproj; "+ "image input will be disabled for this session"+ )+cmd = [binary,"-m",@@ -2610,7 +2653,7 @@ class LlamaCppBackend:# Auto-promote unset/"default" to draft-mtp on MTP GGUFs.if (is_mtp_model- and not is_vision+ and not effective_is_visionand not user_owns_spec_typeand normalized_spec in (None, "", "default")):@@ -2619,7 +2662,11 @@ class LlamaCppBackend:# User --spec-type wins (it accumulates if repeated).normalized_spec = Noneself._speculative_type = None- if normalized_spec and normalized_spec != "off" and not is_vision:+ if (+ normalized_spec+ and normalized_spec != "off"+ and not effective_is_vision+ ):if normalized_spec == "default":cmd.append("--spec-default")self._speculative_type = "default"@@ -2739,24 +2786,9 @@ class LlamaCppBackend:)logger.info(f"Reasoning model: {reasoning_kw} by default")- if mmproj_path:- if not Path(mmproj_path).is_file():- logger.warning(f"mmproj file not found: {mmproj_path}")- else:- # #5347 guard for paths that bypass detect_mmproj_file.- from utils.models.model_config import (- mmproj_matches_model_family,- )-- if not mmproj_matches_model_family(model_path, mmproj_path):- logger.warning(- f"Skipping mmproj with mismatched family: "- f"model={Path(model_path).name}, "- f"mmproj={Path(mmproj_path).name}"- )- else:- cmd.extend(["--mmproj", mmproj_path])- logger.info(f"Using mmproj for vision: {mmproj_path}")+ if launch_mmproj_path and effective_is_vision:+ cmd.extend(["--mmproj", launch_mmproj_path])+ logger.info(f"Using mmproj for vision: {launch_mmproj_path}")# Option C: add --api-key for direct client access when enabledimport os as _os@@ -2954,7 +2986,7 @@ class LlamaCppBackend:self._hf_variant = Noneelse:self._hf_variant = None- self._is_vision = is_vision+ self._is_vision = effective_is_visionself._model_identifier = model_identifier# Store the effective (possibly capped) context separately.diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 4443c5cc117..607245467cb 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -826,7 +826,7 @@ async def load_model(display_name = model_log_labelif native_grant_backedelse config.display_name,- is_vision = config.is_vision,+ is_vision = llama_backend.is_vision,is_lora = False,is_gguf = True,is_audio = _gguf_is_audio,@@ -3575,6 +3575,17 @@ async def _responses_stream(),)+ # Direct pass-through bypasses the openai_chat_completions image gate.+ if not llama_backend.is_vision and any(+ isinstance(m.content, list)+ and any(isinstance(p, ImageContentPart) for p in m.content)+ for m in messages+ ):+ raise HTTPException(+ status_code = 400,+ detail = "Image provided but current GGUF model does not support vision.",+ )+body = _build_openai_passthrough_body(chat_req, backend_ctx = llama_backend.context_length)diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex aeca357f1cf..42a9ddc29b8 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -31,6 +31,7 @@ import {isCustomProviderType,loadExternalProviders,parseExternalModelId,+ providerTypeSupportsVision,supportsProviderPromptCaching,toExternalBackendProviderType,} from "../external-providers";@@ -46,6 +47,7 @@ import {import { useChatRuntimeStore } from "../stores/chat-runtime-store";import { isMultimodalResponse } from "../types/api";import type { ChatModelSummary } from "../types/runtime";+import { getImageInputUnavailableReason } from "../utils/image-input-support";import {hasClosedThinkTag,parseAssistantContent,@@ -779,6 +781,37 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {}const imageBase64 = findLatestUserImageBase64(messages);const audioBase64 = findLatestUserAudioBase64(messages);++ // Block when ANY image is in the outbound payload (current or+ // prior turns) and the loaded model can't process images. Keeps+ // the gate simple: once a chat contains an image, a non-vision+ // model can't respond — user starts a new chat to switch models.+ if (imageBase64) {+ const activeModel = runtime.models.find(+ (m) => m.id === params.checkpoint,+ );+ const imageGateReason = getImageInputUnavailableReason({+ activeModel,+ isExternalModel: isExternalRequest,+ externalSupportsVision: providerTypeSupportsVision(+ externalProvider?.providerType,+ ),+ externalModelLabel: externalSelection?.modelId ?? null,+ loadedIsMultimodal: runtime.loadedIsMultimodal,+ modelLoaded: !!params.checkpoint && !runtime.modelLoading,+ });+ if (imageGateReason) {+ toast.error(imageGateReason);+ // Flip the per-thread running flag on→off so the compare-mode+ // waitForRunEnd resolves instead of hanging. This gate fires+ // before the streaming path's setThreadRunning(true), so the+ // wait promise would otherwise never settle.+ const gatedThreadKey = resolvedThreadId || "__default";+ runtime.setThreadRunning(gatedThreadKey, true);+ runtime.setThreadRunning(gatedThreadKey, false);+ throw new Error(imageGateReason);+ }+ }// Clear pending audio from store after extracting (consumed on send)if (audioBase64) {const audioName = runtime.pendingAudioName;diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.tsindex d455ff138e3..c71949a16ce 100644--- a/studio/frontend/src/features/chat/external-providers.ts+++ b/studio/frontend/src/features/chat/external-providers.ts@@ -49,6 +49,30 @@ export function supportsProviderReasoningToggle();}+// Known text-only providers on their main chat endpoint.+const NON_VISION_PROVIDER_TYPES = new Set<string>([+ "cohere",+ "deepseek",+ "mistral",+]);+// Providers whose vision-tier model selection accepts images.+const VISION_CAPABLE_PROVIDER_TYPES = new Set<string>([+ "openai",+ "anthropic",+ "gemini",+ "openrouter",+]);++// false = known text-only, true = known vision, null = unknown (default-allow).+export function providerTypeSupportsVision(+ providerType: string | null | undefined,+): boolean | null {+ if (providerType == null) return null;+ if (NON_VISION_PROVIDER_TYPES.has(providerType)) return false;+ if (VISION_CAPABLE_PROVIDER_TYPES.has(providerType)) return true;+ return null;+}+export const CUSTOM_BACKEND_PROVIDER_TYPE = "openai";export const LEGACY_CUSTOM_PROVIDER_TYPE = "custom";diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex b019fd2d4d1..ca9eb2dcf60 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -32,9 +32,15 @@ import {useRef,} from "react";import { extractText, getDocumentProxy } from "unpdf";+import { toast } from "sonner";import { authFetch } from "@/features/auth";import { createOpenAIStreamAdapter } from "./api/chat-adapter";import { db } from "./db";+import {+ loadExternalProviders,+ parseExternalModelId,+ providerTypeSupportsVision,+} from "./external-providers";import { useChatRuntimeStore } from "./stores/chat-runtime-store";import type { MessageRecord, ModelType } from "./types";import {@@ -42,6 +48,7 @@ import {markChatThreadDeleted,} from "./utils/chat-thread-tombstones";import { syncExportedRepositoryToDexie } from "./utils/delete-thread-message";+import { getImageInputUnavailableReason } from "./utils/image-input-support";const DEFAULT_SUGGESTIONS = [{@@ -78,6 +85,37 @@ class VisionImageAdapter implements AttachmentAdapter {accept = "image/jpeg,image/png,image/webp,image/gif";async add({ file }: { file: File }): Promise<PendingAttachment> {+ const state = useChatRuntimeStore.getState();+ const checkpoint = state.params.checkpoint;+ const activeModel = state.models.find((m) => m.id === checkpoint);+ const externalSelection = parseExternalModelId(checkpoint);+ const isExternalModel = externalSelection !== null;+ const modelLoaded = !!checkpoint && !state.modelLoading;+ let externalSupportsVision: boolean | null = null;+ let externalModelLabel: string | null = null;+ if (externalSelection !== null) {+ const providers = loadExternalProviders();+ const provider = providers.find(+ (p) => p.id === externalSelection.providerId,+ );+ externalSupportsVision = providerTypeSupportsVision(+ provider?.providerType,+ );+ externalModelLabel = externalSelection.modelId;+ }+ const unavailableReason = getImageInputUnavailableReason({+ activeModel,+ isExternalModel,+ externalSupportsVision,+ externalModelLabel,+ loadedIsMultimodal: state.loadedIsMultimodal,+ modelLoaded,+ });+ if (unavailableReason) {+ toast.error(unavailableReason);+ throw new Error(unavailableReason);+ }+const maxSize = 20 * 1024 * 1024;if (file.size > maxSize) {throw new Error("Image size exceeds 20MB limit");diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex e255c1c2b01..ac23356180e 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -14,11 +14,13 @@ import {import { applyQwenThinkingParams } from "@/features/chat/utils/qwen-params";import { AUDIO_ACCEPT, MAX_AUDIO_SIZE, fileToBase64 } from "@/lib/audio-utils";import { isTauri } from "@/lib/api-base";+import { isMultimodalResponse } from "./types/api";+import { getImageInputUnavailableReason } from "./utils/image-input-support";import { useAui } from "@assistant-ui/react";import { ArrowUpIcon, GlobeIcon, HeadphonesIcon, LightbulbIcon, LightbulbOffIcon, MicIcon, PlusIcon, SquareIcon, XIcon } from "lucide-react";import { toast } from "sonner";import { loadModel, validateModel } from "./api/chat-api";-import { parseExternalModelId } from "./external-providers";+import { parseExternalModelId, providerTypeSupportsVision } from "./external-providers";import { useExternalProvidersStore } from "./stores/external-providers-store";import {type ReasoningEffort,@@ -294,6 +296,7 @@ export function SharedComposer({const modelLoaded = useChatRuntimeStore((s) => !!s.params.checkpoint && !s.modelLoading,);+ const loadedIsMultimodal = useChatRuntimeStore((s) => s.loadedIsMultimodal);const supportsReasoning = useChatRuntimeStore((s) => s.supportsReasoning);const reasoningAlwaysOn = useChatRuntimeStore((s) => s.reasoningAlwaysOn);const reasoningEnabled = useChatRuntimeStore((s) => s.reasoningEnabled);@@ -318,10 +321,28 @@ export function SharedComposer({(s) => s.lastOpenRouterChosenModel,);const externalSelection = parseExternalModelId(checkpoint);+ const isExternalModel = externalSelection !== null;const selectedExternalProvider =externalSelection != null? externalProviders.find((p) => p.id === externalSelection.providerId): undefined;+ const imageUnavailableReason = getImageInputUnavailableReason({+ activeModel,+ isExternalModel,+ externalSupportsVision: providerTypeSupportsVision(+ selectedExternalProvider?.providerType,+ ),+ externalModelLabel: externalSelection?.modelId ?? null,+ loadedIsMultimodal,+ modelLoaded,+ });+ const isCompareMode = Boolean(model1?.id || model2?.id);+ // Attach-time gate. Compare mode defers to send: the catalog can lag+ // behind a model's real capabilities (e.g., a GGUF whose mmproj+ // arrives after the catalog snapshot), and we only sync the models[]+ // entry after ensureModelLoaded runs at send time. Single mode uses+ // the loaded model's runtime capability.+ const attachUnavailableReason = isCompareMode ? null : imageUnavailableReason;const effectiveExternalModelId =selectedExternalProvider?.providerType === "openrouter" &&externalSelection?.modelId === "openrouter/free" &&@@ -422,6 +443,7 @@ export function SharedComposer({const addFiles = useCallback((files: FileList | null) => {if (!files?.length) return;const next: PendingImage[] = [];+ let droppedImageForUnavailable = false;for (let i = 0; i < files.length; i++) {const file = files[i];if (!file) continue;@@ -436,10 +458,17 @@ export function SharedComposer({// Handle image filesif (!file.type.match(/^image\/(jpeg|png|webp|gif)$/i)) continue;if (file.size > MAX_IMAGE_SIZE) continue;+ if (attachUnavailableReason) {+ droppedImageForUnavailable = true;+ continue;+ }next.push({ id: crypto.randomUUID(), file });}+ if (droppedImageForUnavailable && attachUnavailableReason) {+ toast.error(attachUnavailableReason);+ }setPendingImages((prev) => [...prev, ...next]);- }, [setPendingAudioStore]);+ }, [setPendingAudioStore, attachUnavailableReason]);const removePendingImage = useCallback((id: string) => {setPendingImages((prev) => prev.filter((p) => p.id !== id));@@ -455,6 +484,21 @@ export function SharedComposer({const msg = text.trim();if (!msg && pendingImages.length === 0 && !pendingAudio) return;+ const hasCompareHandles = Boolean(+ handlesRef.current["model1"] || handlesRef.current["model2"],+ );+ const isGeneralizedCompare =+ hasCompareHandles && Boolean(model1?.id || model2?.id);++ if (pendingImages.length > 0 && !isGeneralizedCompare && imageUnavailableReason) {+ // Single mode: the loaded model's runtime capability is known+ // here. Compare mode defers — each ensureModelLoaded below sets+ // loadedIsMultimodal for its side, and the chat-adapter's+ // pre-stream gate runs per-side against that fresh state.+ toast.error(imageUnavailableReason);+ return;+ }+const content: CompareMessagePart[] = [];for (const { file } of pendingImages) {try {@@ -479,8 +523,6 @@ export function SharedComposer({textareaRef.current?.focus();// Generalized compare: load each model before dispatching to its side- const hasCompareHandles = Boolean(handlesRef.current["model1"] || handlesRef.current["model2"]);- const isGeneralizedCompare = hasCompareHandles && Boolean(model1?.id || model2?.id);if (isGeneralizedCompare) {const store = useChatRuntimeStore.getState();const maxSeqLength = store.params.maxSeqLength;@@ -541,7 +583,36 @@ export function SharedComposer({reasoningStyle: resp.reasoning_style ?? "enable_thinking",supportsPreserveThinking: resp.supports_preserve_thinking ?? false,supportsTools: resp.supports_tools ?? false,+ loadedIsMultimodal: isMultimodalResponse(resp),});+ // Sync the models[] entry with the load response so the+ // attach/send gates read fresh capabilities. /api/models/list+ // can lag behind a model's actual state (e.g., a GGUF whose+ // mmproj was downloaded after the catalog snapshot).+ const currentModels = useChatRuntimeStore.getState().models;+ const idx = currentModels.findIndex((m) => m.id === sel.id);+ const synced = {+ isVision: Boolean(resp.is_vision),+ isGguf: Boolean(resp.is_gguf),+ isAudio: Boolean(resp.is_audio),+ audioType: resp.audio_type ?? null,+ hasAudioInput: Boolean(resp.has_audio_input),+ };+ if (idx === -1) {+ store.setModels([+ ...currentModels,+ {+ id: sel.id,+ name: resp.display_name ?? sel.id,+ isLora: sel.isLora,+ ...synced,+ },+ ]);+ } else {+ const next = [...currentModels];+ next[idx] = { ...next[idx], ...synced };+ store.setModels(next);+ }return resp.status;}@@ -713,7 +784,13 @@ export function SharedComposer({variant="ghost"size="icon"className="size-8.5 rounded-full p-1 font-semibold text-xs hover:bg-muted-foreground/15 dark:border-muted-foreground/15 dark:hover:bg-muted-foreground/30"- onClick={() => fileInputRef.current?.click()}+ onClick={() => {+ // The picker accepts both image and audio. Don't gate the+ // button on image-availability — addFiles still filters+ // image files per-file when the loaded model can't take+ // them, while audio attach always works.+ fileInputRef.current?.click();+ }}aria-label="Add Attachment"><PlusIcon className="size-5 stroke-[1.5px]" />diff --git a/studio/frontend/src/features/chat/utils/image-input-support.ts b/studio/frontend/src/features/chat/utils/image-input-support.tsnew file mode 100644index 00000000000..fb39303e296--- /dev/null+++ b/studio/frontend/src/features/chat/utils/image-input-support.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { ChatModelSummary } from "../types/runtime";++export function getImageInputUnavailableReason({+ activeModel,+ isExternalModel,+ externalSupportsVision,+ externalModelLabel,+ loadedIsMultimodal,+ modelLoaded,+}: {+ activeModel?: ChatModelSummary;+ isExternalModel: boolean;+ // true/false = caller knows; null/undefined = unknown (default-allow).+ // External selections aren't in runtime.models[], so callers should+ // resolve provider-type capability and pass it here.+ externalSupportsVision?: boolean | null;+ // Fallback toast label when activeModel is missing.+ externalModelLabel?: string | null;+ loadedIsMultimodal: boolean;+ modelLoaded: boolean;+}): string | null {+ if (isExternalModel) {+ const explicitlyNonVision =+ externalSupportsVision === false ||+ (activeModel &&+ activeModel.isVision === false &&+ !activeModel.isAudio &&+ !activeModel.hasAudioInput);+ if (explicitlyNonVision) {+ const label =+ activeModel?.name ||+ externalModelLabel ||+ activeModel?.id ||+ "Current model";+ return `${label} cannot accept images.`;+ }+ return null;+ }+ if (!modelLoaded) return "Load a model before adding images.";+ // loadedIsMultimodal is true for vision OR audio. Can't tell them apart+ // from that one flag, so only block when activeModel confirms+ // audio-only: audio capability set AND isVision === false. Otherwise+ // trust the load response. The models-list entry might be stale, or+ // not even there yet (gets auto-injected after load).+ if (loadedIsMultimodal) {+ const isAudioOnly =+ Boolean(activeModel?.isAudio || activeModel?.hasAudioInput) &&+ activeModel?.isVision === false;+ if (!isAudioOnly) return null;+ }++ const label = activeModel?.name || activeModel?.id || "Current model";+ const suffix = activeModel?.isGguf+ ? " with a valid mmproj before attaching images."+ : " before attaching images.";+ return `${label} cannot accept images. Load a vision-capable model${suffix}`;+}